Java Code Examples for javax.ws.rs.container.ContainerRequestContext#getMethod()

The following examples show how to use javax.ws.rs.container.ContainerRequestContext#getMethod() . 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: AuthorizationRequestFilter.java    From gazpachoquest with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    String method = requestContext.getMethod();
    String requestUrl = requestContext.getUriInfo().getPath();

    // We do allow wadl to be retrieve
    if (method.equals("GET")
            && (requestUrl.indexOf("application.wadl") > -1 || requestUrl.indexOf("api-docs") > -1)) {
        return;
    }

    // Get the authentification passed in HTTP headers parameters
    String authToken = requestContext.getHeaderString("authorization");
    SecurityContext context = null;
    if (StringUtils.isNotBlank(authToken)) {
        AuthorizationRequestContext authRequestContext = AuthorizationRequestContext.with().httpMethod(method)
                .requestUrl(requestUrl).authorizationToken(authToken).build();

        context = authorizationService.authorize(authRequestContext);
    } else {
        context = new SecurityContextImpl();
    }
    requestContext.setSecurityContext(context);
}
 
Example 2
Source File: ResponseLoggingFilter.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext
        containerResponseContext) throws IOException {
    Class<?> resourceClass = resourceInfo.getResourceClass();

    if (log.isInfoEnabled() && containerRequestContext != null && containerResponseContext != null
            && resourceClass != null) {
        Logger resourceLog = LoggerFactory.getLogger(resourceClass);

        Object startTimeValue = containerRequestContext.getProperty(Filters.REQ_START_TIME);
        if (resourceLog.isInfoEnabled() && startTimeValue != null) {
            long start = (long) startTimeValue;
            long responseTime = System.currentTimeMillis() - start;

            String path = containerRequestContext.getUriInfo().getPath();
            String method = containerRequestContext.getMethod();
            int statusCode = containerResponseContext.getStatusInfo().getStatusCode();
            String statusMsg = containerResponseContext.getStatusInfo().getReasonPhrase();

            resourceLog.info(
                    String.format("%s: %s -> %d: %s (%dms)", method, path, statusCode, statusMsg, responseTime));
        }
    }
}
 
Example 3
Source File: RequestLoggingFilter.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
    Class<?> resourceClass = resourceInfo.getResourceClass();

    if (log.isInfoEnabled() && containerRequestContext != null && resourceClass != null) {
        Logger resourceLog = LoggerFactory.getLogger(resourceClass);

        if (resourceLog.isInfoEnabled()) {
            containerRequestContext.setProperty(Filters.REQ_START_TIME, System.currentTimeMillis());

            String path = containerRequestContext.getUriInfo().getPath();
            String method = containerRequestContext.getMethod();
            resourceLog.debug(String.format("%s: %s", method, path));
        }
    }
}
 
Example 4
Source File: LoggingResourceFilter.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
    Long requestTime = requestTimestamps.remove(servletRequest);
    Duration requestDuration = null;
    if (requestTime != null) {
        long responseTime = System.nanoTime();
        requestDuration = Duration.nanos(responseTime - requestTime);
    }
    
    String method = requestContext.getMethod();
    boolean isInteresting = !UNINTERESTING_METHODS.contains(method.toUpperCase())
            || (requestDuration != null && requestDuration.isLongerThan(REQUEST_DURATION_LOG_POINT));
    LogLevel logLevel = isInteresting ? LogLevel.DEBUG : LogLevel.TRACE;

    logResponse(requestContext, responseContext, requestDuration, logLevel);
}
 
Example 5
Source File: LoggingResponseFilter.java    From demo-restWS-spring-jersey-tomcat-mybatis with MIT License 5 votes vote down vote up
public void filter(ContainerRequestContext requestContext,
		ContainerResponseContext responseContext) throws IOException {
	String method = requestContext.getMethod();

	logger.debug("Requesting " + method + " for path " + requestContext.getUriInfo().getPath());
	Object entity = responseContext.getEntity();
	if (entity != null) {
		logger.debug("Response " + new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(entity));
	}

}
 
