类javax.ws.rs.container.ContainerRequestContext源码实例Demo

下面列出了怎么用javax.ws.rs.container.ContainerRequestContext的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
public void filter(ContainerRequestContext requestContext)
    throws IOException {

    Class<?> matchedResource = (Class<?>)requestContext.
        getUriInfo().
        getMatchedResources().
        get(0);

    Object resource = _resourceContext.getResource(matchedResource);

    if (resource instanceof PerRequestTestResource) {
        PerRequestTestResource perRequestTestResource =
            (PerRequestTestResource) resource;

        perRequestTestResource.setState(perRequestTestResource.getState() + "-changed");
    }
}
 
源代码2 项目: mobi   文件: OntologyRest.java
/**
 * Returns an array of the imports closure in the requested format from the ontology
 * with the requested ID.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param rdfFormat   the desired RDF return format. NOTE: Optional param - defaults to "jsonld".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return array of imported ontologies from the ontology with the requested ID in the requested format
 */
@GET
@Path("{recordId}/imported-ontologies")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Retrieves the JSON-LD of all imported ontologies.")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getImportsClosure(@Context ContainerRequestContext context,
                                  @PathParam("recordId") String recordIdStr,
                                  @DefaultValue("jsonld") @QueryParam("rdfFormat") String rdfFormat,
                                  @QueryParam("branchId") String branchIdStr,
                                  @QueryParam("commitId") String commitIdStr) {
    try {
        Set<Ontology> importedOntologies = getImportedOntologies(context, recordIdStr, branchIdStr, commitIdStr);
        ArrayNode arrayNode = mapper.createArrayNode();
        importedOntologies.stream()
                .map(ontology -> getOntologyAsJsonObject(ontology, rdfFormat))
                .forEach(arrayNode::add);
        return arrayNode.size() == 0 ? Response.noContent().build() : Response.ok(arrayNode.toString()).build();
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
源代码3 项目: jeesuite-libs   文件: ResponseWrapperHandler.java
@Override
public void processResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext,
		ResourceInfo resourceInfo) {
	MediaType mediaType = responseContext.getMediaType();
	if (mediaType != null && MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
		Object responseData = responseContext.getEntity();
		WrapperResponseEntity jsonResponse;

		if (responseData instanceof WrapperResponseEntity) {
			jsonResponse = (WrapperResponseEntity) responseData;
		} else {
			jsonResponse = new WrapperResponseEntity(ResponseCode.OK);
			jsonResponse.setData(responseData);
		}
		responseContext.setStatus(ResponseCode.OK.getCode());

		responseContext.setEntity(jsonResponse);

	}
}
 
@Override
public void filter( ContainerRequestContext request ) {
    if (logger.isTraceEnabled()) {
        logger.trace("Filtering: {}", request.getUriInfo().getBaseUri());
    }

    if( bypassSecurityCheck(request) ){
        return;
    }

    String clientId = httpServletRequest.getParameter( "client_id" );
    String clientSecret = httpServletRequest.getParameter( "client_secret" );

    if ( isNotBlank( clientId ) && isNotBlank( clientSecret ) ) {
        try {
            PrincipalCredentialsToken token =
                    management.getPrincipalCredentialsTokenForClientCredentials( clientId, clientSecret );
            Subject subject = SubjectUtils.getSubject();
            subject.login( token );
        }
        catch ( Exception e ) {
            throw mappableSecurityException( OAUTH2_INVALID_CLIENT );
        }
    }
}
 
源代码5 项目: trellis   文件: JwtAuthFilterTest.java
@Test
void testJwtAuthFilter() {
    final ContainerRequestContext mockContext = mock(ContainerRequestContext.class);
    assertNotNull(filter);
    assertNotNull(producer);

    final String iss = "https://example.com/idp/";
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);

    producer.setJsonWebToken(new DefaultJWTCallerPrincipal(claims));
    assertDoesNotThrow(() -> filter.filter(mockContext));
    verify(mockContext).setSecurityContext(securityArgument.capture());
    assertEquals(iss + sub, securityArgument.getValue().getUserPrincipal().getName());
}
 
