Java Code Examples for io.netty.channel.Channel#hasAttr()

The following examples show how to use io.netty.channel.Channel#hasAttr() . 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: PojoEndpointServer.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public void doOnClose(Channel channel) {
    Attribute<String> attrPath = channel.attr(PATH_KEY);
    PojoMethodMapping methodMapping = null;
    if (pathMethodMappingMap.size() == 1) {
        methodMapping = pathMethodMappingMap.values().iterator().next();
    } else {
        String path = attrPath.get();
        methodMapping = pathMethodMappingMap.get(path);
        if (methodMapping == null) {
            return;
        }
    }
    if (methodMapping.getOnClose() != null) {
        if (!channel.hasAttr(SESSION_KEY)) {
            return;
        }
        Object implement = channel.attr(POJO_KEY).get();
        try {
            methodMapping.getOnClose().invoke(implement,
                    methodMapping.getOnCloseArgs(channel));
        } catch (Throwable t) {
            logger.error(t);
        }
    }
}
 
Example 2
Source File: PojoEndpointServer.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public void doOnError(Channel channel, Throwable throwable) {
    Attribute<String> attrPath = channel.attr(PATH_KEY);
    PojoMethodMapping methodMapping = null;
    if (pathMethodMappingMap.size() == 1) {
        methodMapping = pathMethodMappingMap.values().iterator().next();
    } else {
        String path = attrPath.get();
        methodMapping = pathMethodMappingMap.get(path);
    }
    if (methodMapping.getOnError() != null) {
        if (!channel.hasAttr(SESSION_KEY)) {
            return;
        }
        Object implement = channel.attr(POJO_KEY).get();
        try {
            Method method = methodMapping.getOnError();
            Object[] args = methodMapping.getOnErrorArgs(channel, throwable);
            method.invoke(implement, args);
        } catch (Throwable t) {
            logger.error(t);
        }
    }
}
 
Example 3
Source File: PojoEndpointServer.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
public void doOnEvent(Channel channel, Object evt) {
    Attribute<String> attrPath = channel.attr(PATH_KEY);
    PojoMethodMapping methodMapping = null;
    if (pathMethodMappingMap.size() == 1) {
        methodMapping = pathMethodMappingMap.values().iterator().next();
    } else {
        String path = attrPath.get();
        methodMapping = pathMethodMappingMap.get(path);
    }
    if (methodMapping.getOnEvent() != null) {
        if (!channel.hasAttr(SESSION_KEY)) {
            return;
        }
        Object implement = channel.attr(POJO_KEY).get();
        try {
            methodMapping.getOnEvent().invoke(implement, methodMapping.getOnEventArgs(channel, evt));
        } catch (Throwable t) {
            logger.error(t);
        }
    }
}
 
Example 4
Source File: PushRespHandler.java    From GoPush with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void call(ChannelHandlerContext context, PushResp message) {
    Channel channel = context.channel();
    if (!channel.hasAttr(Constants.CHANNEL_ATTR_HANDSHAKE)) {
        log.warn("channel not handshake, channel:{}", channel);
        context.close();
        return;
    }
    //接收成功后,将推送的消息置换成已读或删除等操作
    if (PushResp.Result.S.equals(message.getResult()) || PushResp.Result.D.equals(message.getResult())) {
        putMsg(message);
        log.info("receive pushResp, device:{}, msg_id:{}, result:{}!", message.getDevice(), message.getMsgId(), message.getResult());
    } else {
        log.warn("receive pushResp, device:{}, msg_id:{}, result:{}", message.getDevice(), message.getMsgId(), message.getResult());
    }

}
 
Example 5
Source File: RequestParamMapMethodArgumentResolver.java    From netty-websocket-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception {
    RequestParam ann = parameter.getParameterAnnotation(RequestParam.class);
    String name = ann.name();
    if (name.isEmpty()) {
        name = parameter.getParameterName();
        if (name == null) {
            throw new IllegalArgumentException(
                    "Name for argument type [" + parameter.getNestedParameterType().getName() +
                            "] not available, and parameter name information not found in class file either.");
        }
    }

    if (!channel.hasAttr(REQUEST_PARAM)) {
        QueryStringDecoder decoder = new QueryStringDecoder(((FullHttpRequest) object).uri());
        channel.attr(REQUEST_PARAM).set(decoder.parameters());
    }

    Map<String, List<String>> requestParams = channel.attr(REQUEST_PARAM).get();
    MultiValueMap multiValueMap = new LinkedMultiValueMap(requestParams);
    if (MultiValueMap.class.isAssignableFrom(parameter.getParameterType())) {
        return multiValueMap;
    } else {
        return multiValueMap.toSingleValueMap();
    }
}
 
