Java Code Examples for io.netty.util.Attribute#set()

The following examples show how to use io.netty.util.Attribute#set() . 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: HttpsHostCaptureFilter.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        if (ProxyUtils.isCONNECT(httpRequest)) {
            Attribute<String> hostname = ctx.channel().attr(AttributeKey.valueOf(HOST_ATTRIBUTE_NAME));
            String hostAndPort = httpRequest.uri();

            // CONNECT requests contain the port, even when using the default port. a sensible default is to remove the
            // default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example)
            // would be unexpected.
            String hostNoDefaultPort = BrowserUpHttpUtil.removeMatchingPort(hostAndPort, 443);
            hostname.set(hostNoDefaultPort);
        }
    }

    return null;
}
 
Example 2
Source File: BlockingQueueHelper.java    From hanboDB with Apache License 2.0 6 votes vote down vote up
public void notifyListener(String key) {
    if (listenerMap.containsKey(key)) {
        List<ChannelHandlerContext> contextList = listenerMap.get(key);
        ListStore v = listenerRouters.get(key);
        //random assign a channel to receive data
        int randomVal = new Random().nextInt(contextList.size());
        Attribute attribute = contextList.get(randomVal).channel().attr(RedisCommandProcessorImpl.attributeKey);
        int position = (int) attribute.get();
        attribute.set(null);
        byte[] list_ = new byte[0];
        try {
            list_ = v.pop(key, position);
        } catch (RedisException e) {
            log.error("", e);
        }
        if (list_ != null) {
            Reply[] replies = new BulkReply[]{new BulkReply(key.getBytes()), new BulkReply(list_)};
            contextList.get(randomVal).writeAndFlush(new MultiBulkReply(replies));
            contextList.remove(randomVal);
            if (contextList.size() == 0) {
                listenerMap.clear();
                listenerRouters.clear();
            }
        }
    }
}
 
Example 3
Source File: HttpsHostCaptureFilter.java    From AndroidHttpCapture with MIT License 6 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        if (ProxyUtils.isCONNECT(httpRequest)) {
            Attribute<String> hostname = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.HOST_ATTRIBUTE_NAME));
            String hostAndPort = httpRequest.getUri();

            // CONNECT requests contain the port, even when using the default port. a sensible default is to remove the
            // default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example)
            // would be unexpected.
            String hostNoDefaultPort = BrowserMobHttpUtil.removeMatchingPort(hostAndPort, 443);
            hostname.set(hostNoDefaultPort);
        }
    }

    return null;
}
 
Example 4
Source File: HttpLifecycleChannelHandler.java    From zuul with Apache License 2.0 6 votes vote down vote up
protected static boolean fireCompleteEventIfNotAlready(ChannelHandlerContext ctx, CompleteReason reason)
{
    // Only allow this method to run once per request.
    Attribute<State> attr = ctx.channel().attr(ATTR_STATE);
    State state = attr.get();

    if (state == null || state != State.STARTED)
        return false;
    
    attr.set(State.COMPLETED);

    HttpRequest request = ctx.channel().attr(ATTR_HTTP_REQ).get();
    HttpResponse response = ctx.channel().attr(ATTR_HTTP_RESP).get();

    // Cleanup channel attributes.
    ctx.channel().attr(ATTR_HTTP_REQ).set(null);
    ctx.channel().attr(ATTR_HTTP_RESP).set(null);

    // Fire the event to whole pipeline.
    ctx.pipeline().fireUserEventTriggered(new CompleteEvent(reason, request, response));
    
    return true;
}
 
Example 5
Source File: NodeSessionService.java    From litchi with Apache License 2.0 5 votes vote down vote up
public void addSessionNode(String nodeType, String nodeId, NettySession session) {
    Map<String, Long> maps = sessionServerIdMaps.get(nodeType);
    if (maps == null) {
        maps = new ConcurrentHashMap<>();
        sessionServerIdMaps.put(nodeType, maps);
    }
    Attribute<String> typeAttr = session.attr(NettySession.FROM_NODE_TYPE);
    typeAttr.set(nodeType);
    Attribute<String> idAttr = session.attr(NettySession.FROM_NODE_ID);
    idAttr.set(nodeId);
    maps.put(nodeId, session.getSessionId());
}
 
