Java 类org.jboss.netty.channel.Channel 实例源码

项目:athena    文件:OFMessageDecoder.java   
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
        ChannelBuffer buffer) throws Exception {
    if (!channel.isConnected()) {
        // In testing, I see decode being called AFTER decode last.
        // This check avoids that from reading corrupted frames
        return null;
    }

    // Note that a single call to decode results in reading a single
    // OFMessage from the channel buffer, which is passed on to, and processed
    // by, the controller (in OFChannelHandler).
    // This is different from earlier behavior (with the original openflowj),
    // where we parsed all the messages in the buffer, before passing on
    // a list of the parsed messages to the controller.
    // The performance *may or may not* not be as good as before.
    OFMessageReader<OFMessage> reader = OFFactories.getGenericReader();
    OFMessage message = reader.readFrom(buffer);

    return message;
}
项目:iTAP-controller    文件:AbstractRPCChannelHandler.java   
/**
 * Handle a generic {@link SyncMessage} and dispatch to an appropriate
 * handler
 * @param bsm the message
 * @param channel the channel on which the message arrived
 */
protected void handleSyncMessage(SyncMessage bsm, Channel channel) {
    switch (channelState) {
        case OPEN:
        case CONNECTED:
            switch (bsm.getType()) {
                case HELLO:
                    handshake(bsm.getHello(), channel);
                    break;
                case ECHO_REQUEST:
                    handleEchoRequest(bsm.getEchoRequest(), channel);
                    break;
                case ERROR:
                    handleError(bsm.getError(), channel);
                    break;
                default:
                    // ignore
            }
            break;
        case AUTHENTICATED:
            handleSMAuthenticated(bsm, channel);
            break;
    }
}
项目:traccar-service    文件:Gps056FrameDecoder.java   
@Override
protected Object decode(
        ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {

    if (buf.readableBytes() >= MESSAGE_HEADER) {
        int length = Integer.parseInt(buf.toString(2, 2, StandardCharsets.US_ASCII)) + 5;
        if (buf.readableBytes() >= length) {
            ChannelBuffer frame = buf.readBytes(length);
            while (buf.readable() && buf.getUnsignedByte(buf.readerIndex()) != '$') {
                buf.readByte();
            }
            return frame;
        }
    }

    return null;
}
项目:athena    文件:OspfNbrImplTest.java   
/**
 * Tests adjOk() method.
 */
@Test
public void testAdjOk() throws Exception {
    channel = EasyMock.createMock(Channel.class);
    ospfInterface.setInterfaceType(OspfInterfaceType.BROADCAST.value());
    ospfInterface.setIpAddress(Ip4Address.valueOf("2.2.2.2"));
    ospfNbr1 = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("1.1.1.1"),
                               Ip4Address.valueOf("2.2.2.2"), 2,
                               topologyForDeviceAndLink);
    ospfNbr1.setState(OspfNeighborState.TWOWAY);
    ospfNbr1.setNeighborDr(Ip4Address.valueOf("2.2.2.2"));
    ospfNbr1.adjOk(channel);
    assertThat(ospfNbr1, is(notNullValue()));

    ospfInterface.setInterfaceType(OspfInterfaceType.POINT_TO_POINT.value());
    ospfNbr1 = new OspfNbrImpl(ospfArea, ospfInterface, Ip4Address.valueOf("1.1.1.1"),
                               Ip4Address.valueOf("2.2.2.2"), 2,
                               topologyForDeviceAndLink);
    channel = null;
    channel = EasyMock.createMock(Channel.class);
    ospfNbr1.adjOk(channel);
    assertThat(ospfNbr1, is(notNullValue()));
}
项目:hadoop    文件:TestRpcProgramNfs3.java   
@Test(timeout = 60000)
public void testCommit() throws Exception {
  HdfsFileStatus status = nn.getRpcServer().getFileInfo("/tmp/bar");
  long dirId = status.getFileId();
  FileHandle handle = new FileHandle(dirId);
  XDR xdr_req = new XDR();
  COMMIT3Request req = new COMMIT3Request(handle, 0, 5);
  req.serialize(xdr_req);

  Channel ch = Mockito.mock(Channel.class);

  // Attempt by an unpriviledged user should fail.
  COMMIT3Response response1 = nfsd.commit(xdr_req.asReadOnlyWrap(),
      ch, 1, securityHandlerUnpriviledged,
      new InetSocketAddress("localhost", 1234));
  assertEquals("Incorrect return code:", Nfs3Status.NFS3ERR_ACCES,
      response1.getStatus());

  // Attempt by a priviledged user should pass.
  COMMIT3Response response2 = nfsd.commit(xdr_req.asReadOnlyWrap(),
      ch, 1, securityHandler,
      new InetSocketAddress("localhost", 1234));
  assertEquals("Incorrect COMMIT3Response:", null, response2);
}
项目:hadoop    文件:OpenFileCtx.java   
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;  
  }
}
项目:traccar-service    文件:IntellitracFrameDecoder.java   
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {

    // Check minimum length
    if (buf.readableBytes() < MESSAGE_MINIMUM_LENGTH) {
        return null;
    }

    // Check for sync packet
    if (buf.getUnsignedShort(buf.readerIndex()) == 0xFAF8) {
        ChannelBuffer syncMessage = buf.readBytes(8);
        if (channel != null) {
            channel.write(syncMessage);
        }
    }

    return super.decode(ctx, channel, buf);
}
项目:traccar-service    文件:Gt06ProtocolDecoder.java   
private void sendPhotoRequest(Channel channel, int pictureId) {
    if (channel != null) {
        ChannelBuffer photo = photos.get(pictureId);
        ChannelBuffer response = ChannelBuffers.dynamicBuffer();
        response.writeShort(0x7878); // header
        response.writeByte(15); // size
        response.writeByte(MSG_X1_PHOTO_DATA);
        response.writeInt(pictureId);
        response.writeInt(photo.writerIndex());
        response.writeShort(Math.min(photo.writableBytes(), 1024));
        response.writeShort(++serverIndex);
        response.writeShort(Checksum.crc16(Checksum.CRC16_X25,
                response.toByteBuffer(2, response.writerIndex() - 2)));
        response.writeByte('\r'); response.writeByte('\n'); // ending
        channel.write(response);
    }
}
项目:iTAP-controller    文件:RPCChannelHandler.java   
@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));
    }
}
项目:iTAP-controller    文件:ThriftFrameEncoder.java   
@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;
}
项目:athena    文件:OspfNbrImpl.java   
/**
 * At this point, the router has sent and received an entire sequence of DD packets.
 * Now it must be determined whether the new state is FULL, or LS Request packets
 * have to be send.
 *
 * @param message OSPF message instance
 * @param ch      netty channel handler
 */
