com.alibaba.dubbo.remoting.Channel Java Examples

The following examples show how to use com.alibaba.dubbo.remoting.Channel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DeprecatedTelnetCodec.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
protected boolean isClientSide(Channel channel) {
    String side = (String) channel.getAttribute(Constants.SIDE_KEY);
    if ("client".equals(side)) {
        return true;
    } else if ("server".equals(side)) {
        return false;
    } else {
        InetSocketAddress address = channel.getRemoteAddress();
        URL url = channel.getUrl();
        boolean client = url.getPort() == address.getPort()
            && NetUtils.filterLocalHost(url.getIp()).equals(
            NetUtils.filterLocalHost(address.getAddress()
                                         .getHostAddress()));
        channel.setAttribute(Constants.SIDE_KEY, client ? "client"
            : "server");
        return client;
    }
}
 
Example #2
Source File: DubboCodec.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Override
protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException {
    RpcInvocation inv = (RpcInvocation) data;

    out.writeUTF(inv.getAttachment(Constants.DUBBO_VERSION_KEY, DUBBO_VERSION));
    out.writeUTF(inv.getAttachment(Constants.PATH_KEY));
    out.writeUTF(inv.getAttachment(Constants.VERSION_KEY));

    out.writeUTF(inv.getMethodName());

    // NOTICE modified by lishen
    // TODO
    if (getSerialization(channel) instanceof OptimizedSerialization && !containComplexArguments(inv)) {
        out.writeInt(inv.getParameterTypes().length);
    } else {
        out.writeInt(-1);
        out.writeUTF(ReflectUtils.getDesc(inv.getParameterTypes()));
    }

    Object[] args = inv.getArguments();
    if (args != null)
        for (int i = 0; i < args.length; i++){
            out.writeObject(encodeInvocationArgument(channel, inv, i));
        }
    out.writeObject(inv.getAttachments());
}
 
Example #3
Source File: DeprecatedTelnetCodec.java    From dubbox with Apache License 2.0 6 votes vote down vote up
protected boolean isClientSide(Channel channel) {
    String side = (String) channel.getAttribute(Constants.SIDE_KEY);
    if ("client".equals(side)) {
        return true;
    } else if ("server".equals(side)) {
        return false;
    } else {
        InetSocketAddress address = channel.getRemoteAddress();
        URL url = channel.getUrl();
        boolean client = url.getPort() == address.getPort()
            && NetUtils.filterLocalHost(url.getIp()).equals(
            NetUtils.filterLocalHost(address.getAddress()
                                         .getHostAddress()));
        channel.setAttribute(Constants.SIDE_KEY, client ? "client"
            : "server");
        return client;
    }
}
 
Example #4
Source File: HeaderExchangeHandlerTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void test_received_request_oneway() throws RemotingException{
    final Channel mchannel = new MockedChannel();
    
    final Person requestdata = new Person("charles");
    Request request = new Request();
    request.setTwoWay(false);
    request.setData(requestdata);
    
    ExchangeHandler exhandler = new MockedExchangeHandler(){
        public void received(Channel channel, Object message) throws RemotingException {
            Assert.assertEquals(requestdata, message);
        }
    };
    HeaderExchangeHandler hexhandler = new HeaderExchangeHandler(exhandler);
    hexhandler.received(mchannel, request);
}
 
Example #5
Source File: HeaderExchangeHandlerTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Test
public void test_received_request_twoway_error_reqeustBroken() throws RemotingException {
    final Request request = new Request();
    request.setTwoWay(true);
    request.setData(new BizException());
    request.setBroken(true);

    final AtomicInteger count = new AtomicInteger(0);
    final Channel mchannel = new MockedChannel() {
        @Override
        public void send(Object message) throws RemotingException {
            Response res = (Response) message;
            Assert.assertEquals(request.getId(), res.getId());
            Assert.assertEquals(request.getVersion(), res.getVersion());
            Assert.assertEquals(Response.BAD_REQUEST, res.getStatus());
            Assert.assertNull(res.getResult());
            Assert.assertTrue(res.getErrorMessage().contains(BizException.class.getName()));
            count.incrementAndGet();
        }
    };
    HeaderExchangeHandler hexhandler = new HeaderExchangeHandler(new MockedExchangeHandler());
    hexhandler.received(mchannel, request);
    Assert.assertEquals(1, count.get());
}
 
