Example usage for io.netty.channel ChannelHandlerContext attr

List of usage examples for io.netty.channel ChannelHandlerContext attr

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext attr.

Prototype

@Deprecated
@Override
<T> Attribute<T> attr(AttributeKey<T> key);

Source Link

Usage

From source file:org.eclipse.scada.protocol.relp.FrameCodec.java

License:Open Source License

private void processTRAILER(final ChannelHandlerContext ctx, final byte b, final ByteBuf msg) {
    if (b != Constants.LF) {
        throw new CodecException(
                String.format("Expected trailer byte (LF) but found 0x%02X: Remaining buffer: %s", b,
                        ByteBufUtil.hexDump(msg, msg.readerIndex(), msg.readableBytes())));
    }//from  w w  w .j a  v a 2 s  .  c o  m

    final int length = ctx.attr(ATTR_EXPECTED_LENGTH).get();
    final long txnr = Long.parseLong(ctx.attr(ATTR_TXNR_BUFFER).get().toString(TXNR_CHARSET));
    final String command = ctx.attr(ATTR_COMMAND_BUFFER).get().toString(COMMAND_CHARSET);
    final ByteBuf data = ctx.attr(ATTR_DATA_BUFFER).get().readSlice(length);

    final Frame frame = new Frame(txnr, command, data);

    ctx.fireChannelRead(frame);

    ctx.attr(ATTR_STATE).set(State.TXNR);
    ctx.attr(ATTR_TXNR_BUFFER).get().clear();
    ctx.attr(ATTR_COMMAND_BUFFER).get().clear();
    ctx.attr(ATTR_LENGTH_BUFFER).get().clear();
    ctx.attr(ATTR_DATA_BUFFER).get().clear();
}

From source file:org.eclipse.scada.protocol.relp.FrameCodec.java

License:Open Source License

private void processDATA(final ChannelHandlerContext ctx, final byte b) {
    final ByteBuf data = ctx.attr(ATTR_DATA_BUFFER).get();
    data.writeByte(b);//from ww w .ja v a 2  s . c o  m
    if (data.readableBytes() >= ctx.attr(ATTR_EXPECTED_LENGTH).get()) {
        ctx.attr(ATTR_STATE).set(State.TRAILER);
    }
}

From source file:org.eclipse.scada.protocol.relp.FrameCodec.java

License:Open Source License

private void processLENGTH(final ChannelHandlerContext ctx, final byte b) {
    final ByteBuf lengthBuffer = ctx.attr(ATTR_LENGTH_BUFFER).get();

    if (b == Constants.SP || lengthBuffer.readableBytes() > 0 && b == Constants.LF) {
        // either we have a SP or at least one byte (possibly "0") and a LF

        final int length = Integer.parseInt(lengthBuffer.toString(LENGTH_CHARSET));

        ctx.attr(ATTR_EXPECTED_LENGTH).set(length);
        ctx.attr(ATTR_STATE).set(State.DATA);
    } else {//from  w w  w  .ja v  a 2s.  c  o m
        lengthBuffer.writeByte(b);
    }
}

From source file:org.eclipse.scada.protocol.relp.FrameCodec.java

License:Open Source License

private void processCOMMAND(final ChannelHandlerContext ctx, final byte b) {
    if (b == Constants.SP) {
        ctx.attr(ATTR_STATE).set(State.LENGTH);
    } else {/* w ww  .  j  a  v a 2 s .co  m*/
        ctx.attr(ATTR_COMMAND_BUFFER).get().writeByte(b);
    }
}

From source file:org.eclipse.scada.protocol.relp.FrameCodec.java

License:Open Source License

private void processTXNR(final ChannelHandlerContext ctx, final byte b) {
    if (b == Constants.SP) {
        ctx.attr(ATTR_STATE).set(State.COMMAND);
    } else {//from ww w .  j  ava2  s. c om
        if (b < 0x30 || b > 0x39) {
            throw new CodecException(String.format("Invalid character found: 0x%1$02x (%1$s)", b, (char) b));
        }
        ctx.attr(ATTR_TXNR_BUFFER).get().writeByte(b);
    }
}

From source file:org.hawkular.metrics.clients.ptrans.MetricBatcher.java

License:Apache License

/**
 * Batch up incoming SingleMetric messages. If the #minimumBatchSize is not yet reached, the messages are stored
 * locally. Otherwise the list of messages will be forwarded to the next handler.
 * This method will be called for each written message that can be handled
 * by this encoder.//from  ww  w  .j a  va 2  s .  c  o m
 *
 * @param ctx           the {@link ChannelHandlerContext} which this {@link MessageToMessageDecoder} belongs to
 * @param msg           the SingleMetric to be batched up
 * @param out           the {@link List} to which decoded messages should be added if the batch size is reached
 * @throws Exception    is thrown if an error occurs
 */