源代码6 项目: katharsis-framework   文件: CookieParamProvider.java
@Override
public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) {
    Object returnValue;
    String cookieName = parameter.getAnnotation(CookieParam.class).value();
    Cookie cookie = requestContext.getCookies().get(cookieName);
    if (cookie == null) {
        return null;
    } else {
        if (Cookie.class.isAssignableFrom(parameter.getType())) {
            returnValue = cookie;
        } else if (String.class.isAssignableFrom(parameter.getType())) {
            returnValue = cookie.getValue();
        } else {
            try {
                returnValue = objectMapper.readValue(cookie.getValue(), parameter.getType());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    return returnValue;
}
 
@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    requestContext.setSecurityContext(new SecurityContext() {
        @Override
        public Principal getUserPrincipal() {
            return null;
        }
        @Override
        public boolean isUserInRole(String string) {
            return false;
        }
        @Override
        public boolean isSecure() { return false; }
        
        @Override
        public String getAuthenticationScheme() { return "BASIC"; }
    });
}
 
源代码8 项目: cloudbreak   文件: StructuredEventFilter.java
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
    if (BooleanUtils.isTrue((Boolean) requestContext.getProperty(LOGGING_ENABLED_PROPERTY))) {
        RestResponseDetails restResponse = createResponseDetails(responseContext);
        if (responseContext.hasEntity()) {
            OutputStream stream = new LoggingStream(responseContext.getEntityStream());
            responseContext.setEntityStream(stream);
            requestContext.setProperty(LOGGINGSTREAM_PROPERTY, stream);
            requestContext.setProperty(RESPONSE_DETAILS, restResponse);
        } else {
            Long requestTime = (Long) requestContext.getProperty(REQUEST_TIME);
            RestRequestDetails restRequest = (RestRequestDetails) requestContext.getProperty(REQUEST_DETAILS);
            Map<String, String> restParams = (Map<String, String>) requestContext.getProperty(REST_PARAMS);
            sendStructuredEvent(restRequest, restResponse, restParams, requestTime, "");
        }
    }
}
 
源代码9 项目: dubbox   文件: RpcContextFilter.java
public void filter(ContainerRequestContext requestContext) throws IOException {
    HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class);
    RpcContext.getContext().setRequest(request);

    // this only works for servlet containers
    if (request != null && RpcContext.getContext().getRemoteAddress() == null) {
        RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort());
    }

    RpcContext.getContext().setResponse(ResteasyProviderFactory.getContextData(HttpServletResponse.class));

    String headers = requestContext.getHeaderString(DUBBO_ATTACHMENT_HEADER);
    if (headers != null) {
        for (String header : headers.split(",")) {
            int index = header.indexOf("=");
            if (index > 0) {
                String key = header.substring(0, index);
                String value = header.substring(index + 1);
                if (!StringUtils.isEmpty(key)) {
                    RpcContext.getContext().setAttachment(key.trim(), value.trim());
                }
            }
        }
    }
}
 
源代码10 项目: cxf   文件: ClientCodeRequestFilter.java
private Response createCodeResponse(ContainerRequestContext rc, UriInfo ui) {
    MultivaluedMap<String, String> codeRequestState = toCodeRequestState(rc, ui);
    MultivaluedMap<String, String> redirectState = createRedirectState(rc, ui, codeRequestState);
    String theState = redirectState != null ? redirectState.getFirst(OAuthConstants.STATE) : null;
    String redirectScope = redirectState != null ? redirectState.getFirst(OAuthConstants.SCOPE) : null;
    String theScope = redirectScope != null ? redirectScope : scopes;
    UriBuilder ub = OAuthClientUtils.getAuthorizationURIBuilder(authorizationServiceUri,
                                         consumer.getClientId(),
                                         getAbsoluteRedirectUri(ui).toString(),
                                         theState,
                                         theScope);
    setFormPostResponseMode(ub, redirectState);
    setCodeVerifier(ub, redirectState);
    setAdditionalCodeRequestParams(ub, redirectState, codeRequestState);
    URI uri = ub.build();
    return Response.seeOther(uri).build();
}
 
