Java Code Examples for io.netty.handler.codec.http.FullHttpRequest#getUri()

The following examples show how to use io.netty.handler.codec.http.FullHttpRequest#getUri() . 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: TwilioBaseHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected boolean verifyRequest(FullHttpRequest request){
   
   if(!request.headers().contains(TwilioHelper.SIGNATURE_HEADER_KEY)){
      throw new IllegalArgumentException(String.format("%s header not found",TwilioHelper.SIGNATURE_HEADER_KEY));
   }
   
   String signature = request.headers().get(TwilioHelper.SIGNATURE_HEADER_KEY);
   String host = request.headers().get(TwilioHelper.HOST_HEADER_KEY);

   if(callbackHost != null){
      host=callbackHost;
   }
   
   String fullURL=callbackProtocol + "://" + host + request.getUri();
   
   boolean verified = verifySignature(twilioAccountAuth, fullURL, signature);
   
   if(!verified && twilioVerifyAuth){
      LOGGER.warn("Twilio Failed Signature Verfication: Signature: {} URL: {} ", signature, fullURL);
      FAILED_SIGNATURE_VERFICATIONS_COUNTER.inc();
      return false;
   }
   return true;
}
 
Example 2
Source File: MP4Handler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(@Nullable ChannelHandlerContext ctx, @Nullable FullHttpRequest request) throws Exception {
   if (ctx == null) {
      log.error("channel context should not be null");
      return;
   }

   if (request == null) {
      sendErrorResponse(ctx,HttpResponseStatus.INTERNAL_SERVER_ERROR);
      return;
   }

   try {
      QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
      UUID id = getRecordingId(decoder, UUID_START, UUID_END, ".mp4");
      if (id == null || !validateRequest(request, id, decoder)) {
         sendErrorResponse(ctx,HttpResponseStatus.BAD_REQUEST);
         return;
      }

      stream(id, ctx, request);
   } catch (Exception ex) {
      sendErrorResponse(ctx,HttpResponseStatus.BAD_REQUEST);
   }
}
 
Example 3
Source File: FunctionsChannelHandler.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
	if (!request.getDecoderResult().isSuccess()) {
		sendError(ctx, BAD_REQUEST);
		return;
	}
				
	String uri = request.getUri();
	QueryStringDecoder decoder = new QueryStringDecoder(uri);			
	SimpleHttpRequest req = new SimpleHttpRequest(decoder.path(), decoder.parameters());
				
	String cookieString = request.headers().get(HttpHeaders.Names.COOKIE);
	if (cookieString != null) {
		Set<Cookie> cookies = CookieDecoder.decode(cookieString);
		req.setCookies(cookies);
	} else {
		req.setCookies(Collections.emptySet());
	}
	req.setHeaders(request.headers());
	copyHttpBodyData(request, req);
	
	SimpleHttpResponse resp =  eventHandler.apply(req);
	ctx.write( HttpEventHandler.buildHttpResponse(resp.toString(), resp.getStatus(), resp.getContentType()) );
	ctx.flush().close();
	
}
 
Example 4
Source File: InboundWebsocketSourceHandler.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private String getWebSocketLocation(FullHttpRequest req) throws URISyntaxException {
    String location = req.headers().get(HOST) + req.getUri();
    subscriberPath = new URI(req.getUri());
    if (isSSLEnabled) {
        return "wss://" + location;
    } else {
        return "ws://" + location;
    }
}
 
Example 5
Source File: OAuthUtil.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static Map<String, String> extractQueryArgs(FullHttpRequest req) {
   QueryStringDecoder decoder = new QueryStringDecoder(req.getUri());
   return decoder.parameters()
         .entrySet()
         .stream()
         .collect(Collectors.toMap(Map.Entry::getKey, (v) -> { return v.getValue().get(0); }));
}
 