Example 6
Source File: ControllerResponseFilter.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
    throws IOException {
  final String method = requestContext.getMethod();
  final String uri = requestContext.getUriInfo().getRequestUri().toString();
  final int respStatus = responseContext.getStatus();
  final String reasonPhrase = responseContext.getStatusInfo().getReasonPhrase();
  final String srcIpAddr = request.get().getRemoteAddr();
  final String contentType = requestContext.getHeaderString(HttpHeaders.CONTENT_TYPE);
  LOGGER.info("Handled request from {} {} {}, content-type {} status code {} {}", srcIpAddr, method, uri, contentType,
      respStatus, reasonPhrase);
}
 
Example 7
Source File: OpenTracingProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    final TraceScopeHolder<TraceScope> holder = super.startTraceSpan(requestContext.getHeaders(),
        requestContext.getUriInfo().getRequestUri(), requestContext.getMethod());

    if (holder != null) {
        requestContext.setProperty(TRACE_SPAN, holder);
    }
}
 
Example 8
Source File: RequestLoggingFilter.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
private void logRequest(Logger.Level level, ContainerRequestContext requestContext) {
    String request =
            "\n" +
            "REST API request:\n" +
            "--------------------------------------\n" +
            "path: " + requestContext.getUriInfo().getPath() + "\n" +
            "segments: " + requestContext.getUriInfo().getPathSegments() + "\n" +
            "method: " + requestContext.getMethod() + "\n" +
            "query parameters: " + requestContext.getUriInfo().getQueryParameters() + "\n" +
            // Only log the tenant header to avoid logging any security sensitive information
            "Tenant: " + requestContext.getHeaders().get(TENANT_HEADER_NAME) + "\n" +
            "--------------------------------------\n";
    logger.log(level, request);
}
 
Example 9
Source File: LoggingResponseFilter.java    From demo-rest-jersey-spring with MIT License 5 votes vote down vote up
public void filter(ContainerRequestContext requestContext,
		ContainerResponseContext responseContext) throws IOException {
	String method = requestContext.getMethod();

	logger.debug("Requesting " + method + " for path " + requestContext.getUriInfo().getPath());
	Object entity = responseContext.getEntity();
	if (entity != null) {
		logger.debug("Response " + new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(entity));
	}
	
}
 
Example 10
Source File: FedizRedirectBindingFilter.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public void filter(ContainerRequestContext context) {
    Message m = JAXRSUtils.getCurrentMessage();
    FedizContext fedConfig = getFedizContext(m);

    // See if it is a Metadata request
    if (isMetadataRequest(context, fedConfig)) {
        return;
    }

    String httpMethod = context.getMethod();
    MultivaluedMap<String, String> params = null;

    try {
        if (HttpMethod.GET.equals(httpMethod)) {
            params = context.getUriInfo().getQueryParameters();
        } else if (HttpMethod.POST.equals(httpMethod)) {
            String strForm = IOUtils.toString(context.getEntityStream(), "UTF-8");
            params = JAXRSUtils.getStructuredParams(strForm, "&", true, false);
        }
    } catch (Exception ex) {
        LOG.debug(ex.getMessage(), ex);
        throw ExceptionUtils.toInternalServerErrorException(ex, null);
    }

    // See if it is a Logout request first
    if (isLogoutRequest(context, fedConfig, m, params) || isSignoutCleanupRequest(fedConfig, m, params)) {
        return;
    } else if (checkSecurityContext(fedConfig, m, params)) {
        return;
    } else if (isSignInRequired(fedConfig, params)) {
        processSignInRequired(context, fedConfig);
    } else if (isSignInRequest(fedConfig, params)) {
        processSignInRequest(context, fedConfig, m, params);
    } else {
        LOG.error("SignIn parameter is incorrect or not supported");
        throw ExceptionUtils.toBadRequestException(null, null);
    }
}
 