Example 6
Source File: NodeManager.java    From nuls with MIT License 5 votes vote down vote up
private void cacheNode(Node node, SocketChannel channel) {

        String name = "node-" + node.getId();
        boolean exists = AttributeKey.exists(name);
        AttributeKey attributeKey;
        if (exists) {
            attributeKey = AttributeKey.valueOf(name);
        } else {
            attributeKey = AttributeKey.newInstance(name);
        }
        Attribute<Node> attribute = channel.attr(attributeKey);
        attribute.set(node);
    }
 
Example 7
Source File: TransportHelper.java    From journalkeeper with Apache License 2.0 5 votes vote down vote up
public static ChannelTransport getOrNewTransport(Channel channel, RequestBarrier requestBarrier) {
    Attribute<ChannelTransport> attr = channel.attr(TRANSPORT_CACHE_ATTR);
    ChannelTransport transport = attr.get();

    if (transport == null) {
        transport = newTransport(channel, requestBarrier);
        attr.set(transport);
    }

    return transport;
}
 
Example 8
Source File: Session.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
private EnumSet<CapabilityFlags> getCapabilities(Channel frontendChannel) {
	Attribute<EnumSet<CapabilityFlags>> attr = frontendChannel.attr(CAPABILITIES_ATTR);
	EnumSet<CapabilityFlags> capabilityFlags = attr.get();
	if (capabilityFlags == null) {
		capabilityFlags = CapabilityFlags.getImplicitCapabilities();
		attr.set(capabilityFlags);
	}
	return capabilityFlags;
}
 
Example 9
Source File: PojoEndpointServer.java    From netty-websocket-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private PojoMethodMapping getPojoMethodMapping(String path, Channel channel) {
    PojoMethodMapping methodMapping;
    if (pathMethodMappingMap.size() == 1) {
        methodMapping = pathMethodMappingMap.values().iterator().next();
    } else {
        Attribute<String> attrPath = channel.attr(PATH_KEY);
        attrPath.set(path);
        methodMapping = pathMethodMappingMap.get(path);
        if (methodMapping == null) {
            throw new RuntimeException("path " + path + " is not in pathMethodMappingMap ");
        }
    }
    return methodMapping;
}
 
Example 10
Source File: RegisterServiceImpl.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
public Response registerClient(String clientName) {
    LOG.debug("invoke registerClient::clientName = [{}]", clientName);
    RpcContext context = RpcContext.getContext();
    Channel channel = context.getChannel();
    Validate.notNull(channel, "rpc context channel cannot be null");
    Attribute<String> clientInfo = channel.attr(PushChannelContextHolder.CLIENTNAME_KEY);
    clientInfo.set(clientName);
    ChannelManager.getInstance().putChannel(clientName, channel);
    LOG.info("register channel success, Name={}, channel={}",
            clientName, channel.remoteAddress().toString());
    return Response.success();
}
 
Example 11
Source File: ConnectionManager.java    From nuls-v2 with MIT License 5 votes vote down vote up
private void cacheNode(Node node, SocketChannel channel) {

        String name = "node-" + node.getId();
        boolean exists = AttributeKey.exists(name);
        AttributeKey attributeKey;
        if (exists) {
            attributeKey = AttributeKey.valueOf(name);
        } else {
            attributeKey = AttributeKey.newInstance(name);
        }
        Attribute<Node> attribute = channel.attr(attributeKey);

        attribute.set(node);
    }
 
Example 12
Source File: Server.java    From zbus-server with MIT License 5 votes vote down vote up
private Session attachSession(ChannelHandlerContext ctx){
	Session sess = new NettySession(ctx);
	Attribute<String> attr = ctx.channel().attr(sessionKey); 
	attr.set(sess.id()); 
	sessionMap.put(sess.id(), sess);
	return sess;
}
 