Example 6
Source File: HttpPageResource.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public FullHttpResponse respond(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   String uri = req.getUri();
   ByteBuf content = getContent(factory.get(ctx.channel()), uri);
   if(content != null) {
      FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
      res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
      setContentLength(res, content.readableBytes());
      return res;
   }
   else {
      throw new HttpException(HttpSender.STATUS_NOT_FOUND);
   }
}
 
Example 7
Source File: HttpRootController.java    From happor with MIT License 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
		throws Exception {
	// TODO Auto-generated method stub
	if (msg instanceof FullHttpRequest) {
		request = (FullHttpRequest) msg;
		response = new DefaultFullHttpResponse(
				request.getProtocolVersion(), HttpResponseStatus.OK);
		
		HapporContext happorContext = server.getContext(request);
		if (happorContext == null) {
			logger.error("cannot find path for URI: " + request.getUri());
			response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
			ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
			return;
		}
		
		HttpController lastController = null;
		
		Map<String, ControllerRegistry> controllers = happorContext.getControllers();
		for (Map.Entry<String, ControllerRegistry> entry : controllers.entrySet()) {
			ControllerRegistry registry = entry.getValue();
			String method = registry.getMethod();
			String uriPattern = registry.getUriPattern();
			UriParser uriParser = new UriParser(request.getUri());
			
			if (isMethodMatch(method) && isUriMatch(uriParser, uriPattern)) {
				HttpController controller = happorContext.getController(registry.getClazz());
				controller.setPrev(lastController);
				controller.setServer(server);
				controller.setUriParser(uriParser);
				boolean isEnd = controller.input(ctx, request, response);
				if (isEnd) {
					break;
				}
				lastController = controller;
			}
		}
	}
}
 
Example 8
Source File: HTTPHandler.java    From ThinkMap with Apache License 2.0 5 votes vote down vote up
public void httpRequest(ChannelHandlerContext context, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;
    }

    URI uri = new URI(request.getUri());
    uri = uri.normalize();
    if (uri.getPath().contains("..")) {
        sendHttpResponse(context, request, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
        return;
    }

    plugin.getWebHandler().getEndPointManager().handle(context, uri, request);
}
 
Example 9
Source File: HttpRequestHandler.java    From aesh-readline with Apache License 2.0 4 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (wsUri.equalsIgnoreCase(request.getUri())) {
        ctx.fireChannelRead(request.retain());
    } else {
        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);
        }

        HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.INTERNAL_SERVER_ERROR);

        String path = request.getUri();
        if ("/".equals(path)) {
            path = "/index.html";
        }
        URL res = HttpTtyConnection.class.getResource("/org/aesh/terminal/http" + path);
        try {
            if (res != null) {
                DefaultFullHttpResponse fullResp = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK);
                InputStream in = res.openStream();
                byte[] tmp = new byte[256];
                for (int l = 0; l != -1; l = in.read(tmp)) {
                    fullResp.content().writeBytes(tmp, 0, l);
                }
                int li = path.lastIndexOf('.');
                if (li != -1 && li != path.length() - 1) {
                    String ext = path.substring(li + 1, path.length());
                    String contentType;
                    switch (ext) {
                        case "html":
                            contentType = "text/html";
                            break;
                        case "js":
                            contentType = "application/javascript";
                            break;
                        default:
                            contentType = null;
                            break;
                    }
                    if (contentType != null) {
                        fullResp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
                    }
                }
                response = fullResp;
            } else {
                response.setStatus(HttpResponseStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ctx.write(response);
            ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}
 
Example 10
Source File: HttpClasspathServerHandler.java    From camunda-bpm-workbench with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);
        return;
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.getUri();
    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        // we use the start time of the JVM as last modified date
        long lastModifiedSeconds = ManagementFactory.getRuntimeMXBean().getStartTime();
        if (ifModifiedSinceDateSeconds == lastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    ClassLoader classLoader = HttpClasspathServerHandler.class.getClassLoader();
    InputStream stream = classLoader.getResourceAsStream(path);

    if(stream == null) {
      sendError(ctx, NOT_FOUND);
      return;
    }

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, stream.available());
    setContentTypeHeader(response, path);
    setDateAndCacheHeaders(response);
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.

    ChannelFuture sendFileFuture = ctx.write(new ChunkedStream(stream), ctx.newProgressivePromise());
        // Write the end marker.
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 11
Source File: HttpRequestHandler.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
  if (wsUri.equalsIgnoreCase(request.getUri())) {
    ctx.fireChannelRead(request.retain());
  } else {
    if (HttpHeaders.is100ContinueExpected(request)) {
      send100Continue(ctx);
    }

    HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.INTERNAL_SERVER_ERROR);

    String path = request.getUri();
    if ("/".equals(path)) {
      path = "/index.html";
    }
    URL res = HttpTtyConnection.class.getResource("/io/termd/core/http" + path);
    try {
      if (res != null) {
        DefaultFullHttpResponse fullResp = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK);
        InputStream in = res.openStream();
        byte[] tmp = new byte[256];
        for (int l = 0; l != -1; l = in.read(tmp)) {
          fullResp.content().writeBytes(tmp, 0, l);
        }
        int li = path.lastIndexOf('.');
        if (li != -1 && li != path.length() - 1) {
          String ext = path.substring(li + 1, path.length());
          String contentType;
          switch (ext) {
            case "html":
              contentType = "text/html";
              break;
            case "js":
              contentType = "application/javascript";
              break;
            default:
              contentType = null;
              break;
          }
          if (contentType != null) {
            fullResp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
          }
        }
        response = fullResp;
      } else {
        response.setStatus(HttpResponseStatus.NOT_FOUND);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      ctx.write(response);
      ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
      future.addListener(ChannelFutureListener.CLOSE);
    }
  }
}
 
