Java Code Examples for org.jboss.netty.channel.Channel

The following examples show how to use org.jboss.netty.channel.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
@Override
protected void handleError(ErrorMessage error, Channel channel) {            
    ErrorType errType = ErrorType.GENERIC;
    for (ErrorType e : ErrorType.values()) {
        if (e.getValue() == error.getError().getErrorCode()) {
            errType = e;
            break;
        }
    }
    SyncException ex = 
            SyncException.newInstance(errType, 
                                      error.getError().getMessage(), 
                                      null);
    if (ChannelState.CONNECTED.equals(channelState) ||
        ChannelState.OPEN.equals(channelState) ||
        ErrorType.AUTH.equals(errType)) {
        syncManager.channelDisconnected(ex);
        channel.close();
    } else {
        SyncReply reply = new SyncReply(null, null, false, ex, 0);
        syncManager.dispatchReply(error.getHeader().getTransactionId(), 
                                  reply);
    }
}
 
Example 2
Source Project: RDFS   Source File: ShuffleHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
    throws Exception {
  Channel ch = e.getChannel();
  Throwable cause = e.getCause();
  if (cause instanceof TooLongFrameException) {
    sendError(ctx, BAD_REQUEST);
    return;
  }

  LOG.error("Shuffle error: ", cause);
  shuffleMetrics.failedOutput();
  if (ch.isConnected()) {
    LOG.error("Shuffle error " + e);
    sendError(ctx, INTERNAL_SERVER_ERROR);
  }
}
 
Example 3
Source Project: big-c   Source File: OpenFileCtx.java    License: Apache License 2.0 6 votes vote down vote up
private WriteCtx checkRepeatedWriteRequest(WRITE3Request request,
    Channel channel, int xid) {
  OffsetRange range = new OffsetRange(request.getOffset(),
      request.getOffset() + request.getCount());
  WriteCtx writeCtx = pendingWrites.get(range);
  if (writeCtx== null) {
    return null;
  } else {
    if (xid != writeCtx.getXid()) {
      LOG.warn("Got a repeated request, same range, with a different xid: "
          + xid + " xid in old request: " + writeCtx.getXid());
      //TODO: better handling.
    }
    return writeCtx;  
  }
}
 
Example 4
Source Project: whiteboard   Source File: MyServerHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	Channel channel = e.getChannel();
	SerializablePath newPath = (SerializablePath) e.getMessage();
	Commons.myUUID = newPath.getMyUUID();

	recordMyUUID(Commons.myUUID, channel);
	System.out.println("������յ���Ϣ,�豸��ʾ��--" + Commons.myUUID);
	if ("send_uuid".equals(newPath.getOPType()))
		return;

	if ("clear".equals(newPath.getOPType())) {
		if (MetadataRepositories.getInstance().getBufferShapes().size() != 0) {
			System.out.println("������������ͼ������");
			MetadataRepositories.getInstance().getBufferShapes().clear();
		}
		return;
	}

	MetadataRepositories.getInstance().getBufferShapes().add(newPath);
	// // ��DZ��͑���д����ͼ������
	sendNewShapeToClient(newPath);
}
 
Example 5
@Override
protected void handleRegisterRequest(RegisterRequestMessage request,
                                     Channel channel) {
    try {
        Scope scope = TProtocolUtil.getScope(request.store.getScope());
        if (request.store.isPersist())
            syncManager.registerPersistentStore(request.store.storeName,
                                                scope);
        else
            syncManager.registerStore(request.store.storeName, scope);
        RegisterResponseMessage m = new RegisterResponseMessage();
        AsyncMessageHeader header = new AsyncMessageHeader();
        header.setTransactionId(request.getHeader().getTransactionId());
        m.setHeader(header);
        SyncMessage bsm =
                new SyncMessage(MessageType.REGISTER_RESPONSE);
        bsm.setRegisterResponse(m);
        channel.write(bsm);
    } catch (Exception e) {
        channel.write(getError(request.getHeader().getTransactionId(), e,
                               MessageType.REGISTER_REQUEST));
    }
}
 
Example 6
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel,
                        Object message) throws Exception {
    if (message instanceof SyncMessage) {
        ChannelBuffer buf = new DynamicChannelBuffer(512);
        ChannelBufferOutputStream os = new ChannelBufferOutputStream(buf);
        TCompactProtocol thriftProtocol =
                new TCompactProtocol(new TIOStreamTransport(os));
        ((SyncMessage) message).write(thriftProtocol);

        ChannelBuffer len = ChannelBuffers.buffer(4);
        len.writeInt(buf.readableBytes());
        return ChannelBuffers.wrappedBuffer(len, buf);
    }
    return message;
}
 