源代码11 项目: aerogear-unifiedpush-server   文件: CORSFilter.java
@Override
public void filter(ContainerRequestContext requestContext,
                   ContainerResponseContext responseContext) throws IOException {
    responseContext.getHeaders().add(
            "Access-Control-Allow-Origin", "*");
    responseContext.getHeaders().add(
            "Access-Control-Allow-Credentials", "true");
    responseContext.getHeaders().add(
            "Access-Control-Allow-Headers",
            "origin, content-type, accept, authorization");
    responseContext.getHeaders().add(
            "Access-Control-Allow-Methods",
            "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    responseContext.getHeaders().add(
            "Access-Control-Expose-Headers", "*");
}
 
源代码12 项目: mobi   文件: OntologyRest.java
/**
 * Returns annotation property IRIs in the imports closure for the ontology identified by the provided IDs.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return annotation properties in the ontology identified by the provided IDs.
 */
@GET
@Path("{recordId}/imported-annotations")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Gets the annotations from the imported ontologies of the identified ontology.")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getAnnotationsInImportedOntologies(@Context ContainerRequestContext context,
                                                   @PathParam("recordId") String recordIdStr,
                                                   @QueryParam("branchId") String branchIdStr,
                                                   @QueryParam("commitId") String commitIdStr) {
    try {
        return doWithImportedOntologies(context, recordIdStr, branchIdStr, commitIdStr,
                this::getAnnotationIRIObject);
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
源代码13 项目: cxf   文件: CrossOriginResourceSharingFilter.java
@Override
public void filter(ContainerRequestContext context) {
    Message m = JAXRSUtils.getCurrentMessage();

    String httpMethod = (String)m.get(Message.HTTP_REQUEST_METHOD);
    if (HttpMethod.OPTIONS.equals(httpMethod)) {
        Response r = preflightRequest(m);
        if (r != null) {
            context.abortWith(r);
        }
    } else if (findResourceMethod) {
        Method method = getResourceMethod(m, httpMethod);
        simpleRequest(m, method);
    } else {
        m.getInterceptorChain().add(new CorsInInterceptor());
    }

}
 
源代码14 项目: keycloak-metrics-spi   文件: MetricsFilter.java
@Override
public void filter(ContainerRequestContext req, ContainerResponseContext res) {
    int status = res.getStatus();

    // We are only interested in recording the response status if it was an error
    // (either a 4xx or 5xx). No point in counting  the successful responses
    if (status >= 400) {
        PrometheusExporter.instance().recordResponseError(status, req.getMethod());
    }

    // Record request duration if timestamp property is present
    // and only if it is relevant (skip pictures)
    if (req.getProperty(METRICS_REQUEST_TIMESTAMP) != null &&
        contentTypeIsRelevant(res)) {
        long time = (long) req.getProperty(METRICS_REQUEST_TIMESTAMP);
        long dur = System.currentTimeMillis() - time;
        LOG.trace("Duration is calculated as " + dur + " ms.");
        PrometheusExporter.instance().recordRequestDuration(dur, req.getMethod());
    }
}
 
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    OidcSecurityContext secCtx = (OidcSecurityContext) requestContext.getSecurityContext();
    OidcClientTokenContext tokenCtx = secCtx.getOidcContext();
    IdToken idToken = tokenCtx.getIdToken();
    String email = idToken.getEmail();
    boolean configured = false;
    try {
        configured = googleConfig.getServiceAccountEmail() != null && googleConfig.readServiceAccountKey() != null;
    } catch (NoPrivateKeyException e) {
    }
    if (configured) {
        log.error("Unauthorized access from {}. Application is already configured!", email);
        ServerError err = new ServerError("E002", "Unauthorized access to Configuration API");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(err).type(MediaType.APPLICATION_JSON).build());
    }
}
 