@Override
protected void decode(ChannelHandlerContext ctx, SingleMetric msg, List<Object> out) throws Exception {
    LOG.trace("Incoming metric for key '{}'", cacheKey.name());
    Attribute<List<SingleMetric>> cache = ctx.attr(cacheKey);
    List<SingleMetric> batchList = cache.get();
    if (batchList == null) {
        LOG.trace("Creating new batch list for key '{}'", cacheKey.name());
        batchList = new ArrayList<>(minimumBatchSize);
        cache.set(batchList);
    }
    batchList.add(msg);
    if (batchList.size() >= minimumBatchSize) {
        LOG.trace("Batch size limit '{}' reached for key '{}'", minimumBatchSize, cacheKey.name());
        cache.remove();
        out.add(batchList);
    }
}

From source file:org.hawkular.metrics.clients.ptrans.MetricBatcher.java

License:Apache License

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (!(evt instanceof IdleStateEvent)) {
        LOG.trace("Dropping unhandled event '{}' for key '{}'", evt, cacheKey.name());
        return;// www  .j a  va 2 s.c o m
    }
    IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
    if (idleStateEvent != IdleStateEvent.FIRST_READER_IDLE_STATE_EVENT) {
        LOG.trace("Dropping event, expecting FIRST_READER_IDLE_STATE_EVENT for key '{}'", cacheKey.name());
        return;
    }
    List<SingleMetric> batchList = ctx.attr(cacheKey).getAndRemove();
    if (batchList != null && !batchList.isEmpty()) {
        LOG.trace("Batch delay reached for key '{}', forwarding {} metrics", cacheKey.name(), batchList.size());
        ctx.fireChannelRead(batchList);
    }
}

From source file:org.helios.octo.server.streams.StreamOutputAdapter.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, MessageList<Object> msgs, ChannelPromise promise) {
    MessageList<ByteBuf> buffers = msgs.cast();
    ByteBuf acc = ctx.attr(ACC).get();
    if (acc == null) {
        acc = Unpooled.buffer();//from ww w.j av a2  s  .c o  m
        ctx.attr(ACC).set(acc);
    }
    for (ByteBuf b : buffers) {
        acc.writeBytes(b);
    }
    msgs.releaseAllAndRecycle();
    while (true) {
        int loc = acc.bytesBefore(ByteBufIndexFinder.LF);
        if (loc == -1)
            break;
        ByteBuf buf = Unpooled.buffer(10);
        buf.writeLong(System.nanoTime()).writeByte(0).writeByte(streamType);
        //.writeBytes(acc.readBytes(loc+1));
        ChannelHandler se = ctx.pipeline().remove("stringEncoder");
        ctx.write(buf);
        ctx.pipeline().addAfter("out", "stringEncoder", se);
        byte[] bytes = new byte[loc];
        acc.readBytes(bytes);
        String s = new String(bytes);
        log.info("Writing out [" + s + "]");
        ctx.write(s + "\n");
    }
}