public void exchangeDone(OspfMessage message, Channel ch) {
    log.debug("OSPFNbr::exchangeDone...!!!");
    stopRxMtDdTimer();

    OspfPacketHeader header = (OspfPacketHeader) message;

    if (state == OspfNeighborState.EXCHANGE) {
        if (lsReqList.isEmpty()) {
            state = OspfNeighborState.FULL;
            //handler.addDeviceInformation(this);
            //handler.addLinkInformation(this, topLevelTlvs);
        } else {
            state = OspfNeighborState.LOADING;
            LsRequest lsRequest = buildLsRequest();
            //Setting the destination address
            lsRequest.setDestinationIp(header.sourceIp());
            byte[] messageToWrite = getMessage(lsRequest);
            ch.write(messageToWrite);

            setLastSentLsrPacket(lsRequest);
            startRxMtLsrTimer(ch);
        }
    }
}
项目:traccar-service    文件:AdmProtocolDecoder.java   
private Position parseCommandResponse(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) {
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
    if (deviceSession == null) {
        return null;
    }

    Position position = new Position();
    position.setProtocol(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    getLastLocation(position, null);

    int responseTextLength = buf.bytesBefore((byte) 0);
    if (responseTextLength < 0) {
        responseTextLength = CMD_RESPONSE_SIZE - 3;
    }
    position.set(Position.KEY_RESULT, buf.readBytes(responseTextLength).toString(StandardCharsets.UTF_8));

    return position;
}
项目:Elasticsearch    文件:NettyTransport.java   
public boolean hasChannel(Channel channel) {
    for (Channel channel1 : allChannels) {
        if (channel.equals(channel1)) {
            return true;
        }
    }
    return false;
}
项目:athena    文件:OspfNbrImplTest.java   
/**
 * 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()));
}
项目:abhot    文件:VersionCommand.java   
@Override
public void execute(Channel chan, String[] command) throws DatastoreException
{
    m_counter.incrementAndGet();
    if (chan.isConnected())
    {
        Package thisPackage = getClass().getPackage();
        String versionString = thisPackage.getImplementationTitle()+" "+thisPackage.getImplementationVersion();
        chan.write(versionString+"\n");
    }
}
项目:voyage    文件:NettyRpcConnection.java   
/**
 * 尝试连接
 */
public void connect() {
       ChannelFuture future = bootstrap.connect(inetAddr);
       try{
           boolean ret = future.awaitUninterruptibly(Constants.TIMEOUT_CONNECTION_MILLSECOND, TimeUnit.MILLISECONDS);
           if (ret && future.isSuccess()) {
               Channel newChannel = future.getChannel();
               newChannel.setInterestOps(Channel.OP_READ_WRITE);
               try {
                   // 关闭旧的连接
                   Channel oldChannel = NettyRpcConnection.this.channel;
                   if (oldChannel != null) {
                       logger.info("Close old netty channel {} on create new netty channel {}", oldChannel, newChannel);
                       oldChannel.close();
                   }
               } finally {
                   if (!isConnected()) {
                       try {
                           logger.info("Close new netty channel {}, because the client closed.", newChannel);
                           newChannel.close();
                       } finally {
                        NettyRpcConnection.this.channel = null;
                       }
                   } else {
                    NettyRpcConnection.this.channel = newChannel;
                   }
               }
           } else if (null != future.getCause()) {
            logger.error("connect fail", future.getCause());
            throw new RuntimeException("connect error", future.getCause());
           } else {
            logger.error("connect fail,connstr: "+this.getConnStr());
            throw new RuntimeException("connect error");
           }
       }finally{
           if (! isConnected()) {
               future.cancel();
           }
       }
}
项目:athena    文件:OspfNbrImpl.java   
/**
 * Starts Ls request retransmission executor task.
 *
 * @param ch Netty channel instance
 */
private void startRxMtLsrTimer(Channel ch) {
    if (!rxmtLsrTimerScheduled) {
        log.debug("OSPFNbr::startRxMtLsrTimer...!!!");
        long retransmitIntrvl = ospfInterface.reTransmitInterval();
        rxmtLsrPacketTask = new InternalRxmtLsrPacket(ch);
        exServiceRxmtLsr = Executors.newSingleThreadScheduledExecutor();
        exServiceRxmtLsr.scheduleAtFixedRate(rxmtLsrPacketTask, retransmitIntrvl,
                                             retransmitIntrvl, TimeUnit.SECONDS);
        rxmtLsrTimerScheduled = true;
    }
}
项目:EatDubbo    文件:NettyClient.java   
@Override
protected com.alibaba.dubbo.remoting.Channel getChannel() {
    Channel c = channel;
    if (c == null || ! c.isConnected())
        return null;
    return NettyChannel.getOrAddChannel(c, getUrl(), this);
}
项目:hadoop    文件:TestDelegationTokenRemoteFetcher.java   
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
    throws Exception {
  Channel ch = e.getChannel();
  Throwable cause = e.getCause();

  if (LOG.isDebugEnabled())
    LOG.debug(cause.getMessage());
  ch.close().addListener(ChannelFutureListener.CLOSE);
}
项目:iTAP-controller    文件:RemoteSyncChannelHandler.java   
@Override
protected void handleHello(HelloMessage hello, Channel channel) {
    syncManager.remoteNodeId = hello.getNodeId();
    syncManager.ready = true;
    synchronized (syncManager.readyNotify) {
        syncManager.notifyAll();
    }
}
项目:traccar-service    文件:Gl200TextProtocolDecoder.java   
private Object decodeOther(Channel channel, SocketAddress remoteAddress, String sentence, String type) {
    Parser parser = new Parser(PATTERN, sentence);
    Position position = initPosition(parser, channel, remoteAddress);
    if (position == null) {
        return null;
    }

    int reportType = parser.nextInt(0);
    if (type.equals("NMR")) {
        position.set(Position.KEY_MOTION, reportType == 1);
    } else if (type.equals("SOS")) {
        position.set(Position.KEY_ALARM, Position.ALARM_SOS);
    }

    decodeLocation(position, parser);

    position.set(Position.KEY_ODOMETER, parser.nextDouble(0) * 1000);
    position.set(Position.KEY_BATTERY_LEVEL, parser.nextInt(0));

    position.set(Position.KEY_ODOMETER, parser.nextDouble(0) * 1000);

    decodeDeviceTime(position, parser);

    if (Context.getConfig().getBoolean(getProtocolName() + ".ack") && channel != null) {
        channel.write("+SACK:" + parser.next() + "$", remoteAddress);
    }

    return position;
}
项目:iTAP-controller    文件:RemoteSyncChannelHandler.java   
@Override
protected void handleCursorResponse(CursorResponseMessage response,
                                    Channel channel) {
    SyncReply reply = new SyncReply(null, response.getValues(), true, 
                                    null, response.getCursorId());
    syncManager.dispatchReply(response.getHeader().getTransactionId(), 
                              reply);
}
项目:traccar-service    文件:MxtFrameDecoder.java   
@Override
protected Object decode(
        ChannelHandlerContext ctx,
        Channel channel,
        ChannelBuffer buf) throws Exception {

    if (buf.readableBytes() < 2) {
        return null;
    }

    int index = buf.indexOf(buf.readerIndex() + 1, buf.writerIndex(), (byte) 0x04);
    if (index != -1) {
        ChannelBuffer result = ChannelBuffers.buffer(ByteOrder.LITTLE_ENDIAN, index + 1 - buf.readerIndex());

        while (buf.readerIndex() <= index) {
            int b = buf.readUnsignedByte();
            if (b == 0x10) {
                result.writeByte(buf.readUnsignedByte() - 0x20);
            } else {
                result.writeByte(b);
            }
        }

        return result;
    }

    return null;
}
项目:athena    文件:DefaultIsisInterface.java   
/**
 * 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));
    }
}
项目:Elasticsearch    文件:NettyTransportChannel.java   
public NettyTransportChannel(NettyTransport transport, TransportServiceAdapter transportServiceAdapter, String action, Channel channel, long requestId, Version version, String profileName) {
    this.transportServiceAdapter = transportServiceAdapter;
    this.version = version;
    this.transport = transport;
    this.action = action;
    this.channel = channel;
    this.requestId = requestId;
    this.profileName = profileName;
}
项目:athena    文件:DefaultIsisInterface.java   
/**
 * 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));
    }
}
项目:traccar-service    文件:OwnTracksProtocolDecoder.java   
private void sendResponse(Channel channel, HttpResponseStatus status) {
    if (channel != null) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
        response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
        channel.write(response);
    }
}
项目:traccar-service    文件:TotemFrameDecoder.java   
@Override
protected Object decode(
        ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {

    if (buf.readableBytes() < 10) {
        return null;
    }

    int beginIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), new StringFinder("$$"));
    if (beginIndex == -1) {
        return null;
    } else if (beginIndex > buf.readerIndex()) {
        buf.readerIndex(beginIndex);
    }

    int length;

    int flagIndex = buf.indexOf(buf.readerIndex(), buf.writerIndex(), new StringFinder("AA"));
    if (flagIndex != -1 && flagIndex - beginIndex == 6) {
        length = Integer.parseInt(buf.toString(buf.readerIndex() + 2, 4, StandardCharsets.US_ASCII));
    } else {
        length = Integer.parseInt(buf.toString(buf.readerIndex() + 2, 2, StandardCharsets.US_ASCII), 16);
    }

    if (length <= buf.readableBytes()) {
        return buf.readBytes(length);
    }

    return null;
}
项目:athena    文件:BgpMessageDecoder.java   
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
    log.debug("MESSAGE IS RECEIVED.");
    if (!channel.isConnected()) {
        log.info("Channel is not connected.");
        return null;
    }

    HexDump.dump(buffer);

    BgpMessageReader<BgpMessage> reader = BgpFactories.getGenericReader();
    List<BgpMessage> msgList = (List<BgpMessage>) ctx.getAttachment();

    if (msgList == null) {
        msgList = new LinkedList<>();
    }

    try {
        while (buffer.readableBytes() > 0) {
            buffer.markReaderIndex();
            BgpHeader bgpHeader = new BgpHeader();
            BgpMessage message = reader.readFrom(buffer, bgpHeader);
            msgList.add(message);
        }

        return msgList;
    } catch (Exception e) {
        log.debug("Bgp protocol message decode error");
        buffer.resetReaderIndex();
        buffer.discardReadBytes();
        ctx.setAttachment(msgList);
    }
    return null;
}
项目:dubbocloud    文件:NettyCodecAdapter.java   
@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());
}
项目:traccar-service    文件:GranitProtocolDecoder.java   
private static void sendResponseArchive(Channel channel, int deviceId, int packNum) {
    ChannelBuffer response = ChannelBuffers.dynamicBuffer(ByteOrder.LITTLE_ENDIAN, 0);
    response.writeBytes("BB+ARCF~".getBytes(StandardCharsets.US_ASCII));
    response.writeShort(4); // length
    response.writeShort(packNum);
    response.writeShort(deviceId);
    appendChecksum(response, 14);
    channel.write(response);
}
项目:traccar-service    文件:TrakMateProtocolDecoder.java   
private Object decodeAlt(Channel channel, SocketAddress remoteAddress, String sentence) {

        Parser parser = new Parser(PATTERN_ALT, sentence);
        if (!parser.matches()) {
            return null;
        }

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next());
        if (deviceSession == null) {
            return null;
        }

        Position position = new Position();
        position.setProtocol(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        parser.next(); // seq
        position.set(Position.KEY_ALARM, decodeAlarm(parser.nextInt(0)));
        parser.next(); // alert status or data

        position.setLatitude(parser.nextDouble(0));
        position.setLongitude(parser.nextDouble(0));

        position.setTime(parser.nextDateTime(Parser.DateTimeFormat.HMS_DMY));

        position.setSpeed(parser.nextDouble(0));
        position.setCourse(parser.nextDouble(0));

        return position;
    }
项目:traccar-service    文件:HuaShengFrameDecoder.java   
@Override
protected Object decode(
        ChannelHandlerContext ctx,
        Channel channel,
        ChannelBuffer buf) throws Exception {

    if (buf.readableBytes() < 2) {
        return null;
    }

    int index = buf.indexOf(buf.readerIndex() + 1, buf.writerIndex(), (byte) 0xC0);
    if (index != -1) {
        ChannelBuffer result = ChannelBuffers.buffer(index + 1 - buf.readerIndex());

        while (buf.readerIndex() <= index) {
            int b = buf.readUnsignedByte();
            if (b == 0xDB) {
                int ext = buf.readUnsignedByte();
                if (ext == 0xDC) {
                    result.writeByte(0xC0);
                } else if (ext == 0xDD) {
                    result.writeByte(0xDB);
                }
            } else {
                result.writeByte(b);
            }
        }

        return result;
    }

    return null;
}
项目:Elasticsearch    文件:NettyTransport.java   
/**
 * Disconnects from a node, only if the relevant channel is found to be part of the node channels.
 */
protected boolean disconnectFromNode(DiscoveryNode node, Channel channel, String reason) {
    // this might be called multiple times from all the node channels, so do a lightweight
    // check outside of the lock
    NodeChannels nodeChannels = connectedNodes.get(node);
    if (nodeChannels != null && nodeChannels.hasChannel(channel)) {
        connectionLock.acquire(node.id());
        try {
            nodeChannels = connectedNodes.get(node);
            // check again within the connection lock, if its still applicable to remove it
            if (nodeChannels != null && nodeChannels.hasChannel(channel)) {
                connectedNodes.remove(node);
                try {
                    logger.debug("disconnecting from [{}], {}", node, reason);
                    nodeChannels.close();
                } finally {
                    logger.trace("disconnected from [{}], {}", node, reason);
                    transportServiceAdapter.raiseNodeDisconnected(node);
                }
                return true;
            }
        } finally {
            connectionLock.release(node.id());
        }
    }
    return false;
}
项目:Elasticsearch    文件:NettyTransport.java   
public void start() {
    List<Channel> newAllChannels = new ArrayList<>();
    newAllChannels.addAll(Arrays.asList(recovery));
    newAllChannels.addAll(Arrays.asList(bulk));
    newAllChannels.addAll(Arrays.asList(reg));
    newAllChannels.addAll(Arrays.asList(state));
    newAllChannels.addAll(Arrays.asList(ping));
    this.allChannels = Collections.unmodifiableList(newAllChannels);
}
项目:Elasticsearch    文件:NettyTransport.java   
public NodeChannels(Channel[] recovery, Channel[] bulk, Channel[] reg, Channel[] state, Channel[] ping) {
    this.recovery = recovery;
    this.bulk = bulk;
    this.reg = reg;
    this.state = state;
    this.ping = ping;
}
项目:athena    文件:DefaultIsisInterface.java   
/**
 * Starts the hello timer which sends hello packet every configured seconds.
 *
 * @param channel netty channel instance
 */
public void startHelloSender(Channel channel) {
    log.debug("IsisInterfaceImpl::startHelloSender");
    if (!helloSenderStarted) {
        isisHelloPduSender = new IsisHelloPduSender(channel, this);
        exServiceHello = Executors.newSingleThreadScheduledExecutor();
        final ScheduledFuture<?> helloHandle =
                exServiceHello.scheduleAtFixedRate(isisHelloPduSender, 0,
                                                   helloInterval, TimeUnit.SECONDS);
        helloSenderStarted = true;
    }
}
项目:traccar-service    文件:H02ProtocolDecoder.java   
private Position decodeLink(String sentence, Channel channel, SocketAddress remoteAddress) {

        Parser parser = new Parser(PATTERN_LINK, sentence);
        if (!parser.matches()) {
            return null;
        }

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, parser.next());
        if (deviceSession == null) {
            return null;
        }

        Position position = new Position();
        position.setProtocol(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        DateBuilder dateBuilder = new DateBuilder()
                .setTime(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0));

        position.set(Position.KEY_RSSI, parser.nextInt());
        position.set(Position.KEY_SATELLITES, parser.nextInt());
        position.set(Position.KEY_BATTERY_LEVEL, parser.nextInt());
        position.set(Position.KEY_STEPS, parser.nextInt());
        position.set("turnovers", parser.nextInt());

        dateBuilder.setDateReverse(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0));

        getLastLocation(position, dateBuilder.getDate());

        processStatus(position, parser.nextLong(16, 0));

        return position;
    }