Example 13
Source File: HttpsOriginalHostCaptureFilter.java    From Dream-Catcher with MIT License 5 votes vote down vote up
public HttpsOriginalHostCaptureFilter(HttpRequest originalRequest, ChannelHandlerContext ctx) {
    super(originalRequest, ctx);

    // if this is an HTTP CONNECT, set the isHttps attribute on the ChannelHandlerConect and capture the hostname from the original request.
    // capturing the original host (and the remapped/modified host in clientToProxyRequest() below) guarantees that we will
    // have the "true" host, rather than relying on the Host header in subsequent requests (which may be absent or spoofed by malicious clients).
    if (ProxyUtils.isCONNECT(originalRequest)) {
        Attribute<String> originalHostAttr = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.ORIGINAL_HOST_ATTRIBUTE_NAME));
        String hostAndPort = originalRequest.getUri();
        originalHostAttr.set(hostAndPort);

        Attribute<Boolean> isHttpsAttr = ctx.attr(AttributeKey.<Boolean>valueOf(HttpsAwareFiltersAdapter.IS_HTTPS_ATTRIBUTE_NAME));
        isHttpsAttr.set(true);
    }
}
 
Example 14
Source File: HttpsOriginalHostCaptureFilter.java    From CapturePacket with MIT License 5 votes vote down vote up
public HttpsOriginalHostCaptureFilter(HttpRequest originalRequest, ChannelHandlerContext ctx) {
    super(originalRequest, ctx);

    // if this is an HTTP CONNECT, set the isHttps attribute on the ChannelHandlerConect and capture the hostname from the original request.
    // capturing the original host (and the remapped/modified host in clientToProxyRequest() below) guarantees that we will
    // have the "true" host, rather than relying on the Host header in subsequent requests (which may be absent or spoofed by malicious clients).
    if (ProxyUtils.isCONNECT(originalRequest)) {
        Attribute<String> originalHostAttr = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.ORIGINAL_HOST_ATTRIBUTE_NAME));
        String hostAndPort = originalRequest.getUri();
        originalHostAttr.set(hostAndPort);

        Attribute<Boolean> isHttpsAttr = ctx.attr(AttributeKey.<Boolean>valueOf(HttpsAwareFiltersAdapter.IS_HTTPS_ATTRIBUTE_NAME));
        isHttpsAttr.set(true);
    }
}
 
Example 15
Source File: MessageMetricsChannelHandler.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
public static MessageMetrics getOrSetMetrics(Channel channel) {
    Attribute<MessageMetrics> attribute = channel.attr(ATTR_KEY_METRICS);
    MessageMetrics metrics = attribute.get();
    if(metrics == null) {
        metrics = new MessageMetrics();
        attribute.set(metrics);
    }
    return metrics;
}
 
Example 16
Source File: Session.java    From spring-boot-protocol with Apache License 2.0 4 votes vote down vote up
public void setBackendCapabilities(Set<CapabilityFlags> capabilities) {
	Attribute<EnumSet<CapabilityFlags>> attr = backendChannel.attr(CAPABILITIES_ATTR);
	attr.set(EnumSet.copyOf(capabilities));
}
 