源代码16 项目: trellis   文件: TestAuthenticationFilter.java
@Override
public void filter(final ContainerRequestContext requestContext) {
    requestContext.setSecurityContext(new SecurityContext() {
        @Override
        public Principal getUserPrincipal() {
            return () -> principal;
        }

        @Override
        public boolean isSecure() {
            return false;
        }

        @Override
        public boolean isUserInRole(final String role) {
            return userRole.equals(role);
        }

        @Override
        public String getAuthenticationScheme() {
            return "BASIC";
        }
    });
}
 
源代码17 项目: mobi   文件: OntologyRest.java
/**
 * Delete class with requested class ID from ontology identified by the provided IDs from the server.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param classIdStr  the String representing the class Resource id. NOTE: Assumes id represents
 *                    an IRI unless String begins with "_:".
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return a Response indicating whether it was successfully deleted.
 */
@DELETE
@Path("{recordId}/classes/{classId}")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Deletes the identified class from the identified ontology.")
@ActionId(Modify.TYPE)
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response deleteClassFromOntology(@Context ContainerRequestContext context,
                                        @PathParam("recordId") String recordIdStr,
                                        @PathParam("classId") String classIdStr,
                                        @QueryParam("branchId") String branchIdStr,
                                        @QueryParam("commitId") String commitIdStr) {
    try {
        Ontology ontology = getOntology(context, recordIdStr, branchIdStr, commitIdStr, true).orElseThrow(() ->
                ErrorUtils.sendError("The ontology could not be found.", Response.Status.BAD_REQUEST));
        return deletionsToInProgressCommit(context, ontology, classIdStr, recordIdStr);
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
源代码18 项目: helix   文件: CORSFilter.java
@Override
public void filter(ContainerRequestContext request) throws IOException {
  // handle preflight
  if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
    Response.ResponseBuilder builder = Response.ok();

    String requestMethods = request.getHeaderString("Access-Control-Request-Method");
    if (requestMethods != null) {
      builder.header("Access-Control-Allow-Methods", requestMethods);
    }

    String allowHeaders = request.getHeaderString("Access-Control-Request-Headers");
    if (allowHeaders != null) {
      builder.header("Access-Control-Allow-Headers", allowHeaders);
    }

    request.abortWith(builder.build());
  }
}
 
源代码19 项目: hawkular-metrics   文件: TenantFilter.java
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    UriInfo uriInfo = requestContext.getUriInfo();
    String path = uriInfo.getPath();

    if (path.startsWith("/tenants") || path.startsWith(StatusHandler.PATH) || path.equals(BaseHandler.PATH)) {
        // Some handlers do not check the tenant header
        return;
    }

    String tenant = requestContext.getHeaders().getFirst(TENANT_HEADER_NAME);
    if (tenant != null && !tenant.trim().isEmpty()) {
        // We're good already
        return;
    }
    // Fail on missing tenant info
    Response response = Response.status(Status.BAD_REQUEST)
                                .type(APPLICATION_JSON_TYPE)
                                .entity(new ApiError(MISSING_TENANT_MSG))
                                .build();
    requestContext.abortWith(response);
}
 
源代码20 项目: syndesis   文件: EndpointMetricsFilter.java
/**
 * Called after the resource method.
 */
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
    Sample sample = (Sample) requestContext.getProperty(TIMING_SAMPLE);
    if (sample != null) {
        Timer timer = Timer
            .builder("http.server.requests")
            // no way to access the exception
            .tag("exception", "")
            .tag("outcome", computeOutcome(responseContext))
            .tag("method", getMethod(requestContext))
            .tag("status", getStatus(responseContext))
            .tag("uri", getUri())
            .publishPercentileHistogram()
            .maximumExpectedValue(Duration.ofSeconds(10))
            .register(registry);
        sample.stop(timer);
    }
}
 