Example 7
Source Project: jstorm   Source File: MessageEncoder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object obj) throws Exception {
    if (obj instanceof MessageBatch) {
        return ((MessageBatch) obj).buffer();
    }

    if (obj instanceof ControlMessage) {
        return ((ControlMessage) obj).buffer();
    }

    if (obj instanceof TaskMessage) {
        return ((TaskMessage) obj).buffer();
    }
    
    throw new RuntimeException("Unsupported encoding of object of class " + obj.getClass().getName());
}
 
Example 8
@Test(timeOut = 10_000)
public void testProcessingOfBatchPersistEventWith2EventsCommitAndCommitRetry() throws Exception {

    // Prepare test batch
    Batch batch = new Batch(BATCH_ID, BATCH_SIZE);
    batch.addCommit(FIRST_ST, FIRST_CT, null, mock(MonitoringContextImpl.class), Optional.<Long>absent());
    batch.addCommitRetry(SECOND_ST, null, mock(MonitoringContextImpl.class));
    PersistBatchEvent batchEvent = new PersistBatchEvent();
    PersistBatchEvent.makePersistBatch(batchEvent, BATCH_SEQUENCE, batch);

    // Initial assertion
    assertEquals(batch.getNumEvents(), 2);

    // Call process method
    persistenceHandler.onEvent(batchEvent);

    verify(persistenceHandler, times(1)).flush(eq(1));
    verify(persistenceHandler, times(1)).filterAndDissambiguateClientRetries(eq(batch));
    verify(retryProcessor, times(1)).disambiguateRetryRequestHeuristically(eq(SECOND_ST), any(Channel.class), any(MonitoringContextImpl.class));
    verify(replyProcessor, times(1)).manageResponsesBatch(eq(BATCH_SEQUENCE), eq(batch));
    assertEquals(batch.getNumEvents(), 1);
    assertEquals(batch.get(0).getStartTimestamp(), FIRST_ST);
    assertEquals(batch.get(0).getCommitTimestamp(), FIRST_CT);

}
 
Example 9
Source Project: onos   Source File: OspfNbrImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends the LSA to destination address.
 *
 * @param lsa         LSA instance to sent
 * @param destination destination IP address
 * @param ch          netty channel instance
 */
public void sendLsa(LsaHeader lsa, Ip4Address destination, Channel ch) {
    if (lsa == null) {
        return;
    }

    LsUpdate responseLsUpdate = new LsUpdate();
    // seting OSPF Header
    responseLsUpdate.setOspfVer(OspfUtil.OSPF_VERSION);
    responseLsUpdate.setOspftype(OspfPacketType.LSUPDATE.value());
    responseLsUpdate.setRouterId(ospfArea.routerId());
    responseLsUpdate.setAreaId(ospfArea.areaId());
    responseLsUpdate.setAuthType(OspfUtil.NOT_ASSIGNED);
    responseLsUpdate.setAuthentication(OspfUtil.NOT_ASSIGNED);
    responseLsUpdate.setOspfPacLength(OspfUtil.NOT_ASSIGNED); // to calculate packet length
    responseLsUpdate.setChecksum(OspfUtil.NOT_ASSIGNED);
    responseLsUpdate.setNumberOfLsa(1);
    responseLsUpdate.addLsa(lsa);

    //setting the destination.
    responseLsUpdate.setDestinationIp(destination);
    byte[] messageToWrite = getMessage(responseLsUpdate);
    ch.write(messageToWrite);
}
 
Example 10
Source Project: ck   Source File: NettyAsyncHttpProvider.java    License: Apache License 2.0 6 votes vote down vote up
private Channel lookupInCache(URI uri) {
	Channel channel = connectionsPool.remove(getBaseUrl(uri));
	if (channel != null) {
		/**
		 * The Channel will eventually be closed by Netty and will becomes invalid.
		 * We might suffer a memory leak if we don't scan for closed channel. The
		 * AsyncHttpClientConfig.reaper() will always make sure those are cleared.
		 */
		if (channel.isOpen()) {
			channel.setReadable(true);
		} else {
			return null;
		}
	}
	return channel;
}
 
