Java Code Examples for org.jboss.netty.channel.Channel#write()

The following examples show how to use org.jboss.netty.channel.Channel#write() . 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: OspfNbrImpl.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a direct Acknowledgment for a particular LSA to the Neighbor.
 *
 * @param ackLsa   LSA instance
 * @param ch       netty channel instance
 * @param sourceIp source IP address
 */
public void directAcknowledge(LsaHeader ackLsa, Channel ch, Ip4Address sourceIp) {
    log.debug("OSPFNbr::directAcknowledge...!!!");

    LsAcknowledge ackContent = new LsAcknowledge();
    // seting OSPF Header
    ackContent.setOspfVer(OspfUtil.OSPF_VERSION);
    ackContent.setOspftype(OspfPacketType.LSAACK.value());
    ackContent.setRouterId(ospfArea.routerId());
    ackContent.setAreaId(ospfArea.areaId());
    ackContent.setAuthType(OspfUtil.NOT_ASSIGNED);
    ackContent.setAuthentication(OspfUtil.NOT_ASSIGNED);
    ackContent.setOspfPacLength(OspfUtil.NOT_ASSIGNED); // to calculate packet length
    ackContent.setChecksum(OspfUtil.NOT_ASSIGNED);
    ackContent.addLinkStateHeader(ackLsa);
    //setting the destination IP
    ackContent.setDestinationIp(sourceIp);
    byte[] messageToWrite = getMessage(ackContent);
    ch.write(messageToWrite);
}
 
Example 2
Source File: ReplyProcessorImpl.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
@Override
public void sendCommitResponse(long startTimestamp, long commitTimestamp, Channel c, MonitoringContext monCtx
        , Optional<Long> newLowWatermark) {
    updateLowWatermark(newLowWatermark);
    TSOProto.Response.Builder builder = TSOProto.Response.newBuilder();
    TSOProto.CommitResponse.Builder commitBuilder = TSOProto.CommitResponse.newBuilder();
    commitBuilder.setAborted(false)
            .setStartTimestamp(startTimestamp)
            .setCommitTimestamp(commitTimestamp);
    builder.setCommitResponse(commitBuilder.build());
    c.write(builder.build());
    commitMeter.mark();
    monCtx.timerStop("reply.processor.commit.latency");
}
 
Example 3
Source File: AbstractRPCChannelHandler.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
protected void handleEchoRequest(EchoRequestMessage request,
                                 Channel channel) {
    EchoReplyMessage m = new EchoReplyMessage();
    AsyncMessageHeader header = new AsyncMessageHeader();
    header.setTransactionId(request.getHeader().getTransactionId());
    m.setHeader(header);
    SyncMessage bsm = new SyncMessage(MessageType.ECHO_REPLY);
    bsm.setEchoReply(m);
    channel.write(bsm);
}
 
Example 4
Source File: TSOClient.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
HandshakingState(StateMachine.Fsm fsm, Channel channel) {
    super(fsm);
    LOG.debug("NEW STATE: HANDSHAKING");
    this.channel = channel;
    TSOProto.HandshakeRequest.Builder handshake = TSOProto.HandshakeRequest.newBuilder();
    // Add the required handshake capabilities when necessary
    handshake.setClientCapabilities(TSOProto.Capabilities.newBuilder().build());
    channel.write(TSOProto.Request.newBuilder().setHandshakeRequest(handshake.build()).build());
    timeout = newTimeout();
}
 
Example 5
Source File: ProgrammableTSOServer.java    From phoenix-omid with 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());
}
 
Example 6
Source File: ProgrammableTSOServer.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
private void sendCommitResponse(long startTimestamp, long commitTimestamp, Channel c) {
    TSOProto.Response.Builder builder = TSOProto.Response.newBuilder();
    TSOProto.CommitResponse.Builder commitBuilder = TSOProto.CommitResponse.newBuilder();
    commitBuilder.setAborted(false).setStartTimestamp(startTimestamp).setCommitTimestamp(commitTimestamp);
    builder.setCommitResponse(commitBuilder.build());
    c.write(builder.build());
}
 