源代码21 项目: docker-java   文件: LoggingFilter.java
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext)
        throws IOException {
    final long id = aid.incrementAndGet();
    final StringBuilder b = new StringBuilder();

    printResponseLine(b, "Server responded with a response", id, responseContext.getStatus());
    printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getStringHeaders());

    if (printEntity && responseContext.hasEntity()) {
        final OutputStream stream = new LoggingStream(b, responseContext.getEntityStream());
        responseContext.setEntityStream(stream);
        requestContext.setProperty(ENTITY_LOGGER_PROPERTY, stream);
        // not calling log(b) here - it will be called by the interceptor
    } else {
        log(b);
    }
}
 
源代码22 项目: crnk-framework   文件: CrnkFilterTest.java
@Test
public void checkWebPathPrefixNullFilter() throws IOException {
	CrnkFeature feature = Mockito.mock(CrnkFeature.class);
	Mockito.when(feature.getWebPathPrefix()).thenReturn(null);
	Mockito.when(feature.getBoot()).thenThrow(new WebApplicationException("test"));

	CrnkFilter filter = new CrnkFilter(feature);
	UriInfo uriInfo = Mockito.mock(UriInfo.class);
	Mockito.when(uriInfo.getPath()).thenReturn("/tasks");
	Mockito.when(uriInfo.getQueryParameters()).thenReturn(Mockito.mock(MultivaluedMap.class));

	ContainerRequestContext requestContext = Mockito.mock(ContainerRequestContext.class);
	Mockito.when(requestContext.getUriInfo()).thenReturn(uriInfo);
	try {
		filter.filter(requestContext);
		Assert.fail();
	} catch (WebApplicationException e) {
		Assert.assertEquals("test", e.getMessage());
	}
}
 
源代码23 项目: jrestless   文件: CorsFilterTest.java
@Test
public void preflightRequestFilter_BlankMethodGiven_CorsFails() throws IOException {
	CorsFilter filter = new CorsFilter.Builder()
			.allowMethod(HttpMethod.GET)
			.build();
	ContainerRequestContext request = createPreflightRequestMock(DEFAULT_HOST, DEFAULT_ORIGIN, " ");
	assertThrows(ForbiddenException.class, () -> filter.filter(request));
}
 
源代码24 项目: tessera   文件: IPWhitelistFilterTest.java
@Before
public void init() throws URISyntaxException {

    when(configService.getPeers()).thenReturn(singletonList(URI.create("http://whitelistedHost:8080")));
    when(configService.isUseWhiteList()).thenReturn(true);

    this.ctx = mock(ContainerRequestContext.class);
    final UriInfo uriInfo = mock(UriInfo.class);
    when(uriInfo.getBaseUri()).thenReturn(new URI("otherhost"));
    when(ctx.getUriInfo()).thenReturn(uriInfo);

    this.filter = new IPWhitelistFilter();
}
 
源代码25 项目: divide   文件: AuthenticationEndpoint.java
@GET
@Path("/recover/{token}")
@Produces(MediaType.APPLICATION_JSON)
public Response recoverFromOneTimeToken(@Context ContainerRequestContext context, @PathParam("token") String token) {
    try{
        Credentials user = authServerLogic.getUserFromRecoveryToken(token);
        context.setSecurityContext(new UserContext(context.getUriInfo(),user));
        return Response.ok(user).build();
    }catch (ServerDAO.DAOException e) {
        e.printStackTrace();
        logger.severe(ExceptionUtils.getStackTrace(e));
        return fromDAOExpection(e);
    }
}
 
@Test
public void shouldClearPrincipal_onFilter() throws Exception {
    // Given
    mockStatic(FeaturesContextHolder.class);
    final ContainerRequestContext mockContainerRequestContext = mock(ContainerRequestContext.class);
    final ContainerResponseContext mockContainerResponseContext = mock(ContainerResponseContext.class);
    final ContainerFeatureSetResponseFilter containerFeatureSetResponseFilter = new ContainerFeatureSetResponseFilter();

    // When
    containerFeatureSetResponseFilter.filter(mockContainerRequestContext, mockContainerResponseContext);

    // Then
    verifyStatic(FeaturesContextHolder.class);
    FeaturesContextHolder.clear();
}
 
