Java Code Examples for com.alibaba.dubbo.remoting.Channel

The following examples show how to use com.alibaba.dubbo.remoting.Channel. These examples are extracted from open source projects. 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 Project: dubbox-hystrix   Source File: ListTelnetHandlerTest.java    License: 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 2
Source Project: dubbo-2.6.5   Source File: HeaderExchangeHandlerTest.java    License: 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 3
Source Project: dubbo3   Source File: DeprecatedTelnetCodec.java    License: 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 Project: dubbox   Source File: HeaderExchangeHandlerTest.java    License: 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 Project: dubbox   Source File: DeprecatedTelnetCodec.java    License: 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 6
Source Project: dubbox   Source File: DubboCodec.java    License: 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 7
Source Project: dubbo3   Source File: CodecAdapter.java    License: 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 8
Source Project: dubbo-2.6.5   Source File: DeprecatedTelnetCodec.java    License: Apache License 2.0 5 votes vote down vote up
public void encode(Channel channel, OutputStream output, Object message) throws IOException {
    if (message instanceof String) {
        if (isClientSide(channel)) {
            message = message + "\r\n";
        }
        byte[] msgData = ((String) message).getBytes(getCharset(channel).name());
        output.write(msgData);
        output.flush();
    } else {
        ObjectOutput objectOutput = CodecSupport.getSerialization(channel.getUrl()).serialize(channel.getUrl(), output);
        objectOutput.writeObject(message);
        objectOutput.flushBuffer();
    }
}
 
Example 9
Source Project: dubbo-2.6.5   Source File: GrizzlyClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Channel getChannel() {
    Connection<?> c = connection;
    if (c == null || !c.isOpen())
        return null;
    return GrizzlyChannel.getOrAddChannel(c, getUrl(), this);
}
 
Example 10
Source Project: dubbo-2.6.5   Source File: NettyServer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
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 11
Source Project: dubbox-hystrix   Source File: DecodeableRpcInvocation.java    License: Apache License 2.0 5 votes vote down vote up
public DecodeableRpcInvocation(Channel channel, Request request, InputStream is, byte id) {
    Assert.notNull(channel, "channel == null");
    Assert.notNull(request, "request == null");
    Assert.notNull(is, "inputStream == null");
    this.channel = channel;
    this.request = request;
    this.inputStream = is;
    this.serializationType = id;
}
 
Example 12
Source Project: dubbox   Source File: AbstractClient.java    License: Apache License 2.0 5 votes vote down vote up
public void send(Object message, boolean sent) throws RemotingException {
    if (send_reconnect && !isConnected()){
        connect();
    }
    Channel channel = getChannel();
    //TODO getChannel返回的状态是否包含null需要改进
    if (channel == null || ! channel.isConnected()) {
      throw new RemotingException(this, "message can not send, because channel is closed . url:" + getUrl());
    }
    channel.send(message, sent);
}
 
Example 13
Source Project: dubbox-hystrix   Source File: AbstractCodec.java    License: Apache License 2.0 5 votes vote down vote up
protected static void checkPayload(Channel channel, long size) throws IOException {
    int payload = Constants.DEFAULT_PAYLOAD;
    if (channel != null && channel.getUrl() != null) {
        payload = channel.getUrl().getParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD);
    }
    if (payload > 0 && size > payload) {
    	IOException e = new IOException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel);
    	logger.error(e);
        throw e;
    }
}
 
Example 14
Source Project: dubbox   Source File: AbstractServer.java    License: Apache License 2.0 5 votes vote down vote up
public void send(Object message, boolean sent) throws RemotingException {
    Collection<Channel> channels = getChannels();
    for (Channel channel : channels) {
        if (channel.isConnected()) {
            channel.send(message, sent);
        }
    }
}
 
Example 15
Source Project: dubbox-hystrix   Source File: CurrentTelnetHandler.java    License: Apache License 2.0 5 votes vote down vote up
public String telnet(Channel channel, String message) {
    if (message.length() > 0) {
        return "Unsupported parameter " + message + " for pwd.";
    }
    String service = (String) channel.getAttribute(ChangeTelnetHandler.SERVICE_KEY);
    StringBuilder buf = new StringBuilder();
    if (service == null || service.length() == 0) {
        buf.append("/");
    } else {
        buf.append(service);
    }
    return buf.toString();
}
 
Example 16
Source Project: dubbo-2.6.5   Source File: CallbackServiceCodec.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isInstancesOverLimit(Channel channel, URL url, String interfaceClass, int instid, boolean isServer) {
    Integer count = (Integer) channel.getAttribute(isServer ? getServerSideCountKey(channel, interfaceClass) : getClientSideCountKey(interfaceClass));
    int limit = url.getParameter(Constants.CALLBACK_INSTANCES_LIMIT_KEY, Constants.DEFAULT_CALLBACK_INSTANCES);
    if (count != null && count >= limit) {
        //client side error
        throw new IllegalStateException("interface " + interfaceClass + " `s callback instances num exceed providers limit :" + limit
                + " ,current num: " + (count + 1) + ". The new callback service will not work !!! you can cancle the callback service which exported before. channel :" + channel);
    } else {
        return false;
    }
}
 
Example 17
Source Project: dubbo3   Source File: ChannelHandlerDispatcher.java    License: Apache License 2.0 5 votes vote down vote up
public void sent(Channel channel, Object message) {
    for (ChannelHandler listener : channelHandlers) {
        try {
            listener.sent(channel, message);
        } catch (Throwable t) {
            logger.error(t.getMessage(), t);
        }
    }
}
 
Example 18
Source Project: dubbox-hystrix   Source File: ExchangeCodecTest.java    License: 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 19
Source Project: dubbo-2.6.5   Source File: AbstractClient.java    License: 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 20
Source Project: dubbox   Source File: ConnectionOrderedChannelHandler.java    License: 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 21
Source Project: dubbox   Source File: ChannelHandlerDispatcher.java    License: 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 22
Source Project: dubbo3   Source File: DeprecatedExchangeCodec.java    License: 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 23
Source Project: dubbox   Source File: MinaClient.java    License: 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 24
Source Project: dubbo-2.6.5   Source File: ThriftCodec.java    License: 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 25
Source Project: dubbo-2.6.5   Source File: ExecutionChannelHandler.java    License: 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 26
Source Project: dubbox-hystrix   Source File: TelnetCodecTest.java    License: 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 27
Source Project: dubbo-2.6.5   Source File: HeaderExchangeServer.java    License: 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 28
Source Project: dubbox-hystrix   Source File: DubboProtocol.java    License: 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;
}
 
Example 29
Source Project: dubbox   Source File: CodecAdapter.java    License: 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 30
Source Project: dubbox   Source File: HeaderExchangeClient.java    License: 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 );
    }
}