Example 12
Source File: WebsocketInboundHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

    //check if the request is a handshake
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest req = (FullHttpRequest) msg;
        uri = req.getUri();
        URI uriTemp = new URI(uri);
        apiContextUri = new URI(uriTemp.getScheme(), uriTemp.getAuthority(), uriTemp.getPath(),
                 null, uriTemp.getFragment()).toString();

        if (req.getUri().contains("/t/")) {
            tenantDomain = MultitenantUtils.getTenantDomainFromUrl(req.getUri());
        } else {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }

        String useragent = req.headers().get(HttpHeaders.USER_AGENT);

        // '-' is used for empty values to avoid possible errors in DAS side.
        // Required headers are stored one by one as validateOAuthHeader()
        // removes some of the headers from the request
        useragent = useragent != null ? useragent : "-";
        headers.add(HttpHeaders.USER_AGENT, useragent);

        if (validateOAuthHeader(req)) {
            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                // carbon-mediation only support websocket invocation from super tenant APIs.
                // This is a workaround to mimic the the invocation came from super tenant.
                req.setUri(req.getUri().replaceFirst("/", "-"));
                String modifiedUri = uri.replaceFirst("/t/", "-t/");
                req.setUri(modifiedUri);
                msg = req;
            } else {
                req.setUri(uri); // Setting endpoint appended uri
            }

            if (StringUtils.isNotEmpty(token)) {
                ((FullHttpRequest) msg).headers().set(APIMgtGatewayConstants.WS_JWT_TOKEN_HEADER, token);
            }
            ctx.fireChannelRead(msg);

            // publish google analytics data
            GoogleAnalyticsData.DataBuilder gaData = new GoogleAnalyticsData.DataBuilder(null, null, null, null)
                    .setDocumentPath(uri)
                    .setDocumentHostName(DataPublisherUtil.getHostAddress())
                    .setSessionControl("end")
                    .setCacheBuster(APIMgtGoogleAnalyticsUtils.getCacheBusterId())
                    .setIPOverride(ctx.channel().remoteAddress().toString());
            APIMgtGoogleAnalyticsUtils gaUtils = new APIMgtGoogleAnalyticsUtils();
            gaUtils.init(tenantDomain);
            gaUtils.publishGATrackingData(gaData, req.headers().get(HttpHeaders.USER_AGENT),
                    headers.get(HttpHeaders.AUTHORIZATION));
        } else {
            ctx.writeAndFlush(new TextWebSocketFrame(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE));
            if (log.isDebugEnabled()) {
                log.debug("Authentication Failure for the websocket context: " + apiContextUri);
            }
            throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS,
                    APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
        }
    } else if ((msg instanceof CloseWebSocketFrame) || (msg instanceof PingWebSocketFrame)) {
        //if the inbound frame is a closed frame, throttling, analytics will not be published.
        ctx.fireChannelRead(msg);
    } else if (msg instanceof WebSocketFrame) {

        boolean isAllowed = doThrottle(ctx, (WebSocketFrame) msg);

        if (isAllowed) {
            ctx.fireChannelRead(msg);
            String clientIp = getRemoteIP(ctx);
            // publish analytics events if analytics is enabled
            if (APIUtil.isAnalyticsEnabled()) {
                publishRequestEvent(clientIp, true);
            }
        } else {
            ctx.writeAndFlush(new TextWebSocketFrame("Websocket frame throttled out"));
            if (log.isDebugEnabled()) {
                log.debug("Inbound Websocket frame is throttled. " + ctx.channel().toString());
            }
        }
    }
}
 