源代码27 项目: mobi   文件: OntologyRest.java
/**
 * Returns the JSON String of the resulting entities sorted by type from the ontology with the requested record ID
 * that have statements which contain the requested searchText in a Literal Value.
 *
 * @param context     the context of the request.
 * @param recordIdStr the String representing the record Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:".
 * @param searchText  the String for the text that is searched for in all of the Literals within the ontology with
 *                    the requested record ID.
 * @param branchIdStr the String representing the Branch Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the
 *                    master Branch.
 * @param commitIdStr the String representing the Commit Resource id. NOTE: Assumes id represents an IRI unless
 *                    String begins with "_:". NOTE: Optional param - if nothing is specified, it will get the head
 *                    Commit. The provided commitId must be on the Branch identified by the provided branchId;
 *                    otherwise, nothing will be returned.
 * @return JSON String providing the sorted list of results from the search.
 */
@GET
@Path("{recordId}/search-results")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed("user")
@ApiOperation("Gets the search results from the identified ontology using the provided searchText.")
@ResourceId(type = ValueType.PATH, value = "recordId")
public Response getSearchResults(@Context ContainerRequestContext context,
                                 @PathParam("recordId") String recordIdStr,
                                 @QueryParam("searchText") String searchText,
                                 @QueryParam("branchId") String branchIdStr,
                                 @QueryParam("commitId") String commitIdStr) {
    try {
        Ontology ontology = getOntology(context, recordIdStr, branchIdStr, commitIdStr, true).orElseThrow(() ->
                ErrorUtils.sendError("The ontology could not be found.", Response.Status.BAD_REQUEST));
        checkStringParam(searchText, "The searchText is missing.");
        TupleQueryResult results = ontology.getSearchResults(searchText, valueFactory);
        Map<String, Set<String>> response = new HashMap<>();
        results.forEach(queryResult -> {
            Value entity = Bindings.requiredResource(queryResult, "entity");
            Value filter = Bindings.requiredResource(queryResult, "type");
            if (!(entity instanceof BNode) && !(filter instanceof BNode)) {
                String entityString = entity.stringValue();
                String filterString = filter.stringValue();
                if (response.containsKey(filterString)) {
                    response.get(filterString).add(entityString);
                } else {
                    Set<String> newSet = new HashSet<>();
                    newSet.add(entityString);
                    response.put(filterString, newSet);
                }
            }
        });
        return response.size() == 0 ? Response.noContent().build() :
                Response.ok(mapper.valueToTree(response).toString())
                .build();
    } catch (MobiException e) {
        throw ErrorUtils.sendError(e, e.getMessage(), Response.Status.INTERNAL_SERVER_ERROR);
    }
}
 
源代码28 项目: hawkular-metrics   文件: CacheControlFilter.java
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {

    if (cacheControl != null) {
        MultivaluedMap<String, Object> responseHeaders = responseContext.getHeaders();
        responseHeaders.add("Cache-Control", cacheControl);
        responseHeaders.add("Vary", "Origin,Accept-Encoding");
    }
}
 
源代码29 项目: jrestless   文件: ApplicationPathFilter.java
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	String applicationPath = getApplicationPath();
	if (applicationPath != null) {
		UriInfo requestUriInfo = requestContext.getUriInfo();
		UriBuilder baseUriBuilder = requestUriInfo.getBaseUriBuilder();
		baseUriBuilder.path(applicationPath);
		// the base URI must end with a trailing slash
		baseUriBuilder.path("/");
		URI updatedBaseUri = baseUriBuilder.build();
		URI requestUri = requestUriInfo.getRequestUri();
		requestContext.setRequestUri(updatedBaseUri, requestUri);
	}
}
 
源代码30 项目: blog-tutorials   文件: CorsFilter.java
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
		throws IOException {
	responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
	responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
	responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
	responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
 
 类所在包
 同包方法