@Override public void onEvent(RequestEvent event) { switch (event.getType()) { case RESOURCE_METHOD_START: ExtendedUriInfo uriInfo = event.getUriInfo(); ResourceMethod method = uriInfo.getMatchedResourceMethod(); ContainerRequest containerRequest = event.getContainerRequest(); LOG.info(requestNumber+" Resource method " + method.getHttpMethod() + " started for request " + requestNumber); LOG.info(requestNumber+" Headers: "+ render(containerRequest.getHeaders())); LOG.info(requestNumber+" Path: "+uriInfo.getPath()); LOG.info(requestNumber+" PathParameters: "+ render(uriInfo.getPathParameters())); LOG.info(requestNumber+" QueryParameters: "+ render(uriInfo.getQueryParameters())); LOG.info(requestNumber+" Body: "+getBody(containerRequest)); break; case FINISHED: LOG.info("Request " + requestNumber + " finished. Processing time " + (System.currentTimeMillis() - startTime) + " ms."); break; default: break; } }
@Test public final void verifyProvideRequiresApiKey() { // given final ExtendedUriInfo uriInfo = mock(ExtendedUriInfo.class); final MultivaluedMap<String, String> parameterMap = ImmutableMultivaluedMap.empty(); given(uriInfo.getQueryParameters()).willReturn(parameterMap); given(request.getUriInfo()).willReturn(uriInfo); // when try { factory.provide(); // then fail("Expected 400 status code"); } catch (final BadRequestException bre) { } }
@Test public final void verifyProvideGrantsAccess() throws URISyntaxException { // given final MultivaluedMap<String, String> parameterMap = new MultivaluedHashMap<String, String>(); parameterMap.putSingle("apiKey", "validApiKey"); final URI uri = new URI("https://api.example.com/path/to/resource?apiKey=validApiKey"); final ExtendedUriInfo uriInfo = mock(ExtendedUriInfo.class); given(uriInfo.getQueryParameters()).willReturn(parameterMap); given(uriInfo.getRequestUri()).willReturn(uri); given(request.getUriInfo()).willReturn(uriInfo); given(request.getHeaderString("X-Auth-Version")).willReturn("1"); given(request.getHeaderString("X-Auth-Signature")).willReturn("validSignature"); given(request.getHeaderString("X-Auth-Timestamp")).willReturn("two seconds ago"); given(request.getMethod()).willReturn("GET"); given(authenticator.authenticate(any(Credentials.class))).willReturn("principal"); // when final String result = factory.provide(); // then assertEquals("principal", result); }
private String getTemplatePath(ExtendedUriInfo uriInfo) { StringBuilder builder = new StringBuilder(); for (UriTemplate template : uriInfo.getMatchedTemplates()) { List<String> variables = template.getTemplateVariables(); String[] args = new String[variables.size()]; for (int i = 0; i < args.length; i++) { args[i] = "{" + variables.get(i) + "}"; } String uri = template.createURI(args); if (!uri.equals("/") && !uri.equals("")) builder.insert(0, uri); } return builder.toString(); }
private static String templatedUri(RequestEvent event) { final ExtendedUriInfo uriInfo = event.getUriInfo(); final List<UriTemplate> matchedTemplates = new ArrayList<>(uriInfo.getMatchedTemplates()); if (matchedTemplates.size() > 1) { Collections.reverse(matchedTemplates); } final StringBuilder sb = new StringBuilder(); sb.append(uriInfo.getBaseUri().getPath()); for (UriTemplate uriTemplate : matchedTemplates) { sb.append(uriTemplate.getTemplate()); } return sb.toString().replaceAll("//+", "/"); }
private static RequestEvent event(String method, Integer status, Exception exception, String baseUri, String... uriTemplateStrings) { Builder builder = new RequestEventImpl.Builder(); ContainerRequest containerRequest = mock(ContainerRequest.class); when(containerRequest.getMethod()).thenReturn(method); builder.setContainerRequest(containerRequest); ContainerResponse containerResponse = mock(ContainerResponse.class); when(containerResponse.getStatus()).thenReturn(status); builder.setContainerResponse(containerResponse); builder.setException(exception, null); ExtendedUriInfo extendedUriInfo = mock(ExtendedUriInfo.class); when(extendedUriInfo.getBaseUri()).thenReturn( URI.create("http://localhost:8080" + (baseUri == null ? "/" : baseUri))); List<UriTemplate> uriTemplates = uriTemplateStrings == null ? Collections.emptyList() : Arrays.stream(uriTemplateStrings).map(uri -> new UriTemplate(uri)) .collect(Collectors.toList()); // UriTemplate are returned in reverse order Collections.reverse(uriTemplates); when(extendedUriInfo.getMatchedTemplates()).thenReturn(uriTemplates); builder.setExtendedUriInfo(extendedUriInfo); return builder.build(Type.FINISHED); }
@Test public final void verifyProvideDeniesAccess() throws URISyntaxException { // given final MultivaluedMap<String, String> parameterMap = new MultivaluedHashMap<String, String>(); parameterMap.putSingle("apiKey", "invalidApiKey"); final URI uri = new URI("https://api.example.com/path/to/resource?apiKey=invalidApiKey"); final ExtendedUriInfo uriInfo = mock(ExtendedUriInfo.class); given(uriInfo.getQueryParameters()).willReturn(parameterMap); given(uriInfo.getRequestUri()).willReturn(uri); given(request.getUriInfo()).willReturn(uriInfo); given(request.getHeaderString("X-Auth-Version")).willReturn("1"); given(request.getHeaderString("X-Auth-Signature")).willReturn("invalidSignature"); given(request.getHeaderString("X-Auth-Timestamp")).willReturn("two days ago"); given(request.getMethod()).willReturn("POST"); given(authenticator.authenticate(any(Credentials.class))).willReturn(null); // when try { factory.provide(); // then fail("Expected 401 status code"); } catch (final NotAuthorizedException nae) { } }
/** * Get media types for which the {@link org.glassfish.jersey.server.mvc.spi.ResolvedViewable resolved viewable} could be * produced. * * @param containerRequest request to obtain acceptable media types. * @param extendedUriInfo uri info to obtain resource method from and its producible media types. * @param varyHeaderValue Vary header reference. * @return list of producible media types. */ public static List<MediaType> getProducibleMediaTypes(final ContainerRequest containerRequest, final ExtendedUriInfo extendedUriInfo, final Ref<String> varyHeaderValue) { final List<MediaType> producedTypes = getResourceMethodProducibleTypes(extendedUriInfo); final MediaType[] mediaTypes = producedTypes.toArray(new MediaType[producedTypes.size()]); final List<Variant> variants = VariantSelector.selectVariants(containerRequest, Variant.mediaTypes(mediaTypes) .build(), varyHeaderValue == null ? Refs.emptyRef() : varyHeaderValue); return Lists.transform(variants, variant -> MediaTypes.stripQualityParams(variant.getMediaType())); }
/** * Return a list of producible media types of the last matched resource method. * * @param extendedUriInfo uri info to obtain resource method from. * @return list of producible media types of the last matched resource method. */ private static List<MediaType> getResourceMethodProducibleTypes(final ExtendedUriInfo extendedUriInfo) { if (extendedUriInfo.getMatchedResourceMethod() != null && !extendedUriInfo.getMatchedResourceMethod().getProducedTypes().isEmpty()) { return extendedUriInfo.getMatchedResourceMethod().getProducedTypes(); } return Collections.singletonList(MediaType.WILDCARD_TYPE); }
/** * Create a {@code TemplateModelProcessor} instance. * * @param resourceContext (injected) resource context. * @param extendedUriInfoProvider (injected) extended uri info provider. */ @Inject TemplateModelProcessor(final ResourceContext resourceContext, final Provider<ConfiguredValidator> validatorProvider, final Provider<ExtendedUriInfo> extendedUriInfoProvider) { this.resourceContext = resourceContext; this.validatorProvider = validatorProvider; this.extendedUriInfoProvider = extendedUriInfoProvider; }
/** * Obtains a model object for a viewable. * * @param extendedUriInfo uri info to obtain last matched resource from. * @return a model object. */ private Object getModel(final ExtendedUriInfo extendedUriInfo) { final List<Object> matchedResources = extendedUriInfo.getMatchedResources(); if (resourceInstance != null) { return setModelClass(resourceInstance); } else if (matchedResources.size() > 1) { return setModelClass(matchedResources.get(1)); } else { return setModelClass(resourceContext.getResource(resourceClass)); } }
@GET @Path("{file:.*}") public Response getResource(@PathParam("file") String fileName, @Context ContainerRequest request, @Context ExtendedUriInfo uriInfo) throws URISyntaxException, IOException { if (!fileName.startsWith("/")) { fileName = "/" + fileName; } URI rawUri = ((Request) request).getRawReqeustUri(); String reqPath = rawUri.getPath(); int pathFileIndex = reqPath.lastIndexOf("/"); String reqFileName = reqPath; if (pathFileIndex != -1) { reqFileName = reqPath.substring(pathFileIndex); } if (!fileName.endsWith(reqFileName)) { if (pathFileIndex != -1) { fileName = fileName.substring(0, fileName.lastIndexOf("/")) + reqFileName; } else { fileName = reqFileName; } } List<String> uris = uriInfo.getMatchedURIs(true); String mapName = uris.get(uris.size() - 1); URL url = AssetsFeature.lookupAsset(mapName, fileName); return assets(url, request); }
/** * <p>generateRespBuilder.</p> * * @param containerRequestContext a {@link javax.ws.rs.container.ContainerRequestContext} object. * @param extendedUriInfo a {@link org.glassfish.jersey.server.ExtendedUriInfo} object. * @param mediaType a {@link javax.ws.rs.core.MediaType} object. * @param respEntityGenerators a {@link java.lang.Iterable} object. * @return a {@link javax.ws.rs.core.Response.ResponseBuilder} object. */ protected static Response.ResponseBuilder generateRespBuilder( ContainerRequestContext containerRequestContext, ExtendedUriInfo extendedUriInfo, MediaType mediaType, Iterable<OptionsResponseGenerator> respEntityGenerators) { final Set<String> allowedMethods = ModelProcessorUtil.getAllowedMethods( (extendedUriInfo.getMatchedRuntimeResources().get(0))); Response.ResponseBuilder builder = Response.ok().allow(allowedMethods); if (allowedMethods.contains(HttpPatchProperties.METHOD_NAME)) { builder.header(HttpPatchProperties.ACCEPT_PATCH_HEADER, getSupportPatchMediaTypes()); } if (mediaType != null) { builder.type(mediaType); } if (respEntityGenerators != null) { Response response = builder.build(); for (OptionsResponseGenerator generator : respEntityGenerators) { response = generator.generate(allowedMethods, mediaType, extendedUriInfo, containerRequestContext, response); } builder = Response.fromResponse(response); } return builder; }
@Override public Response generate(Set<String> allowedMethods, MediaType mediaType, ExtendedUriInfo extendedUriInfo, ContainerRequestContext containerRequestContext, Response response) { Response.ResponseBuilder builder = Response.fromResponse(response); if (mediaType.isCompatible(TEXT_PLAIN_TYPE)) { return builder.entity(StringUtils.join(allowedMethods, ",")).build(); } String uri = extendedUriInfo.getMatchedModelResource().getPathPattern().getTemplate().getTemplate(); return builder.entity(new AllowedMethods(uri, allowedMethods)).build(); }
@Test public void testDefinition() throws Exception { RestTriggerResource resource = new RestTriggerResource(); RestTriggerResource.Definition definition = resource .redirectToTrigger(); DefinitionBackend backend = new DefinitionBackend(); TriggerDefinitionService service = Mockito .mock(TriggerDefinitionService.class); backend.setService(service); resource.setDefinitionBackend(backend); TriggerParameters params = new TriggerParameters(); params.setId(new Long(1L)); params.setMatch("1"); ContainerRequest request = Mockito.mock(ContainerRequest.class); Mockito.when(request.getProperty(Mockito.anyString())) .thenReturn(new Integer(CommonParams.VERSION_1)); ExtendedUriInfo uri = Mockito.mock(ExtendedUriInfo.class); Mockito.when(request.getUriInfo()).thenReturn(uri); Mockito.when(uri.getAbsolutePathBuilder()) .thenReturn(UriBuilder.fromPath("")); Response response = definition.getCollection(request, params); assertThat(response.getEntity(), IsInstanceOf.instanceOf(RepresentationCollection.class)); response = definition.getItem(request, params); assertThat(response.getEntity(), IsInstanceOf.instanceOf(DefinitionRepresentation.class)); DefinitionRepresentation content = new DefinitionRepresentation(); content.setId(new Long(1L)); content.setETag(new Long(1L)); content.setDescription("abc"); content.setSuspending(Boolean.TRUE); content.setType("REST_SERVICE"); content.setTargetURL("http://abc.de/asdf"); content.setAction("SUBSCRIBE_TO_SERVICE"); response = definition.postCollection(request, content, params); assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); response = definition.putItem(request, content, params); assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); }
/** * Returns a list of template names to be considered as candidates for resolving * {@link org.glassfish.jersey.server.mvc.Viewable viewable} into * {@link org.glassfish.jersey.server.mvc.spi.ResolvedViewable resolved viewable}. * <p/> * Order of template names to be resolved is as follows: * <ul> * <li>{{@value #IMPLICIT_VIEW_PATH_PARAMETER}} value</li> * <li>{@link org.glassfish.jersey.server.mvc.Template#name()}</li> * <li>last sub-resource manager path</li> * <li>index</li> * </ul> * * @param requestContext request context to obtain {@link #IMPLICIT_VIEW_PATH_PARAMETER} value from. * @return a non-empty list of template names. */ private List<String> getTemplateNames(final ContainerRequestContext requestContext) { final List<String> templateNames = Lists.newArrayList(); // Template name extracted from path param. final String pathTemplate = requestContext.getUriInfo().getPathParameters().getFirst(IMPLICIT_VIEW_PATH_PARAMETER); if (pathTemplate != null) { templateNames.add(pathTemplate); } // Annotation. if (this.templateName != null && this.templateName.length > 0) { for (String name : this.templateName) { if (StringUtils.isNotBlank(name)) { templateNames.add(name); } } } // Sub-resource path. final ExtendedUriInfo uriInfo = extendedUriInfoProvider.get(); final List<RuntimeResource> matchedRuntimeResources = uriInfo.getMatchedRuntimeResources(); if (matchedRuntimeResources.size() > 1) { // > 1 to check that we matched sub-resource final RuntimeResource lastMatchedRuntimeResource = matchedRuntimeResources.get(0); final Resource lastMatchedResource = lastMatchedRuntimeResource.getResources().get(0); String path = lastMatchedResource.getPath(); if (path != null && !IMPLICIT_VIEW_PATH_PARAMETER_TEMPLATE.equals(path)) { path = path.charAt(0) == '/' ? path.substring(1, path.length()) : path; templateNames.add(path); } } // Index. if (templateNames.isEmpty()) { templateNames.add("index"); } return templateNames; }
/** * <p>generateRespBuilder.</p> * * @param extendedUriInfo a {@link org.glassfish.jersey.server.ExtendedUriInfo} object. * @param mediaType a {@link javax.ws.rs.core.MediaType} object. * @return a {@link javax.ws.rs.core.Response.ResponseBuilder} object. */ protected static Response.ResponseBuilder generateRespBuilder(ExtendedUriInfo extendedUriInfo, MediaType mediaType) { return generateRespBuilder(null, extendedUriInfo, mediaType, null); }
/** * <p>generate.</p> * * @param allowedMethods a {@link java.util.Set} object. * @param mediaType a {@link javax.ws.rs.core.MediaType} object. * @param extendedUriInfo a {@link org.glassfish.jersey.server.ExtendedUriInfo} object. * @param containerRequestContext a {@link javax.ws.rs.container.ContainerRequestContext} object. * @param response a {@link javax.ws.rs.core.Response} object. * @return a {@link javax.ws.rs.core.Response} object. */ Response generate(Set<String> allowedMethods, MediaType mediaType, ExtendedUriInfo extendedUriInfo, ContainerRequestContext containerRequestContext, Response response);
/** * <p>getUriInfo.</p> * * @return a {@link org.glassfish.jersey.server.ExtendedUriInfo} object. */ public ExtendedUriInfo getUriInfo() { return event.getUriInfo(); }
/** * <p>getUriInfo.</p> * * @return a {@link org.glassfish.jersey.server.ExtendedUriInfo} object. */ public static ExtendedUriInfo getUriInfo() { return getRequest().getUriInfo(); }