Example 7
Source File: DefaultIsisInterface.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the partial sequence number PDU.
 *
 * @param lspEntryRequestList list of lsp entry request
 * @param isisPduType         intermediate system PDU type
 * @param channel             netty channel instance
 */
private void sendPsnPduMessage(List<LspEntry> lspEntryRequestList, IsisPduType isisPduType, Channel channel) {
    IsisHeader isisHeader = new LspGenerator().getHeader(isisPduType);
    Psnp psnp = new Psnp(isisHeader);
    psnp.setSourceId(lspKeyP2P(this.systemId));
    TlvHeader tlvHeader = new TlvHeader();
    tlvHeader.setTlvType(TlvType.LSPENTRY.value());
    tlvHeader.setTlvLength(0);
    LspEntriesTlv lspEntriesTlv = new LspEntriesTlv(tlvHeader);
    for (LspEntry lspEntry : lspEntryRequestList) {
        lspEntry.setLspChecksum(0);
        lspEntry.setLspSequenceNumber(0);
        lspEntry.setRemainingTime(0);
        lspEntriesTlv.addLspEntry(lspEntry);
    }
    psnp.addTlv(lspEntriesTlv);
    //write it to channel buffer.
    byte[] psnpBytes = psnp.asBytes();
    psnpBytes = IsisUtil.addLengthAndMarkItInReserved(psnpBytes, IsisConstants.LENGTHPOSITION,
                                                      IsisConstants.LENGTHPOSITION + 1,
                                                      IsisConstants.RESERVEDPOSITION);
    flagValue = false;
    //write to the channel
    if (channel != null && channel.isConnected() && channel.isOpen()) {
        channel.write(IsisUtil.framePacket(psnpBytes, interfaceIndex));
    }
}
 
Example 8
Source File: NetworkFailureHandler.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent event) throws Exception {
	if (blocked.get()) {
		return;
	}

	ChannelBuffer msg = (ChannelBuffer) event.getMessage();
	Channel targetChannel = sourceToTargetChannels.get(event.getChannel());
	if (targetChannel == null) {
		throw new IllegalStateException("Could not find a target channel for the source channel");
	}
	targetChannel.write(msg);
}
 
Example 9
Source File: Nfs3Utils.java    From big-c with Apache License 2.0 5 votes vote down vote up
public static void writeChannelCommit(Channel channel, XDR out, int xid) {
  if (RpcProgramNfs3.LOG.isDebugEnabled()) {
    RpcProgramNfs3.LOG.debug("Commit done:" + xid);
  }
  ChannelBuffer outBuf = XDR.writeMessageTcp(out, true);
  channel.write(outBuf);
}
 
Example 10
Source File: Nfs3Utils.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Send a write response to the netty network socket channel
 */
public static void writeChannel(Channel channel, XDR out, int xid) {
  if (channel == null) {
    RpcProgramNfs3.LOG
        .info("Null channel should only happen in tests. Do nothing.");
    return;
  }
  
  if (RpcProgramNfs3.LOG.isDebugEnabled()) {
    RpcProgramNfs3.LOG.debug(WRITE_RPC_END + xid);
  }
  ChannelBuffer outBuf = XDR.writeMessageTcp(out, true);
  channel.write(outBuf);
}
 
Example 11
Source File: DefaultIsisInterface.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Sends LS PDU message to channel.
 *
 * @param lsp     LS PDU message instance
 * @param channel channel instance
 */
private void sendLsp(LsPdu lsp, Channel channel) {
    byte[] lspBytes = lsp.asBytes();
    lspBytes = IsisUtil.addLengthAndMarkItInReserved(lspBytes, IsisConstants.LENGTHPOSITION,
                                                     IsisConstants.LENGTHPOSITION + 1,
                                                     IsisConstants.RESERVEDPOSITION);
    lspBytes = IsisUtil.addChecksum(lspBytes, IsisConstants.CHECKSUMPOSITION,
                                    IsisConstants.CHECKSUMPOSITION + 1);
    //write to the channel
    if (channel != null && channel.isConnected() && channel.isOpen()) {
        channel.write(IsisUtil.framePacket(lspBytes, interfaceIndex));
    }
}
 