Example 11
Source Project: hadoop   Source File: ShuffleHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
    throws Exception {
  Channel ch = e.getChannel();
  Throwable cause = e.getCause();
  if (cause instanceof TooLongFrameException) {
    sendError(ctx, BAD_REQUEST);
    return;
  } else if (cause instanceof IOException) {
    if (cause instanceof ClosedChannelException) {
      LOG.debug("Ignoring closed channel error", cause);
      return;
    }
    String message = String.valueOf(cause.getMessage());
    if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) {
      LOG.debug("Ignoring client socket close", cause);
      return;
    }
  }

  LOG.error("Shuffle error: ", cause);
  if (ch.isConnected()) {
    LOG.error("Shuffle error " + e);
    sendError(ctx, INTERNAL_SERVER_ERROR);
  }
}
 
Example 12
Source Project: hadoop   Source File: OpenFileCtx.java    License: Apache License 2.0 6 votes vote down vote up
private WriteCtx checkRepeatedWriteRequest(WRITE3Request request,
    Channel channel, int xid) {
  OffsetRange range = new OffsetRange(request.getOffset(),
      request.getOffset() + request.getCount());
  WriteCtx writeCtx = pendingWrites.get(range);
  if (writeCtx== null) {
    return null;
  } else {
    if (xid != writeCtx.getXid()) {
      LOG.warn("Got a repeated request, same range, with a different xid: "
          + xid + " xid in old request: " + writeCtx.getXid());
      //TODO: better handling.
    }
    return writeCtx;  
  }
}
 
Example 13
Source Project: jstorm   Source File: NettyServerFlowCtrlHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void run() {
    while(true) {
        int taskId;
        try {
            taskId = eventQueue.take();
            Set<String> remoteAddrs = flowCtrlClients.get(taskId);
            if (remoteAddrs == null)
                continue;

            synchronized (remoteAddrs) {
                if (!remoteAddrs.isEmpty()) {
                    for (String remoteAddr : remoteAddrs) {
                        Channel channel = allChannels.getChannel(remoteAddr);
                        if (channel == null) {
                            continue;
                        }
                        // send back backpressure flow control request to source client
                        JStormUtils.sendFlowControlRequest(channel, taskId, 0);
                    }
                    remoteAddrs.clear();
                }
            }
        } catch (InterruptedException e) {
            LOG.warn("Failed to take flow control event", e);
        }
    }
}
 
Example 14
Source Project: Android-Airplay-Server   Source File: RaopAudioHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt) throws Exception {
	final RaopRtpPacket packet = (RaopRtpPacket)evt.getMessage();

	/* Get control and timing channel from the enclosing RaopAudioHandler */
	Channel tempControlChannel = null;
	Channel tempTimingChannel = null;
	
	synchronized(RaopAudioHandler.this) {
		tempControlChannel = controlChannel;
		tempTimingChannel = timingChannel;
	}

	if (packet instanceof RaopRtpPacket.RetransmitRequest) {
		if ((tempControlChannel != null) && tempControlChannel.isOpen() && tempControlChannel.isWritable()){
			tempControlChannel.write(evt.getMessage());
		}
	}
	else if (packet instanceof RaopRtpPacket.TimingRequest) {
		if ((tempTimingChannel != null) && tempTimingChannel.isOpen() && tempTimingChannel.isWritable()){
			tempTimingChannel.write(evt.getMessage());
		}
	}
	else {
		super.writeRequested(ctx, evt);
	}
}
 
Example 15
Source Project: onos   Source File: OspfNbrImplTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests oneWayReceived() method.
 */
@Test
public void testOneWayReceived() throws Exception {
    ospfMessage = new HelloPacket();
    ospfNbr.setState(OspfNeighborState.ATTEMPT);
    channel = EasyMock.createMock(Channel.class);
    ospfNbr.oneWayReceived(ospfMessage, channel);
    channel1 = EasyMock.createMock(Channel.class);
    ospfNbr.setState(OspfNeighborState.DOWN);
    ospfNbr.oneWayReceived(ospfMessage, channel1);
    channel2 = EasyMock.createMock(Channel.class);
    ospfNbr.setState(OspfNeighborState.TWOWAY);
    ospfNbr.oneWayReceived(ospfMessage, channel2);
    assertThat(ospfNbr, is(notNullValue()));
}
 
Example 16
Source Project: pinpoint   Source File: DefaultPinpointServer.java    License: Apache License 2.0 5 votes vote down vote up
private void handleClosePacket(Channel channel) {
    logger.info("{} handleClosePacket() started.", objectUniqName);
    
    SocketStateChangeResult stateChangeResult = state.toBeingCloseByPeer();
    if (!stateChangeResult.isChange()) {
        logger.info("{} handleClosePacket() failed. Error: {}", objectUniqName, stateChangeResult);
    } else {
        logger.info("{} handleClosePacket() completed.", objectUniqName);
    }
}
 