Example #6
Source File: ListTelnetHandlerTest.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testListDefault() throws RemotingException {
    mockInvoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(mockInvoker.getInterface()).andReturn(DemoService.class).anyTimes();
    EasyMock.expect(mockInvoker.getUrl()).andReturn(URL.valueOf("dubbo://127.0.0.1:20885/demo")).anyTimes();
    EasyMock.expect(mockInvoker.invoke((Invocation) EasyMock.anyObject())).andReturn(new RpcResult("ok")).anyTimes();
    mockChannel = EasyMock.createMock(Channel.class);
    EasyMock.expect(mockChannel.getAttribute("telnet.service")).andReturn("com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoService").anyTimes();
    EasyMock.replay(mockChannel, mockInvoker);
    DubboProtocol.getDubboProtocol().export(mockInvoker);
    String result = list.telnet(mockChannel, "");
    assertEquals("Use default service com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoService.\r\n\r\n"
                 + methodsName, result);
    EasyMock.reset(mockChannel);
}
 
Example #7
Source File: LogTelnetHandlerTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Test
public void testChangeLogLevel() throws RemotingException {
    mockChannel = EasyMock.createMock(Channel.class);
    EasyMock.replay(mockChannel);
    String result = log.telnet(mockChannel, "error");
    assertTrue(result.contains("\r\nCURRENT LOG LEVEL:ERROR"));
    String result2 = log.telnet(mockChannel, "warn");
    assertTrue(result2.contains("\r\nCURRENT LOG LEVEL:WARN"));
    EasyMock.reset(mockChannel);
}
 
Example #8
Source File: DecodeableRpcResult.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public DecodeableRpcResult(Channel channel, Response response, InputStream is, Invocation invocation, byte id) {
    Assert.notNull(channel, "channel == null");
    Assert.notNull(response, "response == null");
    Assert.notNull(is, "inputStream == null");
    this.channel = channel;
    this.response = response;
    this.inputStream = is;
    this.invocation = invocation;
    this.serializationType = id;
}
 
Example #9
Source File: HeaderExchangeServer.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<ExchangeChannel> getExchangeChannels() {
    Collection<ExchangeChannel> exchangeChannels = new ArrayList<ExchangeChannel>();
    Collection<Channel> channels = server.getChannels();
    if (channels != null && !channels.isEmpty()) {
        for (Channel channel : channels) {
            exchangeChannels.add(HeaderExchangeChannel.getOrAddChannel(channel));
        }
    }
    return exchangeChannels;
}
 
Example #10
Source File: CodecAdapter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {
    byte[] bytes = new byte[buffer.readableBytes()];
    int savedReaderIndex = buffer.readerIndex();
    buffer.readBytes(bytes);
    UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(bytes);
    Object result = codec.decode(channel, is);
    buffer.readerIndex(savedReaderIndex + is.position());
    return result == Codec.NEED_MORE_INPUT ? DecodeResult.NEED_MORE_INPUT : result;
}
 
Example #11
Source File: TraceFilter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public static void addTracer(Class<?> type, String method, Channel channel, int max) {
    channel.setAttribute(TRACE_MAX, max);
    channel.setAttribute(TRACE_COUNT, new AtomicInteger());
    String key = method != null && method.length() > 0 ? type.getName() + "." + method : type.getName();
    Set<Channel> channels = tracers.get(key);
    if (channels == null) {
        tracers.putIfAbsent(key, new ConcurrentHashSet<Channel>());
        channels = tracers.get(key);
    }
    channels.add(channel);
}
 
Example #12
Source File: HeaderExchangeClient.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private void startHeatbeatTimer() {
    stopHeartbeatTimer();
    if ( heartbeat > 0 ) {
        heatbeatTimer = scheduled.scheduleWithFixedDelay(
                new HeartBeatTask( new HeartBeatTask.ChannelProvider() {
                    public Collection<Channel> getChannels() {
                        return Collections.<Channel>singletonList( HeaderExchangeClient.this );
                    }
                }, heartbeat, heartbeatTimeout),
                heartbeat, heartbeat, TimeUnit.MILLISECONDS );
    }
}
 
Example #13
Source File: CodecAdapter.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {
    byte[] bytes = new byte[buffer.readableBytes()];
    int savedReaderIndex = buffer.readerIndex();
    buffer.readBytes(bytes);
    UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(bytes);
    Object result = codec.decode(channel, is);
    buffer.readerIndex(savedReaderIndex + is.position());
    return result == Codec.NEED_MORE_INPUT ? DecodeResult.NEED_MORE_INPUT : result;
}
 