项目:traccar-service    文件:TeltonikaProtocolDecoder.java   
@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ChannelBuffer buf = (ChannelBuffer) msg;

    if (connectionless) {
        return decodeUdp(channel, remoteAddress, buf);
    } else {
        return decodeTcp(channel, remoteAddress, buf);
    }
}
项目:traccar-service    文件:H02ProtocolDecoder.java   
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ChannelBuffer buf = (ChannelBuffer) msg;
    String marker = buf.toString(0, 1, StandardCharsets.US_ASCII);

    switch (marker) {
        case "*":
            String sentence = buf.toString(StandardCharsets.US_ASCII);
            int typeStart = sentence.indexOf(',', sentence.indexOf(',') + 1) + 1;
            int typeEnd = sentence.indexOf(',', typeStart);
            if (typeEnd > 0) {
                String type = sentence.substring(typeStart, typeEnd);
                switch (type) {
                    case "NBR":
                        return decodeLbs(sentence, channel, remoteAddress);
                    case "LINK":
                        return decodeLink(sentence, channel, remoteAddress);
                    case "V3":
                        return decodeV3(sentence, channel, remoteAddress);
                    default:
                        return decodeText(sentence, channel, remoteAddress);
                }
            } else {
                return null;
            }
        case "$":
            return decodeBinary(buf, channel, remoteAddress);
        case "X":
        default:
            return null;
    }
}