Example 17
Source Project: onos   Source File: FpmManager.java    License: Apache License 2.0 5 votes vote down vote up
private void processDhcpStaticRoutes(Channel ch) {

        /* Get Dhcp static routes. */
        if (dhcpStore != null) {
            Collection<FpmRecord> dhcpRecords = dhcpStore.getFpmRecords();
            log.info("Dhcp store size is {}", dhcpRecords.size());

            dhcpRecords.forEach(record -> sendRouteUpdateToChannel(true,
                                record.ipPrefix(), ch));
        }
    }
 
Example 18
Source Project: jstorm   Source File: StormServerHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected int getFailureCounter(Channel channel) {
    Integer num = failureCounters.get(channel);
    if (num == null) {
        return 0;
    }
    return num;
}
 
Example 19
Source Project: phoenix-omid   Source File: TestPersistenceProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 30_000)
public void testRuntimeExceptionOnCommitPersistenceTakesDownDaemon() throws Exception {

    TSOServerConfig config = new TSOServerConfig();

    ObjectPool<Batch> batchPool = new BatchPoolModule(config).getBatchPool();

    ReplyProcessor replyProcessor = new ReplyProcessorImpl(new BlockingWaitStrategy(), metrics, panicker, batchPool, lowWatermarkWriter);

    PersistenceProcessorHandler[] handlers = new PersistenceProcessorHandler[config.getNumConcurrentCTWriters()];
    for (int i = 0; i < config.getNumConcurrentCTWriters(); i++) {
        handlers[i] = new PersistenceProcessorHandler(metrics,
                                                      "localhost:1234",
                                                      mock(LeaseManager.class),
                                                      commitTable,
                                                      replyProcessor,
                                                      retryProcessor,
                                                      panicker);
    }

    PersistenceProcessorImpl proc = new PersistenceProcessorImpl(config, new BlockingWaitStrategy(), commitTable, batchPool,
                                                                 panicker, handlers, metrics);

    // Configure writer to explode with a runtime exception
    doThrow(new RuntimeException("Kaboom!")).when(mockWriter).addCommittedTransaction(anyLong(), anyLong());
    MonitoringContextImpl monCtx = new MonitoringContextImpl(metrics);

    // Check the panic is extended!
    proc.addCommitToBatch(ANY_ST, ANY_CT, mock(Channel.class), monCtx, Optional.<Long>absent());
    proc.triggerCurrentBatchFlush();
    verify(panicker, timeout(1000).atLeastOnce()).panic(anyString(), any(Throwable.class));

}
 
Example 20
Source Project: phoenix-omid   Source File: PersistEvent.java    License: Apache License 2.0 5 votes vote down vote up
void makeCommitRetry(long startTimestamp, Channel c, MonitoringContext monCtx) {

        this.type = Type.COMMIT_RETRY;
        this.startTimestamp = startTimestamp;
        this.channel = c;
        this.monCtx = monCtx;

    }
 
Example 21
Source Project: onos   Source File: OspfNbrImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Starts the Dd Retransmission executor task.
 *
 * @param ch netty channel instance
 */
private void startRxMtDdTimer(Channel ch) {
    if (!rxmtDdPacketTimerScheduled) {
        long retransmitInterval = ospfInterface.reTransmitInterval();
        rxmtDdPacketTask = new InternalRxmtDdPacket(ch);
        exServiceRxmtDDPacket = Executors.newSingleThreadScheduledExecutor();
        exServiceRxmtDDPacket.scheduleAtFixedRate(rxmtDdPacketTask, retransmitInterval,
                                                  retransmitInterval, TimeUnit.SECONDS);
        rxmtDdPacketTimerScheduled = true;
    }
}
 
Example 22
Source Project: jstorm   Source File: StormServerHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected void incFailureCounter(Channel channel) {
    Integer num = failureCounters.get(channel);
    if (num == null) {
        num = 0;
    }
    num = num + 1;

    failureCounters.put(channel, num);
}
 
Example 23
Source Project: onos   Source File: OspfNbrImplTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests processLsUpdate() method.
 */
@Test
public void testProcessLsUpdate() throws Exception {
    LsUpdate ospfMessage = new LsUpdate();
    ospfMessage.setSourceIp(Ip4Address.valueOf("10.10.10.10"));
    ospfMessage.addLsa(new RouterLsa());
    ospfMessage.addLsa(new NetworkLsa());
    channel = EasyMock.createMock(Channel.class);
    ospfNbr.setState(OspfNeighborState.EXCHANGE);
    ospfNbr.processLsUpdate(ospfMessage, channel);
    assertThat(ospfNbr, is(notNullValue()));
}
 