Example #14
Source File: TelnetCodec.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException {
    if (message instanceof String) {
        if (isClientSide(channel)) {
            message = message + "\r\n";
        }
        byte[] msgData = ((String) message).getBytes(getCharset(channel).name());
        buffer.writeBytes(msgData);
    } else {
        super.encode(channel, buffer, message);
    }
}
 
Example #15
Source File: ExchangeCodecTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Test
public void test_Decode_Error_Length() throws IOException {
    byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 0x02, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    Person person = new Person();
    byte[] request = getRequestBytes(person, header);

    Channel channel = getServerSideChannel(url);
    byte[] baddata = new byte[]{1, 2};
    ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(join(request, baddata));
    Response obj = (Response) codec.decode(channel, buffer);
    Assert.assertEquals(person, obj.getResult());
    //only decode necessary bytes
    Assert.assertEquals(request.length, buffer.readerIndex());
}
 
Example #16
Source File: TelnetCodecTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
protected void testDecode_assertEquals(byte[] request,Object ret, boolean isServerside) throws IOException{
    //init channel
    Channel channel = isServerside? getServerSideChannel(url) : getCliendSideChannel(url);
    //init request string
    ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request);

    //decode
    Object obj = codec.decode(channel, buffer);
    Assert.assertEquals(ret, obj);
}
 
Example #17
Source File: ThriftProtocol.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@Override
public void received( Channel channel, Object message ) throws RemotingException {
    if ( message instanceof Invocation ) {
        reply( ( ExchangeChannel ) channel, message );
    } else {
        super.received( channel, message );
    }
}
 
Example #18
Source File: AllChannelHandler.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
public void caught(Channel channel, Throwable exception) throws RemotingException {
    ExecutorService cexecutor = getExecutorService();
    try {
        cexecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.CAUGHT, exception));
    } catch (Throwable t) {
        throw new ExecutionException("caught event", channel, getClass() + " error when process caught event .", t);
    }
}
 
Example #19
Source File: TelnetCodecTest.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
protected void testDecode_assertEquals(byte[] request,Object ret, boolean isServerside) throws IOException{
    //init channel
    Channel channel = isServerside? getServerSideChannel(url) : getCliendSideChannel(url);
    //init request string
    ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request);

    //decode
    Object obj = codec.decode(channel, buffer);
    Assert.assertEquals(ret, obj);
}
 
Example #20
Source File: ExecutionChannelHandler.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
public void received(Channel channel, Object message) throws RemotingException {
    ExecutorService cexecutor = getExecutorService();
    if (message instanceof Request) {
        try {
            cexecutor.execute(new ChannelEventRunnable(channel, handler, ChannelState.RECEIVED, message));
        } catch (Throwable t) {
            // FIXME: when the thread pool is full, SERVER_THREADPOOL_EXHAUSTED_ERROR cannot return properly, 当线程池满时,server_threadpool_sted_error不能正确返回,
            // therefore the consumer side has to wait until gets timeout. This is a temporary solution to prevent 因此,客户端必须等待超时。这是一种临时的解决办法
            // this scenario from happening, but a better solution should be considered later. 这个场景可能会发生,但是稍后应该考虑更好的解决方案。
            if (t instanceof RejectedExecutionException) {
                Request request = (Request) message;
                if (request.isTwoWay()) {
                    String msg = "Server side(" + url.getIp() + "," + url.getPort()
                            + ") thread pool is exhausted, detail msg:" + t.getMessage();
                    Response response = new Response(request.getId(), request.getVersion());
                    response.setStatus(Response.SERVER_THREADPOOL_EXHAUSTED_ERROR);
                    response.setErrorMessage(msg);
                    channel.send(response);
                    return;
                }
            }
            throw new ExecutionException(message, channel, getClass() + " error when process received event.", t);
        }
    } else {
        handler.received(channel, message);
    }
}
 
Example #21
Source File: ThriftCodec.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(Channel channel, ChannelBuffer buffer, Object message)
        throws IOException {

    if (message instanceof Request) {
        encodeRequest(channel, buffer, (Request) message);
    } else if (message instanceof Response) {
        encodeResponse(channel, buffer, (Response) message);
    } else {
        throw new UnsupportedOperationException("Thrift codec only support encode " 
                + Request.class.getName() + " and " + Response.class.getName());
    }

}
 
Example #22
Source File: MinaClient.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Override
protected Channel getChannel() {
    IoSession s = session;
    if (s == null || ! s.isConnected())
        return null;
    return MinaChannel.getOrAddChannel(s, getUrl(), this);
}
 
