private Set<Timed> annotations(RequestEvent event) { final Set<Timed> timed = new HashSet<>(); final ResourceMethod matchingResourceMethod = event.getUriInfo().getMatchedResourceMethod(); if (matchingResourceMethod != null) { // collect on method level timed.addAll(timedFinder.findTimedAnnotations(matchingResourceMethod.getInvocable().getHandlingMethod())); // fallback on class level if (timed.isEmpty()) { timed.addAll(timedFinder.findTimedAnnotations(matchingResourceMethod.getInvocable().getHandlingMethod() .getDeclaringClass())); } } return timed; }
@Test public void map_ProducesPrecedence_WithValidData() throws IOException { // Arrange mockDefinition().host(DBEERPEDIA.OPENAPI_HOST).produces(MediaType.TEXT_PLAIN).path("/breweries", new Path().get(new Operation().vendorExtensions( ImmutableMap.of(OpenApiSpecificationExtensions.INFORMATION_PRODUCT, DBEERPEDIA.BREWERIES.stringValue())).produces(MediaType.APPLICATION_JSON).response( Status.OK.getStatusCode(), new Response().schema(mock(Property.class))))); when(informationProductResourceProviderMock.get(DBEERPEDIA.BREWERIES)).thenReturn( informationProductMock); // Act requestMapper.map(httpConfigurationMock); // Assert verify(httpConfigurationMock).registerResources(resourceCaptor.capture()); ResourceMethod method = resourceCaptor.getValue().getResourceMethods().get(0); assertThat(method.getProducedTypes(), hasSize(1)); assertThat(method.getProducedTypes().get(0), equalTo(MediaType.APPLICATION_JSON_TYPE)); }
@Test public void initialize_RegistersErrorResource_WhenCalled() { // Act errorModule.initialize(httpConfigurationMock); // Assert verify(httpConfigurationMock).registerResources(resourceCaptor.capture()); assertThat(resourceCaptor.getAllValues(), hasSize(1)); Resource resource = resourceCaptor.getValue(); assertThat(resource.getPath(), equalTo("/{domain}/__errors/{statusCode:\\d{3}}")); assertThat(resource.getResourceMethods(), hasSize(1)); ResourceMethod method = resource.getResourceMethods().get(0); assertThat(method.getHttpMethod(), CoreMatchers.equalTo(HttpMethod.GET)); assertThat(method.getProducedTypes(), contains(MediaType.TEXT_PLAIN_TYPE)); Object handler = resource.getHandlerInstances().iterator().next(); assertThat(handler, instanceOf(ServletErrorHandler.class)); }
@Test public void loadRepresentations_MapRepresentation_WithValidData() { // Arrange when(supportedMediaTypesScanner.getMediaTypes(any())).thenReturn( new MediaType[] {MediaType.valueOf("text/turtle")}); // Act ldRepresentationRequestMapper.loadRepresentations(httpConfiguration); // Assert Resource resource = (Resource) httpConfiguration.getResources().toArray()[0]; final ResourceMethod method = resource.getResourceMethods().get(0); assertThat(httpConfiguration.getResources(), hasSize(1)); assertThat(resource.getPath(), equalTo("/" + DBEERPEDIA.ORG_HOST + DBEERPEDIA.BASE_PATH.getLabel() + DBEERPEDIA.URL_PATTERN_VALUE)); assertThat(resource.getResourceMethods(), hasSize(1)); assertThat(method.getHttpMethod(), equalTo(HttpMethod.GET)); }
/** * Updates the default {@code @Produces} list of every controller method whose list is empty. * The new list contains a single media type: "text/html". * * @param r resource to process. * @return newly updated resource. */ private static Resource processResource(Resource r) { final boolean isControllerClass = isController(r); Resource.Builder rb = Resource.builder(r); r.getAllMethods().forEach( (ResourceMethod m) -> { if ((isController(m) || isControllerClass) && m.getProducedTypes().isEmpty()) { final ResourceMethod.Builder rmb = rb.updateMethod(m); rmb.produces(MediaType.TEXT_HTML_TYPE); rmb.build(); } } ); r.getChildResources().forEach(cr -> { rb.replaceChildResource(cr, processResource(cr)); }); return rb.build(); }
private void prepareAppEvent(final String resourceMethodName) throws NoSuchMethodException { final Resource.Builder builder = Resource.builder(); final MockResource mockResource = new MockResource(); final Method handlingMethod = mockResource.getClass().getMethod(resourceMethodName); Method definitionMethod = handlingMethod; final Class<?> interfaceClass = mockResource.getClass().getInterfaces()[0]; if (this.methodDefinedOnInterface(resourceMethodName, interfaceClass.getMethods())) { definitionMethod = interfaceClass.getMethod(resourceMethodName); } final ResourceMethod resourceMethod = builder.addMethod() .handlingMethod(handlingMethod) .handledBy(mockResource, definitionMethod).build(); final Resource resource = builder.build(); final ResourceModel model = new ResourceModel.Builder(false).addResource(resource).build(); when(this.appEvent.getResourceModel()).thenReturn(model); when(this.uriInfo.getMatchedResourceMethod()).thenReturn(resourceMethod); }
private Router getMockRouter(String methodName, Class<?>... parameterTypes) throws NoSuchMethodException { Invocable mockInvocable = PowerMock.createMock(Invocable.class); expect(mockInvocable.getHandlingMethod()) .andReturn(DummyController.class.getDeclaredMethod(methodName, parameterTypes)) .anyTimes(); expect(mockInvocable.getHandler()) .andReturn(MethodHandler.create(DummyController.class)) .anyTimes(); org.lambadaframework.jaxrs.model.ResourceMethod mockResourceMethod = PowerMock.createMock(org.lambadaframework.jaxrs.model.ResourceMethod .class); expect(mockResourceMethod.getInvocable()) .andReturn(mockInvocable) .anyTimes(); Router mockRouter = PowerMock.createMock(Router.class); expect(mockRouter.route(anyObject())) .andReturn(mockResourceMethod) .anyTimes(); PowerMock.replayAll(); return mockRouter; }
@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; } }
private void prepareAppEvent(String resourceMethodName) throws NoSuchMethodException { final Resource.Builder builder = Resource.builder(); final MockResource mockResource = new MockResource(); final Method handlingMethod = mockResource.getClass().getMethod(resourceMethodName); Method definitionMethod = handlingMethod; Class<?> interfaceClass = mockResource.getClass().getInterfaces()[0]; if (methodDefinedOnInterface(resourceMethodName, interfaceClass.getMethods())) { definitionMethod = interfaceClass.getMethod(resourceMethodName); } final ResourceMethod resourceMethod = builder.addMethod() .handlingMethod(handlingMethod) .handledBy(mockResource, definitionMethod).build(); final Resource resource = builder.build(); final ResourceModel model = new ResourceModel.Builder(false).addResource(resource).build(); when(appEvent.getResourceModel()).thenReturn(model); when(uriInfo.getMatchedResourceMethod()).thenReturn(resourceMethod); }
/** * Registers all the given {@link ResourceMethod} into the meter map and in * the {@link MetricRegistry}. * * @param resourceMethods * A list of {@link ResourceMethod} that will be metered for * failures. */ private void registerCircuitBreakerAnnotations(final List<ResourceMethod> resourceMethods) { resourceMethods.parallelStream() .filter(Objects::nonNull) .forEach(resourceMethod -> { this.getCircuitBreakerName(resourceMethod) .ifPresent(actualCircuitName -> { this.meterMap.put(actualCircuitName, this.circuitBreaker.getMeter( actualCircuitName, this.customThresholds.containsKey(actualCircuitName) ? this.customThresholds .get(actualCircuitName) : this.defaultThreshold)); final String openCircuitName = new StringBuilder(actualCircuitName) .append(OPEN_CIRCUIT_SUFFIX).toString(); this.meterMap.put(openCircuitName, this.metricRegistry.meter(openCircuitName)); }); }); }
/** * Builds the circuit breaker name with the given {@link ResourceMethod}. It * the method is {@code null} or the method is not annotated with * {@link CircuitBreaker} it will return {@code Optional.empty()}. * * @param resourceMethod * The method that may contain a {@link CircuitBreaker} * annotation and will be monitored. * @return An Optional of the circuit breaker name or * {@code Optional.empty()} if it's not annotated. */ private Optional<String> getCircuitBreakerName(final ResourceMethod resourceMethod) { // Apparently resourceMethod can be null. if (resourceMethod == null) { return Optional.empty(); } try (Timer.Context context = this.requestOverheadTimer.time()) { final Invocable invocable = resourceMethod.getInvocable(); Method method = invocable.getDefinitionMethod(); CircuitBreaker circuitBreaker = method.getAnnotation(CircuitBreaker.class); // In case it's a child class with a parent method annotated. if (circuitBreaker == null) { method = invocable.getHandlingMethod(); circuitBreaker = method.getAnnotation(CircuitBreaker.class); } if (circuitBreaker != null) { return Optional.of(StringUtils.defaultIfBlank(circuitBreaker.name(), name(invocable.getHandler().getHandlerClass(), method.getName()))); } else { return Optional.empty(); } } }
private static String getName(final ResourceMethod method, final PerformanceMetric annotation, String metric) { StringBuilder builder = new StringBuilder(); boolean prefixed = false; if (annotation != null && !annotation.value().equals(PerformanceMetric.DEFAULT_NAME)) { builder.append(annotation.value()); builder.append('.'); prefixed = true; } if (!prefixed && method != null) { String className = method.getInvocable().getDefinitionMethod() .getDeclaringClass().getSimpleName(); String methodName = method.getInvocable().getDefinitionMethod().getName(); builder.append(className); builder.append('.'); builder.append(methodName); builder.append('.'); } builder.append(metric); return builder.toString(); }
private void prepareAppEvent(String resourceMethodName) throws NoSuchMethodException { final Resource.Builder builder = Resource.builder(); final MockResource mockResource = new MockResource(); final Method handlingMethod = mockResource.getClass().getMethod(resourceMethodName); Method definitionMethod = handlingMethod; Class<?> interfaceClass = mockResource.getClass().getInterfaces()[0]; if (methodDefinedOnInterface(resourceMethodName, interfaceClass.getMethods())) { definitionMethod = interfaceClass.getMethod(resourceMethodName); } final ResourceMethod resourceMethod = builder.addMethod().handlingMethod(handlingMethod) .handledBy(mockResource, definitionMethod).build(); final Resource resource = builder.build(); final ResourceModel model = new ResourceModel.Builder(false).addResource(resource).build(); when(appEvent.getResourceModel()).thenReturn(model); when(uriInfo.getMatchedResourceMethod()).thenReturn(resourceMethod); }
/** * Builds new {@link Resource} from passed one with new * {@link org.glassfish.jersey.process.Inflector} implementation * {@link RestInflector} and with all child resources * * @param resource * @return {@link Resource} * @throws IOException */ public static Resource rebuildResource(Resource resource) throws IOException { Resource rebuiltResource; Resource.Builder builder = Resource.builder(resource.getPath()); builder.name(resource.getName()); MetaData metaData = getMetaData(resource); List<ResourceMethod> methods = resource.getAllMethods(); for (ResourceMethod method : methods) { addMethod(builder, method, metaData); } // Registers children resources recursively registerChildren(resource, builder); rebuiltResource = builder.build(); return rebuiltResource; }
@Test public void map_EndpointsCorrectly_WithValidData() throws IOException { // Arrange Property schema = mock(Property.class); mockDefinition().host(DBEERPEDIA.OPENAPI_HOST).basePath(DBEERPEDIA.OPENAPI_BASE_PATH).produces( ImmutableList.of(MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON)).path( "/breweries", new Path().get(new Operation().vendorExtensions( ImmutableMap.of(OpenApiSpecificationExtensions.INFORMATION_PRODUCT, DBEERPEDIA.BREWERIES.stringValue())).response(Status.OK.getStatusCode(), new Response().schema(schema)))); when(informationProductResourceProviderMock.get(DBEERPEDIA.BREWERIES)).thenReturn( informationProductMock); // Act requestMapper.map(httpConfigurationMock); // Assert verify(httpConfigurationMock).registerResources(resourceCaptor.capture()); Resource resource = resourceCaptor.getValue(); assertThat(resourceCaptor.getAllValues(), hasSize(1)); assertThat(resource.getPath(), equalTo("/" + DBEERPEDIA.OPENAPI_HOST + DBEERPEDIA.OPENAPI_BASE_PATH + "/breweries")); assertThat(resource.getResourceMethods(), hasSize(1)); ResourceMethod method = resource.getResourceMethods().get(0); assertThat(method.getHttpMethod(), equalTo(HttpMethod.GET)); assertThat(method.getProducedTypes(), contains(MediaType.TEXT_PLAIN_TYPE, MediaType.APPLICATION_JSON_TYPE)); GetRequestHandler requestHandler = (GetRequestHandler) resource.getHandlerInstances().iterator().next(); assertThat(requestHandler, sameInstance(getRequestHandlerMock)); }
@Test public void loadRedirections_MapRedirection_WithValidData() { // Act ldRedirectionRequestMapper.loadRedirections(httpConfiguration); // Assert Resource resource = (Resource) httpConfiguration.getResources().toArray()[0]; ResourceMethod method = resource.getResourceMethods().get(0); assertThat(method.getHttpMethod(), equalTo(GET)); assertThat(httpConfiguration.getResources(), hasSize(1)); assertThat(resource.getPath(), equalTo("/dbeerpedia.org/special{any: \\/id\\/(.+)$}")); assertThat(resource.getResourceMethods(), hasSize(1)); }
private void registerUnitOfWorkAnnotations(final ResourceMethod method) { UnitOfWork annotation = method.getInvocable().getDefinitionMethod() .getAnnotation(UnitOfWork.class); if (annotation == null) { annotation = method.getInvocable().getHandlingMethod().getAnnotation(UnitOfWork.class); } if (annotation != null) { this.methodMap.put(method.getInvocable().getDefinitionMethod(), annotation); } }
public UnitOfWorkEventListener(ConcurrentMap<ResourceMethod, Optional<UnitOfWork>> methodMap, TransactionManager transactionManager, boolean runWithTxnIfNotConfigured) { this.methodMap = methodMap; this.transactionManager = transactionManager; this.runWithTxnIfNotConfigured = runWithTxnIfNotConfigured; }
private static Optional<UnitOfWork> registerUnitOfWorkAnnotations(ResourceMethod method) { UnitOfWork annotation = method.getInvocable().getDefinitionMethod().getAnnotation(UnitOfWork.class); if (annotation == null) { annotation = method.getInvocable().getHandlingMethod().getAnnotation(UnitOfWork.class); } return Optional.ofNullable(annotation); }
protected JAXRSParser getJAXRSParser() { List<Resource> resourceList = new LinkedList<>(); org.glassfish.jersey.server.model.Resource.Builder resourceBuilder = org.glassfish.jersey.server.model.Resource.builder(); resourceBuilder.path("/{id}"); ResourceMethod resourceMethod = resourceBuilder .addMethod("GET") .handledBy(new Inflector<ContainerRequestContext, Object>() { @Override public Object apply(ContainerRequestContext containerRequestContext) { return "HELLO"; } }) .build(); resourceList.add(new Resource(resourceBuilder.build())); JAXRSParser mockJaxRSParser = PowerMock.createMock(JAXRSParser.class); expect(mockJaxRSParser.scan()) .andReturn(resourceList) .anyTimes(); expect(mockJaxRSParser.withPackageName(anyString(), anyObject(Class.class))) .andReturn(mockJaxRSParser) .anyTimes(); PowerMock.replayAll(); return mockJaxRSParser; }
@Test public void getRouter() throws Exception { Request request = new Request(); request .setMethod(Request.RequestMethod.GET) .setPackage("org.lambadaframework") .setPathtemplate("/{id}"); org.lambadaframework.jaxrs.model.ResourceMethod routedResource = Router .getRouter() .setJaxrsParser(getJAXRSParser()) .route(request); assertNotNull(routedResource); }
private void prepareAppEvent(String resourceMethodName) throws NoSuchMethodException { final Resource.Builder builder = Resource.builder(); final Method method = mockResource.getClass().getMethod(resourceMethodName); final ResourceMethod resourceMethod = builder.addMethod().handlingMethod(method).handledBy(mockResource, method).build(); final Resource resource = builder.build(); final ResourceModel model = new ResourceModel.Builder(false).addResource(resource).build(); when(appEvent.getResourceModel()).thenReturn(model); when(uriInfo.getMatchedResourceMethod()).thenReturn(resourceMethod); }
private void registerUnitOfWorkAnnotations(ResourceMethod method) { UnitOfWork annotation = method.getInvocable().getDefinitionMethod().getAnnotation(UnitOfWork.class); if (annotation == null) { annotation = method.getInvocable().getHandlingMethod().getAnnotation(UnitOfWork.class); } if (annotation != null) { this.methodMap.put(method.getInvocable().getDefinitionMethod(), annotation); } }
@Inject DynamicCypherResource(CypherInflectorFactory factory, @Assisted String pathName, @Assisted Path path) { logger.info("Building dynamic resource at " + pathName); resourceBuilder.path(pathName); ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("GET"); methodBuilder.produces( MediaType.APPLICATION_JSON_TYPE, CustomMediaTypes.APPLICATION_JSONP_TYPE, CustomMediaTypes.APPLICATION_GRAPHSON_TYPE, MediaType.APPLICATION_XML_TYPE, CustomMediaTypes.APPLICATION_GRAPHML_TYPE, CustomMediaTypes.APPLICATION_XGMML_TYPE, CustomMediaTypes.TEXT_GML_TYPE, CustomMediaTypes.TEXT_CSV_TYPE, CustomMediaTypes.TEXT_TSV_TYPE, CustomMediaTypes.IMAGE_JPEG_TYPE, CustomMediaTypes.IMAGE_PNG_TYPE) .handledBy(factory.create(pathName, path)); }
private void register(ResourceMethod method) { final Method definitionMethod = method.getInvocable().getDefinitionMethod(); if (definitionMethod.isAnnotationPresent(PerformanceMetric.class)) { PerformanceMetric annotation = definitionMethod.getAnnotation(PerformanceMetric.class); methodMetrics.put( definitionMethod, new MethodMetrics(method, annotation, this.metrics, metricGrpPrefix, metricTags)); } }
private MethodMetrics getMethodMetrics(RequestEvent event) { ResourceMethod method = event.getUriInfo().getMatchedResourceMethod(); if (method == null) { return null; } return this.metrics.get(method.getInvocable().getDefinitionMethod()); }
private Resource getResource(Inflector<ContainerRequestContext, ChunkedOutput<?>> inflector) { final Resource.Builder resourceBuilder = Resource.builder(); resourceBuilder.path("/"); final ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("GET"); methodBuilder.produces(MediaType.TEXT_PLAIN_TYPE) .handledBy(inflector); return resourceBuilder.build(); }
/** * Defines method for {@link Resource} to build * * @param builder * @param method * @param metaData */ private static void addMethod(Resource.Builder builder, ResourceMethod method, MetaData metaData) { List<MediaType> consumedTypes = method.getConsumedTypes(); List<MediaType> producedTypes = method.getProducedTypes(); Invocable invocable = method.getInvocable(); Method realMethod = invocable.getHandlingMethod(); List<Parameter> parameters = invocable.getParameters(); // Defines media type MediaType type; if (CollectionUtils.valid(consumedTypes)) { type = CollectionUtils.getFirst(consumedTypes); } else { type = null; } // REST Inflector to define bean methods Inflector<ContainerRequestContext, Response> inflector = new RestInflector( realMethod, metaData, type, parameters); // Builds new method for resource ResourceMethod.Builder methodBuilder = builder.addMethod(method .getHttpMethod()); methodBuilder.consumes(consumedTypes); methodBuilder.produces(producedTypes); methodBuilder.nameBindings(method.getNameBindings()); methodBuilder.handledBy(inflector); methodBuilder.build(); }
/** * Defines method for {@link Resource} to build * * @param builder * @param method * @param metaData */ private static void addMethod(Resource.Builder builder, ResourceMethod method, MetaData metaData) { List<MediaType> consumedTypes = method.getConsumedTypes(); List<MediaType> producedTypes = method.getProducedTypes(); Invocable invocable = method.getInvocable(); Method realMethod = invocable.getHandlingMethod(); List<Parameter> parameters = invocable.getParameters(); // Defines media type MediaType type; if (CollectionUtils.valid(consumedTypes)) { type = CollectionUtils.getFirst(consumedTypes); } else { type = null; } // Implementation of framework defined "Inflector" interface to define // bean // methods Inflector<ContainerRequestContext, Response> inflector = new RestInflector(realMethod, metaData, type, parameters); // Builds new method for resource ResourceMethod.Builder methodBuilder = builder.addMethod(method.getHttpMethod()); methodBuilder.consumes(consumedTypes); methodBuilder.produces(producedTypes); methodBuilder.nameBindings(method.getNameBindings()); methodBuilder.handledBy(inflector); methodBuilder.build(); }
@Test public void resourceTest() { Resource.Builder builder = Resource.builder(LightMareBean.class); Resource resource = builder.build(); System.out.println(resource.getName()); System.out.println(resource); List<ResourceMethod> methods = resource.getAllMethods(); // ResourceMethod.Builder methodBuilder; // String name = resource.getName(); Collection<Class<?>> handlers = resource.getHandlerClasses(); System.out.println(handlers); Class<?> beanClass; Method realMethod; List<Parameter> parameters; for (ResourceMethod method : methods) { System.out.println(method); realMethod = method.getInvocable().getHandlingMethod(); realMethod.getParameterTypes(); MethodHandler handler = method.getInvocable().getHandler(); List<? extends ResourceModelComponent> components = method .getInvocable().getComponents(); parameters = method.getInvocable().getParameters(); MethodHandler methodHandler = method.getInvocable().getHandler(); System.out.println(methodHandler); for (Parameter parameter : parameters) { System.out.println(parameter); System.out.println(parameter.getRawType()); } System.out.println(components); beanClass = handler.getHandlerClass(); System.out.println(beanClass); System.out.println(realMethod); } }
private void mapOpenApiDefinition(Swagger swagger, HttpConfiguration httpConfiguration) { String basePath = createBasePath(swagger); swagger.getPaths().forEach((path, pathItem) -> { ApiOperation apiOperation = SwaggerUtils.extractApiOperation(swagger, path, pathItem); if (apiOperation == null) { return; } Operation getOperation = apiOperation.getOperation(); validateOperation(apiOperation, swagger); String absolutePath = basePath.concat(path); if (!getOperation.getVendorExtensions().containsKey( OpenApiSpecificationExtensions.INFORMATION_PRODUCT)) { LOG.warn("Path '{}' is not mapped to an information product.", absolutePath); return; } String okStatusCode = Integer.toString(Status.OK.getStatusCode()); if (getOperation.getResponses() == null || !getOperation.getResponses().containsKey(okStatusCode)) { throw new ConfigurationException(String.format( "Resource '%s' does not specify a status %s response.", absolutePath, okStatusCode)); } List<String> produces = getOperation.getProduces() != null ? getOperation.getProduces() : swagger.getProduces(); if (produces == null) { throw new ConfigurationException( String.format("Path '%s' should produce at least one media type.", absolutePath)); } Response response = getOperation.getResponses().get(okStatusCode); if (response.getSchema() == null) { throw new ConfigurationException( String.format("Resource '%s' does not specify a schema for the status %s response.", absolutePath, okStatusCode)); } Property property = new ResponseProperty(response); // Will eventually be replaced by OASv3 Content object Map<MediaType, Property> schemaMap = produces.stream().collect(Collectors.toMap(MediaType::valueOf, mediaType -> property)); IRI informationProductIdentifier = valueFactory.createIRI((String) getOperation.getVendorExtensions().get( OpenApiSpecificationExtensions.INFORMATION_PRODUCT)); InformationProduct informationProduct = informationProductResourceProvider.get(informationProductIdentifier); Resource.Builder resourceBuilder = Resource.builder().path(absolutePath); ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod(apiOperation.getMethod().name()).handledBy( getRequestHandlerFactory.newGetRequestHandler(apiOperation, informationProduct, schemaMap, swagger)); produces.forEach(methodBuilder::produces); httpConfiguration.registerResources(resourceBuilder.build()); LOG.debug("Mapped {} operation for request path {}", apiOperation.getMethod().name(), absolutePath); }); }
@Test public void resourceMethodsAreAdded() { DynamicCypherResource resource = new DynamicCypherResource(factory, "foo", path); ResourceMethod method = getOnlyElement(resource.getBuilder().build().getResourceMethods()); assertThat(method.getHttpMethod(), is("GET")); }
public WebAppConfig() throws IOException { Collection<String> mimeTypeList = new HashSet<String>(); mimeTypeList.add(MediaType.APPLICATION_FORM_URLENCODED); mimeTypeList.add(MediaType.APPLICATION_JSON); mimeTypeList.add(MediaType.APPLICATION_OCTET_STREAM); mimeTypeList.add(MediaType.APPLICATION_SVG_XML); mimeTypeList.add(MediaType.APPLICATION_XHTML_XML); mimeTypeList.add(MediaType.APPLICATION_XML); mimeTypeList.add(MediaType.MULTIPART_FORM_DATA); mimeTypeList.add(MediaType.TEXT_HTML); mimeTypeList.add(MediaType.TEXT_PLAIN); mimeTypeList.add(MediaType.TEXT_XML); if (new File("./htdocs").exists()) { Collection<File> files = FileUtils.listFiles(new File("./htdocs"), null, true); for (File file : files) { final byte[] contents = FileUtils.readFileToByteArray(file); Resource.Builder resourceBuilder = Resource.builder(); resourceBuilder.path(file.getAbsolutePath().split("/htdocs/")[1]); final ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("GET"); String mimeType = MimeTypeFinder.probeContentType(Paths.get(file.toURI())); if (!mimeTypeList.contains(mimeType) && !file.getName().toLowerCase().endsWith(".jpg") && !file.getName().toLowerCase().endsWith(".jpeg") && !file.getName().toLowerCase().endsWith(".png") && !file.getName().toLowerCase().endsWith(".gif") && !file.getName().toLowerCase().endsWith(".ico")) { mimeTypeList.add(mimeType); } final File myFile = file; methodBuilder.produces(mimeType) .handledBy(new Inflector<ContainerRequestContext, byte[]>() { @Override public byte[] apply(ContainerRequestContext req) { if (!WebApp.DEV) { return contents; } try { return FileUtils.readFileToByteArray(myFile); } catch (IOException e) { return contents; } } }); registerResources(resourceBuilder.build()); } } register(MultiPartFeature.class); Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forJavaClassPath()) .filterInputsBy(new FilterBuilder().include(".*"))); Set<Class<? extends WebResource>> webResourceClasses = reflections.getSubTypesOf(WebResource.class); for (Class<? extends WebResource> webpageClass : webResourceClasses) { registerResources(Resource.builder(webpageClass).build()); } register(ExceptionHandler.class); mimeTypes = mimeTypeList.toArray(new String[0]); }
public MethodMetrics(ResourceMethod method, PerformanceMetric annotation, Metrics metrics, String metricGrpPrefix, Map<String, String> metricTags) { String metricGrpName = metricGrpPrefix + "-metrics"; this.requestSizeSensor = metrics.sensor(getName(method, annotation, "request-size")); MetricName metricName = new MetricName( getName(method, annotation, "request-rate"), metricGrpName, "The average number of HTTP requests per second.", metricTags); this.requestSizeSensor.add(metricName, new Rate(new Count())); metricName = new MetricName( getName(method, annotation, "request-byte-rate"), metricGrpName, "Bytes/second of incoming requests", metricTags); this.requestSizeSensor.add(metricName, new Avg()); metricName = new MetricName( getName(method, annotation, "request-size-avg"), metricGrpName, "The average request size in bytes", metricTags); this.requestSizeSensor.add(metricName, new Avg()); metricName = new MetricName( getName(method, annotation, "request-size-max"), metricGrpName, "The maximum request size in bytes", metricTags); this.requestSizeSensor.add(metricName, new Max()); this.responseSizeSensor = metrics.sensor(getName(method, annotation, "response-size")); metricName = new MetricName( getName(method, annotation, "response-rate"), metricGrpName, "The average number of HTTP responses per second.", metricTags); this.responseSizeSensor.add(metricName, new Rate(new Count())); metricName = new MetricName( getName(method, annotation, "response-byte-rate"), metricGrpName, "Bytes/second of outgoing responses", metricTags); this.responseSizeSensor.add(metricName, new Avg()); metricName = new MetricName( getName(method, annotation, "response-size-avg"), metricGrpName, "The average response size in bytes", metricTags); this.responseSizeSensor.add(metricName, new Avg()); metricName = new MetricName( getName(method, annotation, "response-size-max"), metricGrpName, "The maximum response size in bytes", metricTags); this.responseSizeSensor.add(metricName, new Max()); this.requestLatencySensor = metrics.sensor(getName(method, annotation, "request-latency")); metricName = new MetricName( getName(method, annotation, "request-latency-avg"), metricGrpName, "The average request latency in ms", metricTags); this.requestLatencySensor.add(metricName, new Avg()); metricName = new MetricName( getName(method, annotation, "request-latency-max"), metricGrpName, "The maximum request latency in ms", metricTags); this.requestLatencySensor.add(metricName, new Max()); this.errorSensor = metrics.sensor(getName(method, annotation, "errors")); metricName = new MetricName( getName(method, annotation, "request-error-rate"), metricGrpName, "The average number of requests per second that resulted in HTTP error responses", metricTags); this.errorSensor.add(metricName, new Rate()); }
private void printResource(Resource resource) { StringBuilder sb = new StringBuilder(); List<ResourceMethod> resourceMethods = resource.getResourceMethods(); if (!resourceMethods.isEmpty()) { sb.append("Resource["); sb.append("\n\tpath="); Resource parent = resource.getParent(); while (parent != null) { sb.append(parent.getPath()); parent = parent.getParent(); } sb.append(resource.getPath()); // sb.append(",pattern=" + resource.getPathPattern()); // sb.append(",name=" + resource.getName()); sb.append(",\n\tmethods=["); for (ResourceMethod resourceMethod : resourceMethods) { sb.append("\n\t\t[" + resourceMethod.getHttpMethod()); sb.append(",producedTypes=" + resourceMethod.getProducedTypes()); sb.append(",nameBindings=" + resourceMethod.getNameBindings()); Invocable invocable = resourceMethod.getInvocable(); sb.append(",handlingMethod=" + invocable.getHandlingMethod().getName()); if (invocable.getResponseType() != null) { sb.append(",responseType=" + invocable.getResponseType()); } else { sb.append(",rawResponseType=" + invocable.getRawResponseType()); } sb.append(",parameters["); for (Parameter parameter : invocable.getParameters()) { sb.append("[rawType=" + parameter.getRawType()); sb.append(",type=" + parameter.getType() + "]"); } sb.append("]"); sb.append("]"); } sb.append("\n\t]"); System.out.println(sb.toString()); } if (!resource.getChildResources().isEmpty()) { for (Resource childResource : resource.getChildResources()) { printResource(childResource); } } }
/** * Called by LensRequestListener in start event. marks the method meter, starts a timer, returns timer context * returned by the start timer call. * * @param method the resource method * @param containerRequest container request * @return * @see org.apache.lens.server.api.metrics.MetricsService#getMethodMetricsContext( *org.glassfish.jersey.server.model.ResourceMethod, org.glassfish.jersey.server.ContainerRequest) */ @Override public MethodMetricsContext getMethodMetricsContext(ResourceMethod method, ContainerRequest containerRequest) { // if method is null then it means no matching resource method was found. return enableResourceMethodMetering ? methodMetricsFactory.get(method, containerRequest).newContext() : DisabledMethodMetricsContext.getInstance(); }
/** * Determines if a resource method is a controller. * * @param method resource method to test. * @return outcome of controller test. */ private static boolean isController(ResourceMethod method) { return method.getInvocable().getDefinitionMethod().isAnnotationPresent(Controller.class); }
/** * This is a factory method for getting a MethodMetrics instance. First a unique name is determined for the arguments * and then function with same name is called with that unique name. * * @param method * @param containerRequest * @return * @see #get(String) * @see #getUniqueName(org.glassfish.jersey.server.model.ResourceMethod, org.glassfish.jersey.server.ContainerRequest) */ public MethodMetrics get(@NonNull ResourceMethod method, @NonNull ContainerRequest containerRequest) { return get(getUniqueName(method, containerRequest)); }