Example 12
Source File: AbstractNSQClient.java    From TrendrrNSQClient with MIT License 5 votes vote down vote up
/**
 * Creates a new connection object.
 *
 * Handles connection and sending magic protocol
 * @param address
 * @param port
 * @return
 */
protected Connection createConnection(String address, int port) {

    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(address, port));

    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.awaitUninterruptibly().getChannel();
    if (!future.isSuccess()) {
        log.error("Caught", future.getCause());
        return null;
    }
    log.info("Creating connection: " + address + " : " + port);
    Connection conn = new Connection(address, port, channel, this);
    conn.setMessagesPerBatch(this.messagesPerBatch);

    ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
    buf.writeBytes(MAGIC_PROTOCOL_VERSION);
    channel.write(buf);

    //indentify
    try {
        String identJson = "{" +
                "\"short_id\":\"" + InetAddress.getLocalHost().getHostName() + "\"" +
                "," +
                "\"long_id\":\"" + InetAddress.getLocalHost().getCanonicalHostName() + "\"" +
                "}";
        NSQCommand ident = NSQCommand.instance("IDENTIFY", identJson.getBytes());
        conn.command(ident);

    } catch (UnknownHostException e) {
        log.error("Caught", e);
    }

    return conn;
}
 
Example 13
Source File: PacketDecoder.java    From pinpoint with 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 14
Source File: RPCChannelHandler.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleSyncRequest(SyncRequestMessage request,
                                 Channel channel) {
    rpcService.messageAcked(MessageType.SYNC_OFFER, getRemoteNodeId());
    if (!request.isSetKeys()) return;

    String storeName = request.getStore().getStoreName();
    try {
        IStorageEngine<ByteArray, byte[]> store =
                syncManager.getRawStore(storeName);

        SyncMessage bsm =
                TProtocolUtil.getTSyncValueMessage(request.getStore());
        SyncValueMessage svm = bsm.getSyncValue();
        svm.setResponseTo(request.getHeader().getTransactionId());
        svm.getHeader().setTransactionId(rpcService.getTransactionId());

        for (ByteBuffer key : request.getKeys()) {
            ByteArray keyArray = new ByteArray(key.array());
            List<Versioned<byte[]>> values =
                    store.get(keyArray);
            if (values == null || values.size() == 0) continue;
            KeyedValues kv =
                    TProtocolUtil.getTKeyedValues(keyArray, values);
            svm.addToValues(kv);
        }

        if (svm.isSetValues()) {
            updateCounter(SyncManager.counterSentValues,
                          svm.getValuesSize());
            rpcService.syncQueue.add(new NodeMessage(getRemoteNodeId(),
                                                     bsm));
        }
    } catch (Exception e) {
        channel.write(getError(request.getHeader().getTransactionId(), e,
                               MessageType.SYNC_REQUEST));
    }
}
 
Example 15
Source File: MyServerHandler.java    From whiteboard with Apache License 2.0 5 votes vote down vote up
/**
 * �����¿ͻ��˽���ʱ����ÿͻ��˷�������ͼ�ζ���
 * 
 * @param channel
 */
private void sendAllShapesToClient(Channel channel) {
	if (MetadataRepositories.getInstance().getBufferShapes().size() != 0) {
		System.out.println("��������ͼ�����ݵ��ͻ���");
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		channel.write(MetadataRepositories.getInstance().getBufferShapes());
	}
}
 
Example 16
Source File: NetworkFailureHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent event) throws Exception {
	if (blocked.get()) {
		return;
	}

	ChannelBuffer msg = (ChannelBuffer) event.getMessage();
	Channel targetChannel = sourceToTargetChannels.get(event.getChannel());
	if (targetChannel == null) {
		throw new IllegalStateException("Could not find a target channel for the source channel");
	}
	targetChannel.write(msg);
}
 