Example 6
Source File: AgentHandler.java    From vlingo-http with Mozilla Public License 2.0 5 votes vote down vote up
private AgentChannelContext agentChannelContext(final ChannelHandlerContext context) {
  final Channel channel = context.channel();

  if (!channel.hasAttr(AGENT_CONTEXT)) {
    channel.attr(AGENT_CONTEXT).set(new AgentChannelContext(context, this));
  }

  return channel.attr(AGENT_CONTEXT).get();
}
 
Example 7
Source File: RejectionUtils.java    From zuul with Apache License 2.0 5 votes vote down vote up
private static boolean closeConnectionAfterReject(Channel channel) {
    if (channel.hasAttr(ATTR_HAPROXY_VERSION)) {
        return HAProxyProtocolVersion.V2 == channel.attr(ATTR_HAPROXY_VERSION).get();
    } else {
        return false;
    }
}
 
Example 8
Source File: Connection.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Return an existing {@link Connection} wrapper or create a simple new one
 *
 * @param channel channel to retrieve the connection reference from
 *
 * @return an existing {@link Connection} wrapper or create a simple new one
 */
static Connection from(Channel channel) {
	if(channel.hasAttr(ReactorNetty.CONNECTION)) {
		return channel.attr(ReactorNetty.CONNECTION)
		              .get();
	}
	return new ReactorNetty.SimpleConnection(channel).bind();
}
 
Example 9
Source File: PingPongProcessor.java    From GoPush with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 检测是否已经握手
 *
 * @param channel
 * @return
 */
protected boolean checkHandShake(Channel channel) {
    if (!channel.hasAttr(Constants.CHANNEL_ATTR_HANDSHAKE)) {
        log.warn("channel not handshake, channel:{}", channel);
        return Boolean.FALSE;
    }
    return Boolean.TRUE;
}
 
Example 10
Source File: DataCenterChannelStore.java    From GoPush with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void isDcChannelToRemove(Channel channel) {
    String dcId = null;
    if (!channel.hasAttr(Constants.CHANNEL_ATTR_DATACENTER)) {
        dcId = dataCenterId(channel);
    } else {
        dcId = channel.attr(Constants.CHANNEL_ATTR_DATACENTER).get();
    }
    if (contains(dcId)) {
        removeChannel(dcId, channel);
    }
}
 
Example 11
Source File: DataCenterChannelStore.java    From GoPush with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void isDcChannelToSave(Channel channel) {
    if (!channel.hasAttr(Constants.CHANNEL_ATTR_DATACENTER)) {
        //添加相应的值
        String dcId = dataCenterId(channel);
        channel.attr(Constants.CHANNEL_ATTR_DATACENTER).set(dcId);
        if (!contains(dcId)) {
            addChannel(dcId, channel);
        }
    }
}
 
Example 12
Source File: RequestParamMethodArgumentResolver.java    From netty-websocket-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, Channel channel, Object object) throws Exception {
    RequestParam ann = parameter.getParameterAnnotation(RequestParam.class);
    String name = ann.name();
    if (name.isEmpty()) {
        name = parameter.getParameterName();
        if (name == null) {
            throw new IllegalArgumentException(
                    "Name for argument type [" + parameter.getNestedParameterType().getName() +
                            "] not available, and parameter name information not found in class file either.");
        }
    }

    if (!channel.hasAttr(REQUEST_PARAM)) {
        QueryStringDecoder decoder = new QueryStringDecoder(((FullHttpRequest) object).uri());
        channel.attr(REQUEST_PARAM).set(decoder.parameters());
    }

    Map<String, List<String>> requestParams = channel.attr(REQUEST_PARAM).get();
    List<String> arg = (requestParams != null ? requestParams.get(name) : null);
    TypeConverter typeConverter = beanFactory.getTypeConverter();
    if (arg == null) {
        if ("\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n".equals(ann.defaultValue())) {
            return null;
        }else {
            return typeConverter.convertIfNecessary(ann.defaultValue(), parameter.getParameterType());
        }
    }
    if (List.class.isAssignableFrom(parameter.getParameterType())) {
        return typeConverter.convertIfNecessary(arg, parameter.getParameterType());
    } else {
        return typeConverter.convertIfNecessary(arg.get(0), parameter.getParameterType());
    }
}
 
Example 13
Source File: FtdcTraderApiAdapter.java    From ftdc with Apache License 2.0 5 votes vote down vote up
private FtdcTraderSpi getSpi(Channel ftdcChannel) {
	FtdcTraderSpi ftdcTraderSpi = null;
	Verify.verifyNotNull(ftdcChannel, "ftdcChannel is null");
	if(ftdcChannel.hasAttr(FtdcTraderSpi.TRADER_API)) {
		Attribute<FtdcTraderSpi> attr = ftdcChannel.attr(FtdcTraderSpi.TRADER_API);
		ftdcTraderSpi =  attr.get();
	}
	Verify.verifyNotNull(ftdcTraderSpi, "FtdcTraderSpi not register, pls register it first");
	return ftdcTraderSpi;
}
 