Example #23
Source File: DeprecatedExchangeCodec.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
protected Object decodeEventData(Channel channel, ObjectInput in) throws IOException {
    try {
        return in.readObject();
    } catch (ClassNotFoundException e) {
        throw new IOException(StringUtils.toString("Read object failed.", e));
    }
}
 
Example #24
Source File: ChannelHandlerDispatcher.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void caught(Channel channel, Throwable exception) {
    for (ChannelHandler listener : channelHandlers) {
        try {
            listener.caught(channel, exception);
        } catch (Throwable t) {
            logger.error(t.getMessage(), t);
        }
    }
}
 
Example #25
Source File: NettyServer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public Collection<Channel> getChannels() {
    Collection<Channel> chs = new HashSet<Channel>();
    for (Channel channel : this.channels.values()) {
        if (channel.isConnected()) {
            chs.add(channel);
        } else {
            channels.remove(NetUtils.toAddressString(channel.getRemoteAddress()));
        }
    }
    return chs;
}
 
Example #26
Source File: CodecAdapter.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public Object decode(Channel channel, ChannelBuffer buffer) throws IOException {
    byte[] bytes = new byte[buffer.readableBytes()];
    int savedReaderIndex = buffer.readerIndex();
    buffer.readBytes(bytes);
    UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(bytes);
    Object result = codec.decode(channel, is);
    buffer.readerIndex(savedReaderIndex + is.position());
    return result == Codec.NEED_MORE_INPUT ? DecodeResult.NEED_MORE_INPUT : result;
}
 
Example #27
Source File: ConnectionOrderedChannelHandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void disconnected(Channel channel) throws RemotingException {
    try{
        checkQueueLength();
        connectionExecutor.execute(new ChannelEventRunnable(channel, handler ,ChannelState.DISCONNECTED));
    }catch (Throwable t) {
        throw new ExecutionException("disconnected event", channel, getClass()+" error when process disconnected event ." , t);
    }
}
 
Example #28
Source File: AbstractClient.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
    public void send(Object message, boolean sent) throws RemotingException {
        if (send_reconnect && !isConnected()) {
            connect();
        }
        Channel channel = getChannel();
        //TODO Can the value returned by getChannel() be null? need improvement.
        if (channel == null || !channel.isConnected()) {
            throw new RemotingException(this, "message can not send, because channel is closed . url:" + getUrl());
        }
//        =》com.alibaba.dubbo.remoting.transport.netty.NettyChannel.send()
        channel.send(message, sent);
    }
 
Example #29
Source File: ExchangeCodecTest.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@Test 
    public void test_Encode_Error_Response() throws IOException{
        ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024);
        Channel channel = getCliendSideChannel(url);
        Response response = new Response();
        response.setHeartbeat(true);
        response.setId(1001l);
        response.setStatus((byte)10 );
        response.setVersion("11");
        String badString = "bad" ;
        response.setErrorMessage(badString);
        Person person = new Person();
        response.setResult(person);
        
        codec.encode(channel, encodeBuffer, response);
        byte[] data = new byte[encodeBuffer.writerIndex()];
        encodeBuffer.readBytes(data);

        //encode resault check need decode 
        ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data);
        Response obj = (Response)codec.decode(channel, decodeBuffer);
        Assert.assertEquals(response.getId(), obj.getId());
        Assert.assertEquals(response.getStatus(), obj.getStatus());
        Assert.assertEquals(response.isHeartbeat(), obj.isHeartbeat());
        Assert.assertEquals(badString, obj.getErrorMessage());
        Assert.assertEquals(null, obj.getResult());
//        Assert.assertEquals(response.getVersion(), obj.getVersion());
    }
 
Example #30
Source File: DubboProtocol.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
private Invocation createInvocation(Channel channel, URL url, String methodKey) {
    String method = url.getParameter(methodKey);
    if (method == null || method.length() == 0) {
        return null;
    }
    RpcInvocation invocation = new RpcInvocation(method, new Class<?>[0], new Object[0]);
    invocation.setAttachment(Constants.PATH_KEY, url.getPath());
    invocation.setAttachment(Constants.GROUP_KEY, url.getParameter(Constants.GROUP_KEY));
    invocation.setAttachment(Constants.INTERFACE_KEY, url.getParameter(Constants.INTERFACE_KEY));
    invocation.setAttachment(Constants.VERSION_KEY, url.getParameter(Constants.VERSION_KEY));
    if (url.getParameter(Constants.STUB_EVENT_KEY, false)){
        invocation.setAttachment(Constants.STUB_EVENT_KEY, Boolean.TRUE.toString());
    }
    return invocation;
}