Example 17
Source File: RPCChannelHandler.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleDeleteRequest(DeleteRequestMessage request,
                                   Channel channel) {
    try {
        String storeName = request.getStoreName();
        IStorageEngine<ByteArray, byte[]> store =
                syncManager.getRawStore(storeName);
        ByteArray key = new ByteArray(request.getKey());
        VectorClock newclock;
        if (request.isSetVersion()) {
            newclock = TProtocolUtil.getVersion(request.getVersion());
        } else {
            newclock = new VectorClock();
            List<IVersion> versions = store.getVersions(key);
            for (IVersion v : versions) {
                newclock = newclock.merge((VectorClock)v);
            }
        }
        newclock =
                newclock.incremented(rpcService.syncManager.getLocalNodeId(),
                                     System.currentTimeMillis());
        Versioned<byte[]> value = Versioned.value(null, newclock);
        store.put(key, value);

        DeleteResponseMessage m = new DeleteResponseMessage();
        AsyncMessageHeader header = new AsyncMessageHeader();
        header.setTransactionId(request.getHeader().getTransactionId());
        m.setHeader(header);

        SyncMessage bsm =
                new SyncMessage(MessageType.DELETE_RESPONSE);
        bsm.setDeleteResponse(m);
        channel.write(bsm);
    } catch (Exception e) {
        channel.write(getError(request.getHeader().getTransactionId(), e,
                               MessageType.DELETE_REQUEST));
    }
}
 
Example 18
Source File: OspfNbrImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Determines whether an adjacency should be established/maintained with the neighbor or not.
 *
 * @param ch netty channel instance
 */
@Override
public void adjOk(Channel ch) {
    log.debug("OSPFNbr::adjOk...!!!");
    if (ospfInterface.interfaceType() != OspfInterfaceType.POINT_TO_POINT.value()) {
        if (state == OspfNeighborState.TWOWAY) {
            if (formAdjacencyOrNot()) {
                state = OspfNeighborState.EXSTART;
                //check for sequence number in lsdb
                ddSeqNum++;

                DdPacket ddPacket = new DdPacket();
                // seting OSPF Header
                ddPacket.setOspfVer(OspfUtil.OSPF_VERSION);
                ddPacket.setOspftype(OspfPacketType.DD.value());
                ddPacket.setRouterId(ospfArea.routerId());
                ddPacket.setAreaId(ospfArea.areaId());
                ddPacket.setAuthType(OspfUtil.NOT_ASSIGNED);
                ddPacket.setAuthentication(OspfUtil.NOT_ASSIGNED);
                ddPacket.setOspfPacLength(OspfUtil.NOT_ASSIGNED);
                ddPacket.setChecksum(OspfUtil.NOT_ASSIGNED);

                // setting DD Body
                boolean isOpaqueEnabled = ospfArea.isOpaqueEnabled();
                if (isOpaqueEnabled && this.isOpaqueCapable) {
                    ddPacket.setOptions(ospfArea.opaqueEnabledOptions());
                } else {
                    ddPacket.setOptions(ospfArea.options());
                }
                ddPacket.setIsInitialize(OspfUtil.INITIALIZE_SET);
                ddPacket.setIsMore(OspfUtil.MORE_SET);
                ddPacket.setIsMaster(OspfUtil.IS_MASTER);
                ddPacket.setImtu(ospfInterface.mtu());
                ddPacket.setSequenceNo(ddSeqNum);
                rxmtDdPacketTask = new InternalRxmtDdPacket(ch);
                startRxMtDdTimer(ch);
                //setting destination ip
                ddPacket.setDestinationIp(neighborIpAddr());
                setLastSentDdPacket(ddPacket);
                byte[] messageToWrite = getMessage(ddPacket);
                ch.write(messageToWrite);
            }
        } else if (state.getValue() >= OspfNeighborState.EXSTART.getValue()) {
            if (!formAdjacencyOrNot()) {
                state = OspfNeighborState.TWOWAY;
                lsReqList.clear();
                ddSummaryList.clear();
                reTxList.clear();
            }
        }
    }
}
 
Example 19
Source File: OspfNbrImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Called if a LS Request has been received for an LSA which is not contained in the database.
 * This indicates an error in the Database Exchange process.
 * Actions to be performed are the same as in seqNumMismatch.
 * In addition, stop the possibly activated re transmission timer.
 *
 * @param ch netty channel instance
 */