Example 14
Source File: Http2Handler.java    From xrpc with Apache License 2.0 4 votes vote down vote up
@Override
public void onHeadersRead(
    ChannelHandlerContext ctx,
    int streamId,
    Http2Headers headers,
    int padding,
    boolean endOfStream) {

  Channel channel = ctx.channel();
  ServerContext xctx = channel.attr(ServerContext.ATTRIBUTE_KEY).get();

  // Check if this is a new stream. This should either be a new stream, or be the set of
  // trailer-headers for a finished request.
  XrpcRequest request = requests.get(streamId);

  // Mark the request counter if this is a new stream.
  if (request == null) {
    xctx.requestMeter().mark();
  }

  // Rate limit if requested.
  if (channel.hasAttr(XrpcConstants.XRPC_SOFT_RATE_LIMITED)) {
    writeResponse(
        ctx,
        streamId,
        HttpResponseStatus.TOO_MANY_REQUESTS,
        Unpooled.wrappedBuffer(XrpcConstants.RATE_LIMIT_RESPONSE));
    return;
  }

  // Check content-length and short-circuit the channel if it's too big.
  long contentLength = 0;
  try {
    contentLength = headers.getLong(CONTENT_LENGTH, 0);
  } catch (NumberFormatException nfe) {
    // Malformed header, ignore.
    // This isn't supposed to happen, but does; see https://github.com/netty/netty/issues/7710 .
  }

  if (contentLength > maxPayloadBytes) {
    // Friendly short-circuit if someone intends to send us a huge payload.
    writeResponse(
        ctx,
        streamId,
        HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE,
        Unpooled.wrappedBuffer(XrpcConstants.PAYLOAD_EXCEEDED_RESPONSE));
    ctx.flush();
    ctx.close();
    return;
  }

  // Find the request handler. If we found a request for the stream already, the handler will be
  // in our handler map.
  Handler handler;
  if (request == null) {
    // Determine the handler for the request's path.
    String path = getPathFromHeaders(headers);
    CompiledRoutes.Match match = xctx.routes().match(path, headers.method().toString());
    request = new XrpcRequest(headers, xctx, match.getGroups(), channel);
    handler = match.getHandler();
  } else {
    // Add the new headers to the request.
    request.h2Headers().add(headers);
    handler = handlers.get(streamId);
  }

  // If there's no data expected, call the handler. Else, pass the handler and request through in
  // the context.
  if (endOfStream) {
    // Handle CORS.
    Optional<HttpResponse> corsResponse = corsHandler.inbound(headers, streamId);
    if (corsResponse.isPresent()) {
      writeResponse(ctx, streamId, corsResponse.get());
      return;
    }

    try {
      HttpResponse response = handler.handle(request);

      writeResponse(ctx, streamId, response);
    } catch (IOException e) {
      log.error("Error in handling Route", e);
      // Error
      ByteBuf buf = channel.alloc().directBuffer();
      buf.writeBytes("Error executing endpoint".getBytes(XrpcConstants.DEFAULT_CHARSET));
      writeResponse(ctx, streamId, HttpResponseStatus.INTERNAL_SERVER_ERROR, buf);
    }
  } else {
    // Save request & handler to use when the stream is ended.
    // Note that per the HTTP/2 protocol, endOfStream MUST have been set if this is a
    // trailer-part.
    requests.put(streamId, request);
    handlers.put(streamId, handler);
  }
}
 
Example 15
Source File: SessionHelper.java    From bitchat with Apache License 2.0 4 votes vote down vote up
public static String getSessionId(Channel channel) {
    return channel.hasAttr(SESSION_ID) ? channel.attr(SESSION_ID).get() : null;
}
 
Example 16
Source File: NettyPooledTransport.java    From async-gamequery-lib with MIT License 3 votes vote down vote up
/**
 * <p>A method to perform cleanup operations on a {@link Channel}. This is called after every invocation of {@link
 * #send(AbstractRequest)}.</p>
 *
 * @param c
 *         The {@link Channel} that will need to be cleaned-up/released.
 */
@Override
public void cleanupChannel(Channel c) {
    //Release channel from the pool
    if (c.hasAttr(ChannelAttributes.CHANNEL_POOL))
        c.attr(ChannelAttributes.CHANNEL_POOL).get().release(c);
}
 
Example 17
Source File: SessionHelper.java    From bitchat with Apache License 2.0 2 votes vote down vote up
/**
 * check whether the channel is login
 *
 * @param channel the channel
 * @return true if logged in otherwise false
 */
public static boolean hasLogin(Channel channel) {
    return channel.hasAttr(SESSION_ID) && channel.attr(SESSION_ID).get() != null;
}