Example 11
Source File: LoggingResourceFilter.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    requestTimestamps.put(servletRequest, System.nanoTime());
    
    String method = requestContext.getMethod();
    boolean isInteresting = !UNINTERESTING_METHODS.contains(method.toUpperCase());
    LogLevel logLevel = isInteresting ? LogLevel.DEBUG : LogLevel.TRACE;
    
    logRequest(requestContext, logLevel);
}
 
Example 12
Source File: RateLimiterKey.java    From pay-publicapi with MIT License 5 votes vote down vote up
public static RateLimiterKey from(ContainerRequestContext requestContext, String accountId) {
    final String method = requestContext.getMethod();

    StringBuilder builder = new StringBuilder(method);

    final String pathType = PathHelper.getPathType(requestContext.getUriInfo().getPath(), method);
    if (!pathType.isBlank()) {
        builder.append("-").append(pathType);
    }

    final String keyType = builder.toString();
    builder.append("-").append(accountId);

    return new RateLimiterKey(builder.toString(), keyType, method);
}
 
Example 13
Source File: CorsFilter.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
		throws IOException {
	String origin = requestContext.getHeaderString(ORIGIN);
	Object originFailureProperty = requestContext.getProperty(CORS_FAILURE_PROPERTY_NAME);
	String accessControlRequestMethod = requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_METHOD);
	String requestMethod = requestContext.getMethod();
	if (origin == null
			|| originFailureProperty != null
			|| isPreflightRequest(requestMethod, accessControlRequestMethod)
			|| sameOriginPolicy.isSameOrigin(requestContext, origin)) {
		return; // not CORS or a CORS failure => do not add any CORS headers
	}
	addCorsResponseHeaders(responseContext.getHeaders(), origin);
}
 
Example 14
Source File: MCRRestAuthorizationFilter.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) {
    MCRRestAPIACLPermission permission;
    switch (requestContext.getMethod()) {
        case HttpMethod.OPTIONS:
            return;
        case HttpMethod.GET:
        case HttpMethod.HEAD:
            permission = MCRRestAPIACLPermission.READ;
            break;
        case HttpMethod.DELETE:
            permission = MCRRestAPIACLPermission.DELETE;
            break;
        default:
            permission = MCRRestAPIACLPermission.WRITE;
    }
    Optional.ofNullable(resourceInfo.getResourceClass().getAnnotation(Path.class))
        .map(Path::value)
        .ifPresent(path -> {
            checkRestAPIAccess(requestContext, permission, path);
            MultivaluedMap<String, String> pathParameters = requestContext.getUriInfo().getPathParameters();
            checkBaseAccess(requestContext, permission, pathParameters.getFirst(PARAM_MCRID),
                pathParameters.getFirst(PARAM_DERID), pathParameters.getFirst(PARAM_DER_PATH));
        });
    checkDetailLevel(requestContext,
        requestContext.getAcceptableMediaTypes()
            .stream()
            .map(m -> m.getParameters().get(MCRDetailLevel.MEDIA_TYPE_PARAMETER))
            .toArray(String[]::new));
}
 
Example 15
Source File: LoggingFilter.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) {

    final String method = context.getMethod();
    final String path = info.getPath();
    final String address = request.remoteAddress().toString();

    LOG.infof("Request %s %s from IP %s", method, path, address);
}
 
Example 16
Source File: RestUrlParser.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private String getMethod(ContainerRequestContext requestContext) {
    return requestContext.getMethod();
}
 
Example 17
Source File: OperationNameProvider.java    From java-jaxrs with Apache License 2.0 4 votes vote down vote up
@Override
public String operationName(ContainerRequestContext requestContext) {
  return requestContext.getMethod() + ":" + path;
}
 