Example 24
Source Project: pinpoint   Source File: PacketDecoder.java    License: Apache License 2.0 5 votes vote down vote up
private void sendPong(Channel channel) {

        // a "pong" responds to a "ping" automatically.
        logger.debug("received ping. sending pong. {}", channel);
        ChannelFuture write = channel.write(PongPacket.PONG_PACKET);
        write.addListener(pongWriteFutureListener);
    }
 
Example 25
Source Project: nfs-client-java   Source File: RPCRecordDecoder.java    License: Apache License 2.0 5 votes vote down vote up
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception {
    // Wait until the length prefix is available.
    if (channelBuffer.readableBytes() < 4) {
        // If null is returned, it means there is not enough data yet.
        // FrameDecoder will call again when there is a sufficient amount of data available.
        return null;
    }

    //marking the current reading position
    channelBuffer.markReaderIndex();

    //get the fragment size and wait until the entire fragment is available.
    long fragSize = channelBuffer.readUnsignedInt();
    boolean lastFragment = RecordMarkingUtil.isLastFragment(fragSize);
    fragSize = RecordMarkingUtil.maskFragmentSize(fragSize);
    if (channelBuffer.readableBytes() < fragSize) {
        channelBuffer.resetReaderIndex();
        return null;
    }

    //seek to the beginning of the next fragment
    channelBuffer.skipBytes((int) fragSize);

    _recordLength += 4 + (int) fragSize;

    //check the last fragment
    if (!lastFragment) {
        //not the last fragment, the data is put in an internally maintained cumulative buffer
        return null;
    }

    byte[] rpcResponse = new byte[_recordLength];
    channelBuffer.readerIndex(channelBuffer.readerIndex() - _recordLength);
    channelBuffer.readBytes(rpcResponse, 0, _recordLength);

    _recordLength = 0;
    return rpcResponse;
}
 
Example 26
Source Project: msgpack-rpc-java   Source File: MessagePackDecoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
        Object msg) throws Exception {
    if (!(msg instanceof ChannelBuffer)) {
        return msg;
    }

    ChannelBuffer source = (ChannelBuffer) msg;

    ByteBuffer buffer = source.toByteBuffer();
    if (!buffer.hasRemaining()) {
        return null;
    }

    byte[] bytes = buffer.array(); // FIXME buffer must has array
    int offset = buffer.arrayOffset() + buffer.position();
    int length = buffer.arrayOffset() + buffer.limit();

    Value v = messagePack.read(bytes, offset, length);
    return v;

    // TODO MessagePack.unpack()
    /*
     * Unpacker pac = new Unpacker(); pac.wrap(bytes, offset, length);
     * return pac.unpackObject();
     */
}
 
Example 27
Source Project: phoenix-omid   Source File: AbstractRequestProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void handleFence(RequestEvent event) throws Exception {
    long tableID = event.getTableId();
    Channel c = event.getChannel();

    long fenceTimestamp = timestampOracle.next();

    tableFences.put(tableID, fenceTimestamp);

    event.monCtx.timerStart("reply.processor.fence.latency");
    replyProcessor.sendFenceResponse(tableID, fenceTimestamp, c, event.monCtx);
}
 
Example 28
Source Project: dubbo3   Source File: NettyCodecAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object encode(ChannelHandlerContext ctx, Channel ch, Object msg) throws Exception {
    com.alibaba.dubbo.remoting.buffer.ChannelBuffer buffer =
        com.alibaba.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(1024);
    NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler);
    try {
    	codec.encode(channel, buffer, msg);
    } finally {
        NettyChannel.removeChannelIfDisconnected(ch);
    }
    return ChannelBuffers.wrappedBuffer(buffer.toByteBuffer());
}
 
Example 29
Source Project: pinpoint   Source File: PacketEncoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
    if (!(msg instanceof Packet)) {
        logger.error("invalid packet:{} channel:{}", msg, channel);
        return null;
    }
    Packet packet = (Packet) msg;
    return packet.toBuffer();
}
 
Example 30
Source Project: phoenix-omid   Source File: ProgrammableTSOServer.java    License: Apache License 2.0 5 votes vote down vote up
private void sendAbortResponse(long startTimestamp, Channel c) {
    TSOProto.Response.Builder builder = TSOProto.Response.newBuilder();
    TSOProto.CommitResponse.Builder commitBuilder = TSOProto.CommitResponse.newBuilder();
    commitBuilder.setAborted(true).setStartTimestamp(startTimestamp);
    builder.setCommitResponse(commitBuilder.build());
    c.write(builder.build());
}