List of usage examples for io.netty.handler.codec.http HttpRequest getUri
@Deprecated String getUri();
From source file:org.robotbrains.support.web.server.netty.NettyWebServerHandler.java
License:Apache License
/** * Is the HTTP request requesting a Web Socket protocol upgrade? * * @param context//w w w . j a v a 2 s .c o m * the request context * @param request * the HTTP request * @param user * the user making the request * * @return {@code true} if a Web Socket protocol upgrade */ private boolean tryWebSocketUpgradeRequest(ChannelHandlerContext context, HttpRequest request, final String user) { if (!request.getUri().startsWith(fullWebSocketUriPrefix)) { return false; } if (accessManager != null) { if (!accessManager.userHasAccess(user, request.getUri())) { return false; } } // Handshake WebSocketServerHandshakerFactory wsFactory = getWebSocketHandshakerFactory(request); final ChannelWithId channel = (ChannelWithId) context.channel(); final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(request); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channel); } else { ChannelFuture handshake = handshaker.handshake(channel, request); handshake.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { completeWebSocketHandshake(user, channel, handshaker); } }); } // Handled request. return true; }
From source file:org.wingsource.wingweb.http.cxf.jaxrs.NettyHttpServletHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { HttpRequest request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { ctx.write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); }/* w w w . j av a 2s. c o m*/ // find the nettyHttpContextHandler by lookup the request url NettyHttpContextHandler nettyHttpContextHandler = pipelineFactory.getNettyHttpHandler(request.uri()); if (request.uri().equals("/snoop")) { new HttpSnoopServerHandler().channelRead(ctx, msg); } else if (nettyHttpContextHandler != null) { handleHttpServletRequest(ctx, request, nettyHttpContextHandler); } else { throw new RuntimeException( new Fault(new Message("NO_NETTY_SERVLET_HANDLER_FOUND", LOG, request.getUri()))); } }
From source file:org.wisdom.engine.server.WisdomHandler.java
License:Apache License
private static String getWebSocketLocation(HttpRequest req) { //TODO Support wss return "ws://" + req.headers().get(HOST) + req.getUri(); }
From source file:org.wisdom.engine.server.WisdomHandler.java
License:Apache License
private boolean writeResponse(final ChannelHandlerContext ctx, final HttpRequest request, Context context, Result result, boolean handleFlashAndSessionCookie, boolean fromAsync) { //TODO Refactor this method. // Render the result. InputStream stream;/* ww w .j a v a2 s.com*/ boolean success = true; Renderable<?> renderable = result.getRenderable(); if (renderable == null) { renderable = NoHttpBody.INSTANCE; } try { stream = processResult(context, result); } catch (Exception e) { LOGGER.error("Cannot render the response to " + request.getUri(), e); stream = new ByteArrayInputStream(NoHttpBody.EMPTY); success = false; } if (accessor.getContentEngines().getContentEncodingHelper().shouldEncode(context, result, renderable)) { ContentCodec codec = null; for (String encoding : accessor.getContentEngines().getContentEncodingHelper() .parseAcceptEncodingHeader(context.request().getHeader(HeaderNames.ACCEPT_ENCODING))) { codec = accessor.getContentEngines().getContentCodecForEncodingType(encoding); if (codec != null) { break; } } if (codec != null) { // Encode Async result.with(CONTENT_ENCODING, codec.getEncodingType()); proceedAsyncEncoding(context, codec, stream, ctx, result, success, handleFlashAndSessionCookie, fromAsync); return true; } //No encoding possible, do the finalize } return finalizeWriteReponse(context, ctx, result, stream, success, handleFlashAndSessionCookie, fromAsync); }
From source file:org.wisdom.engine.wrapper.ContextFromNetty.java
License:Apache License
/** * Creates a new context.//from w ww . java 2s. c o m * * @param accessor a structure containing the used services. * @param ctxt the channel handler context. * @param req the incoming HTTP Request. */ public ContextFromNetty(ServiceAccessor accessor, ChannelHandlerContext ctxt, HttpRequest req) { id = ids.getAndIncrement(); services = accessor; queryStringDecoder = new QueryStringDecoder(req.getUri()); request = new RequestFromNetty(this, ctxt, req); flashCookie = new FlashCookieImpl(accessor.getConfiguration()); sessionCookie = new SessionCookieImpl(accessor.getCrypto(), accessor.getConfiguration()); sessionCookie.init(this); flashCookie.init(this); }
From source file:org.wso2.carbon.gateway.internal.transport.listener.SourceHandler.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*from ww w.j av a 2 s . c o m*/ public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { cMsg = new CarbonMessage(Constants.PROTOCOL_NAME); cMsg.setPort(((InetSocketAddress) ctx.channel().remoteAddress()).getPort()); cMsg.setHost(((InetSocketAddress) ctx.channel().remoteAddress()).getHostName()); ResponseCallback responseCallback = new ResponseCallback(this.ctx); cMsg.setCarbonCallback(responseCallback); HttpRequest httpRequest = (HttpRequest) msg; cMsg.setURI(httpRequest.getUri()); Pipe pipe = new PipeImpl(queueSize); cMsg.setPipe(pipe); cMsg.setProperty(Constants.CHNL_HNDLR_CTX, this.ctx); cMsg.setProperty(Constants.SRC_HNDLR, this); cMsg.setProperty(Constants.HTTP_VERSION, httpRequest.getProtocolVersion().text()); cMsg.setProperty(Constants.HTTP_METHOD, httpRequest.getMethod().name()); cMsg.setProperty(Constants.TRANSPORT_HEADERS, Util.getHeaders(httpRequest)); if (disruptorConfig.isShared()) { cMsg.setProperty(Constants.DISRUPTOR, disruptor); } disruptor.publishEvent(new CarbonEventPublisher(cMsg)); } else { HTTPContentChunk chunk; if (cMsg != null) { if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; chunk = new HTTPContentChunk(httpContent); cMsg.getPipe().addContentChunk(chunk); } } } }
From source file:org.wso2.carbon.mss.internal.router.HttpResourceHandler.java
License:Open Source License
/** * Call the appropriate handler for handling the httprequest. 404 if path is not found. 405 if path is found but * httpMethod does not match what's configured. * * @param request instance of {@code HttpRequest} * @param responder instance of {@code HttpResponder} to handle the request. * @return HttpMethodInfo object, null if urlRewriter rewrite returns false, also when method cannot be invoked. * @throws HandlerException If URL rewriting fails *//*from w w w . java 2s . co m*/ public HttpMethodInfoBuilder getDestinationMethod(HttpRequest request, HttpResponder responder) throws HandlerException { if (urlRewriter != null) { try { request.setUri(URI.create(request.getUri()).normalize().toString()); if (!urlRewriter.rewrite(request, responder)) { return null; } } catch (Throwable t) { log.error("Exception thrown during rewriting of uri {}", request.getUri(), t); throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR, String.format("Caught exception processing request. Reason: %s", t.getMessage())); } } String acceptHeaderStr = request.headers().get(HttpHeaders.Names.ACCEPT); List<String> acceptHeader = (acceptHeaderStr != null) ? Arrays.asList(acceptHeaderStr.split("\\s*,\\s*")).stream() .map(mediaType -> mediaType.split("\\s*;\\s*")[0]).collect(Collectors.toList()) : null; String contentTypeHeaderStr = request.headers().get(HttpHeaders.Names.CONTENT_TYPE); //Trim specified charset since UTF-8 is assumed String contentTypeHeader = (contentTypeHeaderStr != null) ? contentTypeHeaderStr.split("\\s*;\\s*")[0] : null; try { String path = URI.create(request.getUri()).normalize().getPath(); List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations = patternRouter .getDestinations(path); List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations = getMatchedDestination( routableDestinations, request.getMethod(), path); if (!matchedDestinations.isEmpty()) { PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination = matchedDestinations .stream().filter(matchedDestination1 -> { return matchedDestination1.getDestination().matchConsumeMediaType(contentTypeHeader) && matchedDestination1.getDestination().matchProduceMediaType(acceptHeader); }).findFirst().get(); HttpResourceModel httpResourceModel = matchedDestination.getDestination(); // Call preCall method of handler interceptors. boolean terminated = false; HandlerInfo handlerInfo = new HandlerInfo( httpResourceModel.getMethod().getDeclaringClass().getName(), httpResourceModel.getMethod()); for (Interceptor interceptor : interceptors) { if (!interceptor.preCall(request, responder, handlerInfo)) { // Terminate further request processing if preCall returns false. terminated = true; break; } } // Call httpresource handle method, return the HttpMethodInfo Object. if (!terminated) { // Wrap responder to make post hook calls. responder = new WrappedHttpResponder(responder, interceptors, request, handlerInfo); return HttpMethodInfoBuilder.getInstance().httpResourceModel(httpResourceModel) .httpRequest(request).httpResponder(responder) .requestInfo(matchedDestination.getGroupNameValues(), contentTypeHeader, acceptHeader); } } else if (!routableDestinations.isEmpty()) { //Found a matching resource but could not find the right HttpMethod so return 405 throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, request.getUri()); } else { throw new HandlerException(HttpResponseStatus.NOT_FOUND, String.format("Problem accessing: %s. Reason: Not Found", request.getUri())); } } catch (NoSuchElementException ex) { throw new HandlerException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE, String.format("Problem accessing: %s. Reason: Unsupported Media Type", request.getUri()), ex); } return null; }
From source file:org.wso2.carbon.mss.internal.router.HttpResourceModelProcessor.java
License:Open Source License
/** * Handle http Request./* w ww . j av a 2 s.c o m*/ * * @param request HttpRequest to be handled. * @param responder HttpResponder to write the response. * @param groupValues Values needed for the invocation. * @param contentType Content types * @param acceptTypes Accept types * @return HttpMethodInfo * @throws HandlerException If an error occurs */ @SuppressWarnings("unchecked") public HttpMethodInfo buildHttpMethodInfo(HttpRequest request, HttpResponder responder, Map<String, String> groupValues, String contentType, List<String> acceptTypes) throws HandlerException { //TODO: Refactor group values. try { if (httpResourceModel.getHttpMethod().contains(request.getMethod())) { //Setup args for reflection call List<HttpResourceModel.ParameterInfo<?>> paramInfoList = httpResourceModel.getParamInfoList(); List<String> producesMediaTypes = httpResourceModel.getProducesMediaTypes(); Object[] args = new Object[paramInfoList.size()]; String acceptType = "*/*"; if (!producesMediaTypes.contains("*/*") && acceptTypes != null) { acceptType = (acceptTypes.contains("*/*")) ? producesMediaTypes.get(0) : producesMediaTypes.stream().filter(acceptTypes::contains).findFirst().get(); } int idx = 0; for (HttpResourceModel.ParameterInfo<?> paramInfo : paramInfoList) { if (paramInfo.getAnnotation() != null) { Class<? extends Annotation> annotationType = paramInfo.getAnnotation().annotationType(); if (PathParam.class.isAssignableFrom(annotationType)) { args[idx] = getPathParamValue((HttpResourceModel.ParameterInfo<String>) paramInfo, groupValues); } else if (QueryParam.class.isAssignableFrom(annotationType)) { args[idx] = getQueryParamValue( (HttpResourceModel.ParameterInfo<List<String>>) paramInfo, request.getUri()); } else if (HeaderParam.class.isAssignableFrom(annotationType)) { args[idx] = getHeaderParamValue( (HttpResourceModel.ParameterInfo<List<String>>) paramInfo, request); } else if (Context.class.isAssignableFrom(annotationType)) { args[idx] = getContextParamValue((HttpResourceModel.ParameterInfo<Object>) paramInfo, request, responder); } } else if (request instanceof FullHttpRequest) { // If an annotation is not present the parameter is considered a // request body data parameter String content = ((FullHttpRequest) request).content().toString(Charsets.UTF_8); Type paramType = paramInfo.getParameterType(); args[idx] = BeanConverter.instance((contentType != null) ? contentType : "*/*") .toObject(content, paramType); } idx++; } if (httpStreamer == null) { return new HttpMethodInfo(httpResourceModel.getMethod(), httpResourceModel.getHttpHandler(), request, responder, args, httpResourceModel.getExceptionHandler(), acceptType); } else { return new HttpMethodInfo(httpResourceModel.getMethod(), httpResourceModel.getHttpHandler(), request, responder, args, httpResourceModel.getExceptionHandler(), acceptType, httpStreamer); } } else { //Found a matching resource but could not find the right HttpMethod so return 405 throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, String.format("Problem accessing: %s. Reason: Method Not Allowed", request.getUri())); } } catch (Throwable e) { throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR, String.format("Error in executing request: %s %s", request.getMethod(), request.getUri()), e); } }
From source file:org.wso2.carbon.mss.internal.router.MicroserviceMetadata.java
License:Open Source License
/** * Call the appropriate handler for handling the httprequest. 404 if path is not found. 405 if path is found but * httpMethod does not match what's configured. * * @param request instance of {@code HttpRequest} * @param responder instance of {@code HttpResponder} to handle the request. * @return HttpMethodInfo object, null if urlRewriter rewrite returns false, also when method cannot be invoked. * @throws HandlerException If URL rewriting fails *//* ww w . jav a 2 s. c o m*/ public HttpMethodInfoBuilder getDestinationMethod(HttpRequest request, HttpResponder responder) throws HandlerException { if (urlRewriter != null) { try { request.setUri(URI.create(request.getUri()).normalize().toString()); if (!urlRewriter.rewrite(request, responder)) { return null; } } catch (Throwable t) { log.error("Exception thrown during rewriting of uri {}", request.getUri(), t); throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR, String.format("Caught exception processing request. Reason: %s", t.getMessage())); } } String acceptHeaderStr = request.headers().get(HttpHeaders.Names.ACCEPT); List<String> acceptHeader = (acceptHeaderStr != null) ? Arrays.asList(acceptHeaderStr.split("\\s*,\\s*")).stream() .map(mediaType -> mediaType.split("\\s*;\\s*")[0]).collect(Collectors.toList()) : null; String contentTypeHeaderStr = request.headers().get(HttpHeaders.Names.CONTENT_TYPE); //Trim specified charset since UTF-8 is assumed String contentTypeHeader = (contentTypeHeaderStr != null) ? contentTypeHeaderStr.split("\\s*;\\s*")[0] : null; try { String path = URI.create(request.getUri()).normalize().getPath(); List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations = patternRouter .getDestinations(path); List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations = getMatchedDestination( routableDestinations, request.getMethod(), path); if (!matchedDestinations.isEmpty()) { PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination = matchedDestinations .stream().filter(matchedDestination1 -> { return matchedDestination1.getDestination().matchConsumeMediaType(contentTypeHeader) && matchedDestination1.getDestination().matchProduceMediaType(acceptHeader); }).findFirst().get(); HttpResourceModel httpResourceModel = matchedDestination.getDestination(); // Call preCall method of handler interceptors. boolean terminated = false; ServiceMethodInfo serviceMethodInfo = new ServiceMethodInfo( httpResourceModel.getMethod().getDeclaringClass().getName(), httpResourceModel.getMethod()); for (Interceptor interceptor : interceptors) { if (!interceptor.preCall(request, responder, serviceMethodInfo)) { // Terminate further request processing if preCall returns false. terminated = true; break; } } // Call httpresource handle method, return the HttpMethodInfo Object. if (!terminated) { // Wrap responder to make post hook calls. responder = new WrappedHttpResponder(responder, interceptors, request, serviceMethodInfo); return HttpMethodInfoBuilder.getInstance().httpResourceModel(httpResourceModel) .httpRequest(request).httpResponder(responder) .requestInfo(matchedDestination.getGroupNameValues(), contentTypeHeader, acceptHeader); } } else if (!routableDestinations.isEmpty()) { //Found a matching resource but could not find the right HttpMethod so return 405 throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, request.getUri()); } else { throw new HandlerException(HttpResponseStatus.NOT_FOUND, String.format("Problem accessing: %s. Reason: Not Found", request.getUri())); } } catch (NoSuchElementException ex) { throw new HandlerException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE, String.format("Problem accessing: %s. Reason: Unsupported Media Type", request.getUri()), ex); } return null; }
From source file:org.wso2.carbon.mss.security.oauth2.OAuth2SecurityInterceptor.java
License:Open Source License
@Override public boolean preCall(HttpRequest request, HttpResponder responder, ServiceMethodInfo serviceMethodInfo) { SecurityErrorCode errorCode;//from w w w .j av a2 s .co m try { HttpHeaders headers = request.headers(); if (headers != null && headers.contains(AUTHORIZATION_HTTP_HEADER)) { String authHeader = headers.get(AUTHORIZATION_HTTP_HEADER); return validateToken(authHeader); } else { throw new MSSSecurityException(SecurityErrorCode.AUTHENTICATION_FAILURE, "Missing Authorization header is the request.`"); } } catch (MSSSecurityException e) { errorCode = e.getErrorCode(); log.error(e.getMessage() + " Requested Path: " + request.getUri()); } handleSecurityError(errorCode, responder); return false; }