Example 13
Source File: RouteMatcher.java    From blueflood with Apache License 2.0 4 votes vote down vote up
public void route(ChannelHandlerContext context, FullHttpRequest request) {
    final String method = request.getMethod().name();
    final String URI = request.getUri();

    // Method not implemented for any resource. So return 501.
    if (method == null || !implementedVerbs.contains(method)) {
        route(context, request, unsupportedVerbsHandler);
        return;
    }

    final Pattern pattern = getMatchingPatternForURL(URI);

    // No methods registered for this pattern i.e. URL isn't registered. Return 404.
    if (pattern == null) {
        route(context, request, noRouteHandler);
        return;
    }

    final Set<String> supportedMethods = getSupportedMethods(pattern);
    if (supportedMethods == null) {
        log.warn("No supported methods registered for a known pattern " + pattern);
        route(context, request, noRouteHandler);
        return;
    }

    // The method requested is not available for the resource. Return 405.
    if (!supportedMethods.contains(method)) {
        route(context, request, unsupportedMethodHandler);
        return;
    }
    PatternRouteBinding binding = null;
    if (method.equals(HttpMethod.GET.name())) {
        binding = getBindings.get(pattern);
    } else if (method.equals(HttpMethod.PUT.name())) {
        binding = putBindings.get(pattern);
    } else if (method.equals(HttpMethod.POST.name())) {
        binding = postBindings.get(pattern);
    } else if (method.equals(HttpMethod.DELETE.name())) {
        binding = deleteBindings.get(pattern);
    } else if (method.equals(HttpMethod.PATCH.name())) {
        binding = deleteBindings.get(pattern);
    } else if (method.equals(HttpMethod.OPTIONS.name())) {
        binding = optionsBindings.get(pattern);
     } else if (method.equals(HttpMethod.HEAD.name())) {
        binding = headBindings.get(pattern);
    } else if (method.equals(HttpMethod.TRACE.name())) {
        binding = traceBindings.get(pattern);
    } else if (method.equals(HttpMethod.CONNECT.name())) {
        binding = connectBindings.get(pattern);
    }

    if (binding != null) {
        request = updateRequestHeaders(request, binding);
        route(context, request, binding.handler);
    } else {
        throw new RuntimeException("Cannot find a valid binding for URL " + URI);
    }
}
 
Example 14
Source File: ProcessDefintionAwareHandler.java    From camunda-bpm-workbench with GNU Affero General Public License v3.0 3 votes vote down vote up
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {

    String uri = msg.getUri();

    Matcher matcher = processDefinitionIdPattern.matcher(uri);

    if(matcher.matches()) {
      String processDefinitionId = matcher.group(1);
      ChannelAttributes.setProcessDefinitionId(ctx.channel(), processDefinitionId);
    }

  }