Example 18
Source File: LoggingResourceFilter.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private void logResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext, Duration requestDuration, LogLevel level) {
    if (!isLogEnabled(LOG, level)) return;
    
    int status = responseContext.getStatus();
    String method = requestContext.getMethod();
    String path = requestContext.getUriInfo().getPath();
    requestContext.getSecurityContext();
    MultivaluedMap<String, String> queryParams = requestContext.getUriInfo().getQueryParameters();
    
    SecurityContext securityContext = requestContext.getSecurityContext();
    Principal userPrincipal = (securityContext != null) ? requestContext.getSecurityContext().getUserPrincipal() : null;
    String userName = (userPrincipal != null) ? userPrincipal.getName() : "<no-user>";
    String remoteAddr = servletRequest.getRemoteAddr();
    
    boolean includeHeaders = (responseContext.getStatus() / 100 == 5) || LOG.isTraceEnabled();

    StringBuilder message = new StringBuilder("Request completed: ")
            .append("status ")
            .append(status)
            .append(" in ")
            .append(requestDuration)
            .append(", ")
            .append(method)
            .append(" ")
            .append(path)
            .append(" from ")
            .append(userName)
            .append(" @ ")
            .append(remoteAddr);

    if (!queryParams.isEmpty()) {
        message.append(", queryParams: {");
        message.append(Joiner.on(", ").withKeyValueSeparator("=").join(queryParams));
        message.append("}");
    }
    if (requestContext.getLength() > 0) {
        // TODO `getLength` is based on the presence of `Content-Length` header, rather than the measured length.
        int len = requestContext.getLength();
        message.append(", mediaType=").append(requestContext.getMediaType())
                .append(" (length=").append(len).append(")");
    }
    if (includeHeaders) {
        MultivaluedMap<String, String> headers = requestContext.getHeaders();
        message.append(", headers={");
        if (!headers.isEmpty()) {
            boolean first = true;
            for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
                if (first) {
                    first = false;
                } else {
                    message.append(", ");
                }
                String headerName = entry.getKey();
                message.append(headerName).append(": ");
                if (CENSORED_HEADERS.contains(headerName)) {
                    message.append("******");
                } else {
                    message.append(entry.getValue());
                }
            }
        }
        message.append("}");
    }

    log(LOG, level, message.toString());
}
 
Example 19
Source File: OperationNameProvider.java    From java-jaxrs with Apache License 2.0 4 votes vote down vote up
@Override
public String operationName(ContainerRequestContext requestContext) {
  return requestContext.getMethod();
}
 
Example 20
Source File: LoginShiroFilter.java    From gazpachoquest with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    
    String method = requestContext.getMethod();
    String path = uriInfo.getPath();
    String query = uriInfo.getRequestUri().getQuery();
    logger.debug("New access to resource {}", path);
    if (path.startsWith("auth") || path.contains("api-docs")) {
        // Ignore the AuthenticationResource
        return;
    }

    Subject subject = SecurityUtils.getSubject();
   
    String dateUTC = requestContext.getHeaderString(HttpHeaders.DATE);
    String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

    if (authorizationHeader == null) {
        throw new AccountException("Hmac-SHA1 Authorization token is required");
    }
    String[] values = authorizationHeader.split(" ");
    String apiKeyAndSignature[] = StringUtils.split(values[1], ":");

    StringBuilder signedContent = new StringBuilder().append(method).append(" /").append(path);
    if (query != null) {
        signedContent.append("?").append(query);
    }

    if (dateUTC != null) {
        signedContent.append("\n").append(dateUTC);
    }
    /*-
    if ("POST".equals(method)) {
        DelegatingInputStream input = message.getContent(DelegatingInputStream.class);
        if (input != null) {
            input.cacheInput();
            try {
                signedContent.append("\n").append(IOUtils.toString(input));
            } catch (IOException e) {
                throw new IllegalStateException("Errors when reading POST content", e);
            }
        }
    }*/
    String apiKey = apiKeyAndSignature[0];
    String signature = apiKeyAndSignature[1];
    AuthenticationToken token = new HmacAuthToken.Builder().apiKey(apiKey).message(signedContent.toString())
            .signature(signature).dateUTC(dateUTC).build();
    subject.login(token); //
}