Example 17
Source File: IrisNettyPlatformBusListener.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private String filter(Session session, PlatformMessage msg) {
   try {
      PlatformMessage filtered = authorizer.filter(session.getAuthorizationContext(), session.getActivePlace(), msg);
      if(filtered != null) {
         
         Address source = msg.getSource();
         if (source != null && MessageConstants.SERVICE.equals(source.getNamespace()) && VideoService.NAMESPACE.equals(source.getGroup())) {
            Channel ch = session.getChannel();
            Attribute<MessageBody> attr = (ch != null) ? ch.attr(CACHED_LIST_RECORDINGS_RESPONSE) : null;
            if (attr != null) {
               switch (filtered.getMessageType()) {
               case VideoService.ListRecordingsResponse.NAME:
                  attr.set(msg.getValue());
                  break;

               case VideoService.DeleteAllResponse.NAME:
               case Capability.EVENT_ADDED:
               case Capability.EVENT_DELETED:
               case Capability.EVENT_VALUE_CHANGE:
                  attr.remove();
                  break;

               default:
                  break;
               }
            }
         }

         return JSON.toJson(messageUtil.convertPlatformToClient(filtered));
      } else {
         logger.debug("Dropped message [{}]:  msg place {} != session place {}", msg, msg.getPlaceId(), session.getActivePlace());
      }
   }
   catch (UnknownSessionException use){
      logger.debug("Session expired by shiro:  [{}] and session [{}]", msg, session.getClientToken(), use);
      session.disconnect(Constants.SESSION_EXPIRED_STATUS);
      session.destroy();
   }  
   catch (IllegalStateException ise){
 	  if (session != null) {
 		  logger.debug("Attempted to send message to disconnected client: [{}] and session [{}]", msg, session.getClientToken(), ise);
 		  session.destroy();
 	  } else {
 		  logger.debug("Attempted to send message to disconnected client: [{}]", msg, ise);
 	  }
   }
   catch(Exception e) {
      logger.debug("Unable to dispatch message [{}] to session [{}]", msg, session.getClientToken(), e);
   }

   return null;
}
 
Example 18
Source File: HttpServerHandler.java    From ext-opensource-netty with Mozilla Public License 2.0 4 votes vote down vote up
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
	// Handle a bad request.
	if (!req.decoderResult().isSuccess()) {
		sendHttpResponse(ctx, req,
				new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
		return;
	}

	// Allow only GET methods.
	if (req.method() != HttpMethod.GET) {
		sendHttpResponse(ctx, req,
				new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
		return;
	}

	String uri = req.uri();
	int index = uri.indexOf("?");
	String paramterStr = "";
	String path = null;
	if (index == -1) {
		path = uri;
	} else {
		path = uri.substring(0, index);
		paramterStr = uri.substring(index+1);
	}

    if (websocketPath != null && websocketPath.trim().length() > 0 && websocketPath.equals(path)) {
		// Handshake
		WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
				WebSocketUtil.getWebSocketLocation(ctx.pipeline(), req, websocketPath), null, true, 5 * 1024 * 1024);
		handshaker = wsFactory.newHandshaker(req);
		if (handshaker == null) {
			WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
		} else {
			handshaker.handshake(ctx.channel(), req);
				
			if (!ctx.channel().hasAttr(WEBSOCKET_KEY)) {
				Attribute<String> attr = ctx.channel().attr(WEBSOCKET_KEY);
				attr.set("");
			}
			
			if (webSocketEvent != null) {
				Map<String, Object> paramter = MapUrlParamsUtil.getUrlParams(paramterStr);
				webSocketEvent.onOpenEvent(baseServer, new WebSocketSession(ctx.channel()), paramter);
			}
		}
	}  else {
		if (httpResource != null) {
			String resFileName = path;
			ByteBuf res = httpResource.buildWebSocketRes(req, resFileName);
			if (null == res) {
				sendHttpResponse(ctx, req,
						new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND));
				return;
			} else {
				sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
						res));
			}
		}
		return;
	}
}
 
Example 19
Source File: NettySession.java    From litchi with Apache License 2.0 4 votes vote down vote up
public void setUid(long uid) {
    Attribute<Long> attribute = channel().attr(UID);
    attribute.set(uid);
}
 
Example 20
Source File: NettySession.java    From litchi with Apache License 2.0 4 votes vote down vote up
public NettySession(Channel channel) {
    Attribute<Long> attrId = channel.attr(SESSION_ID);
    attrId.set(atomicId.incrementAndGet());
    this.channel = channel;
}