@Override
public void badLSReq(Channel ch) {
    log.debug("OSPFNbr::badLSReq...!!!");

    if (state.getValue() >= OspfNeighborState.EXCHANGE.getValue()) {
        if (state == OspfNeighborState.FULL) {
            ospfArea.refreshArea(ospfInterface);
        }

        stopRxMtDdTimer();
        state = OspfNeighborState.EXSTART;

        lsReqList.clear();
        ddSummaryList.clear();
        reTxList.clear();
        //increment the dd sequence number
        isMaster = OspfUtil.IS_MASTER;
        ddSeqNum++;
        DdPacket ddPacket = new DdPacket();
        // seting OSPF Header
        ddPacket.setOspfVer(OspfUtil.OSPF_VERSION);
        ddPacket.setOspftype(OspfPacketType.DD.value());
        ddPacket.setRouterId(ospfArea.routerId());
        ddPacket.setAreaId(ospfArea.areaId());
        ddPacket.setAuthType(OspfUtil.NOT_ASSIGNED);
        ddPacket.setAuthentication(OspfUtil.NOT_ASSIGNED);
        ddPacket.setOspfPacLength(OspfUtil.NOT_ASSIGNED); // to calculate packet length
        ddPacket.setChecksum(OspfUtil.NOT_ASSIGNED);

        // setting DD Body
        boolean isOpaqueEnabled = ospfArea.isOpaqueEnabled();
        if (isOpaqueEnabled && this.isOpaqueCapable) {
            ddPacket.setOptions(ospfArea.opaqueEnabledOptions());
        } else {
            ddPacket.setOptions(ospfArea.options());
        }
        ddPacket.setIsInitialize(OspfUtil.INITIALIZE_SET);
        ddPacket.setIsMore(OspfUtil.MORE_SET);
        ddPacket.setIsMaster(OspfUtil.IS_MASTER);
        ddPacket.setImtu(ospfInterface.mtu());
        ddPacket.setSequenceNo(ddSeqNum);

        rxmtDdPacketTask = new InternalRxmtDdPacket(ch);
        startRxMtDdTimer(ch);

        //setting destination ip
        ddPacket.setDestinationIp(neighborIpAddr());
        setLastSentDdPacket(ddPacket);
        byte[] messageToWrite = getMessage(ddPacket);
        ch.write(messageToWrite);
    }
}
 
Example 20
Source File: ShuffleHandler.java    From big-c with Apache License 2.0 4 votes vote down vote up
protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch,
    String user, String mapId, int reduce, MapOutputInfo mapOutputInfo)
    throws IOException {
  final IndexRecord info = mapOutputInfo.indexRecord;
  final ShuffleHeader header =
    new ShuffleHeader(mapId, info.partLength, info.rawLength, reduce);
  final DataOutputBuffer dob = new DataOutputBuffer();
  header.write(dob);
  ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
  final File spillfile =
      new File(mapOutputInfo.mapOutputFileName.toString());
  RandomAccessFile spill;
  try {
    spill = SecureIOUtils.openForRandomRead(spillfile, "r", user, null);
  } catch (FileNotFoundException e) {
    LOG.info(spillfile + " not found");
    return null;
  }
  ChannelFuture writeFuture;
  if (ch.getPipeline().get(SslHandler.class) == null) {
    final FadvisedFileRegion partition = new FadvisedFileRegion(spill,
        info.startOffset, info.partLength, manageOsCache, readaheadLength,
        readaheadPool, spillfile.getAbsolutePath(), 
        shuffleBufferSize, shuffleTransferToAllowed);
    writeFuture = ch.write(partition);
    writeFuture.addListener(new ChannelFutureListener() {
        // TODO error handling; distinguish IO/connection failures,
        //      attribute to appropriate spill output
      @Override
      public void operationComplete(ChannelFuture future) {
        if (future.isSuccess()) {
          partition.transferSuccessful();
        }
        partition.releaseExternalResources();
      }
    });
  } else {
    // HTTPS cannot be done with zero copy.
    final FadvisedChunkedFile chunk = new FadvisedChunkedFile(spill,
        info.startOffset, info.partLength, sslFileBufferSize,
        manageOsCache, readaheadLength, readaheadPool,
        spillfile.getAbsolutePath());
    writeFuture = ch.write(chunk);
  }
  metrics.shuffleConnections.incr();
  metrics.shuffleOutputBytes.incr(info.partLength); // optimistic
  return writeFuture;
}