From source file:org.iotivity.cloud.ciserver.protocols.CoapRelayHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    if (msg instanceof CoapRequest) {
        CoapRequest request = (CoapRequest) msg;
        // Parse uri, send to RD
        String uriPath = request.getUriPath();
        CoapRequest accountRequest = null;
        String userId, deviceId, authPayload;
        CoapResponse response;//  w  ww. jav  a  2  s  . c o  m

        Logger.d("Request received, URI: " + uriPath);
        if (uriPath != null) {
            switch (uriPath) {
            case Constants.AUTH_URI:
                // This case user wants to logout
                String uriQuery = request.getUriQuery();
                if (uriQuery != null) {
                    if (uriQuery.endsWith("logout")) {
                        ctx.channel().attr(Constants.Attribute_UserId).remove();
                        response = new CoapResponse(CoapStatus.DELETED);
                    } else {
                        response = new CoapResponse(CoapStatus.BAD_REQUEST);
                    }
                    ctx.writeAndFlush(response);
                }
                break;

            case Constants.RD_URI:
                // RD POST means publish device to server
                switch (request.getRequestMethod()) {
                case POST:
                    userId = ctx.channel().attr(Constants.Attribute_UserId).get();
                    deviceId = request.decodeDeviceId();
                    authPayload = String.format("{\"userid\":\"%s\",\"deviceid\":\"%s\"}", userId, deviceId);
                    accountRequest = new CoapRequest(CoapMethod.POST);
                    accountRequest.setUriPath(Constants.ACCOUNT_URI);
                    accountRequest.setUriQuery("reqtype=publish");
                    accountRequest.setToken(request.getToken());
                    accountRequest.setPayload(authPayload.getBytes(StandardCharsets.UTF_8));

                    // TODO: deviceId must be registered after
                    // session
                    // granted
                    Logger.d("Adding deviceId to session: " + deviceId);
                    sessionManager.addSession(deviceId, ctx);
                    break;

                default:
                    Logger.e("Unsupported request type");
                    break;
                }

                rdClient.getChannelFuture().channel().attr(keyRDClient).set(ctx);

                // Add original request to list for future use
                asClient.getChannelFuture().channel().attr(keyAccountClient).get().add(request);
                asClient.sendRequest(accountRequest);
                return;

            case Constants.WELL_KNOWN_URI:
                switch (request.getRequestMethod()) {
                case GET:
                    userId = ctx.channel().attr(Constants.Attribute_UserId).get();
                    authPayload = String.format("{\"userid\":\"%s\"}", userId);
                    accountRequest = new CoapRequest(CoapMethod.GET);
                    accountRequest.setUriPath(Constants.ACCOUNT_URI);
                    accountRequest.setUriQuery("reqtype=find");
                    accountRequest.setToken(request.getToken());
                    accountRequest.setPayload(authPayload.getBytes(StandardCharsets.UTF_8));
                    break;

                default:
                    Logger.e("Unsupported request type");
                    break;
                }

                rdClient.getChannelFuture().channel().attr(keyRDClient).set(ctx);

                // Add original request to list for future use
                asClient.getChannelFuture().channel().attr(keyAccountClient).get().add(request);
                asClient.sendRequest(accountRequest);
                return;

            case Constants.KEEP_ALIVE_URI:
                break;

            default:
                List<String> uriPathList = request.getUriPathSegments();
                if (uriPathList != null) {
                    Logger.i("uriPahtList: " + uriPathList.toString());

                    String did = uriPathList.get(0);

                    Logger.i("did: " + did);

                    // TODO: Clustering algorithm required
                    // find ctx about did, and send msg
                    StringBuffer resource = new StringBuffer();
                    List<String> pathSegments = uriPathList.subList(1, uriPathList.size());
                    for (String path : pathSegments) {
                        resource.append("/");
                        resource.append(path);
                    }
                    Logger.i("resource: " + resource);
                    request.setUriPath(resource.toString());

                    ChannelHandlerContext deviceCtx = sessionManager.querySession(did);
                    if (deviceCtx != null) {
                        deviceCtx.attr(keyDevice).set(ctx);
                        deviceCtx.writeAndFlush(request);
                    } else {
                        Logger.e("deviceCtx is null");
                        response = new CoapResponse(CoapStatus.FORBIDDEN);
                        response.setToken(request.getToken());
                        ctx.writeAndFlush(response);
                    }
                }
                return;
            }
        }

    } else if (msg instanceof CoapResponse) {
        ChannelHandlerContext resourceClient = ctx.attr(keyDevice).get();
        if (resourceClient != null) {
            Logger.i("Forwards message to client");

            CoapResponse response = (CoapResponse) msg;

            // If response contains path, add di
            String did = sessionManager.queryDid(ctx);
            if (response.getOption(11) != null && did != null) {
                response.getOption(11).add(0, did.getBytes(StandardCharsets.UTF_8));
            }

            Logger.i("ctx.channel : " + resourceClient.channel().toString());
            resourceClient.writeAndFlush(response);
            return;
        }
    }

    super.channelRead(ctx, msg);
}

From source file:org.jboss.aerogear.sync.DiffSyncHandler.java

License:Apache License

@Override
protected void messageReceived(final ChannelHandlerContext ctx, final WebSocketFrame frame) throws Exception {
    if (frame instanceof CloseWebSocketFrame) {
        logger.debug("Received closeFrame");
        ctx.close();/* www . j  a  v a  2s .c om*/
        return;
    }

    if (frame instanceof TextWebSocketFrame) {
        final JsonNode json = JsonMapper.asJsonNode(((TextWebSocketFrame) frame).text());
        logger.info("Doc:" + json);
        switch (MessageType.from(json.get("msgType").asText())) {
        case ADD:
            final Document<String> doc = documentFromJson(json);
            final String clientId = json.get("clientId").asText();
            final PatchMessage patchMessage = addSubscriber(doc, clientId, ctx);
            ctx.attr(DOC_ADD).set(true);
            ctx.channel().writeAndFlush(textFrame(toJson(patchMessage)));
            break;
        case PATCH:
            final PatchMessage clientPatchMessage = JsonMapper.fromJson(json.toString(),
                    DefaultPatchMessage.class);
            checkForReconnect(clientPatchMessage.documentId(), clientPatchMessage.clientId(), ctx);
            logger.debug("Client Edits=" + clientPatchMessage);
            patch(clientPatchMessage);
            break;
        case DETACH:
            // detach the client from a specific document.
            break;
        case UNKNOWN:
            unknownMessageType(ctx, json);
            break;
        }
    } else {
        ctx.fireChannelRead(frame);
    }
}