org.glassfish.jersey.server.model.ResourceMethod Java Examples

The following examples show how to use org.glassfish.jersey.server.model.ResourceMethod. 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: MetricsResourceMethodApplicationListener.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
private MethodMetrics getMethodMetrics(RequestEvent event) {
  ResourceMethod method = event.getUriInfo().getMatchedResourceMethod();
  if (method == null) {
    return null;
  }

  RequestScopedMetrics metrics = this.metrics.get(method.getInvocable().getDefinitionMethod());
  if (metrics == null) {
    return null;
  }

  Map tags = (Map) event.getContainerRequest().getProperty(REQUEST_TAGS_PROP_KEY);
  if (tags == null) {
    return metrics.metrics();
  }

  // we have additional tags, find the appropriate metrics holder
  return metrics.metrics(tags);
}
 
Example #2
Source File: MetricsResourceMethodApplicationListener.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #3
Source File: KrazoModelProcessor.java    From krazo with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #4
Source File: MetricsRequestEventListener.java    From micrometer with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: HandlerTest.java    From lambadaframework with MIT License 6 votes vote down vote up
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;
    }
 
Example #6
Source File: OzarkModelProcessor.java    From ozark with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #7
Source File: JerseyRouteExecutionStrategyUtils.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Override
public void visitResourceMethod(final ResourceMethod method) {
    resourceMethodDeque.push(method);
    try {
        processComponents(method);
    } finally {
        resourceMethodDeque.pop();
    }
}
 
Example #8
Source File: EventParser.java    From brave with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked prior to request invocation during {@link RequestEventListener#onEvent(RequestEvent)}
 * where the event type is {@link RequestEvent.Type#REQUEST_MATCHED}
 *
 * <p>Adds the tags {@link #RESOURCE_CLASS} and {@link #RESOURCE_METHOD}. Override or use {@link
 * #NOOP} to change this behavior.
 */
protected void requestMatched(RequestEvent event, SpanCustomizer customizer) {
  ResourceMethod method = event.getContainerRequest().getUriInfo().getMatchedResourceMethod();
  if (method == null) return; // This case is extremely odd as this is called on REQUEST_MATCHED!
  Invocable i = method.getInvocable();
  customizer.tag(RESOURCE_CLASS, i.getHandler().getHandlerClass().getSimpleName());
  customizer.tag(RESOURCE_METHOD, i.getHandlingMethod().getName());
}
 
Example #9
Source File: MetricsResourceMethodApplicationListener.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
public ConstructionContext(
    ResourceMethod method,
    PerformanceMetric performanceMetric,
    MetricsResourceMethodApplicationListener methodAppListener
) {
  this.method = method;
  this.performanceMetric = performanceMetric;
  this.metrics = methodAppListener.metrics;
  this.metricTags = methodAppListener.metricTags;
  this.metricGrpPrefix = methodAppListener.metricGrpPrefix;
}
 
Example #10
Source File: MetricsResourceMethodApplicationListener.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
private void register(ResourceMethod method) {
  final Method definitionMethod = method.getInvocable().getDefinitionMethod();
  if (definitionMethod.isAnnotationPresent(PerformanceMetric.class)) {
    PerformanceMetric annotation = definitionMethod.getAnnotation(PerformanceMetric.class);

    MethodMetrics m = new MethodMetrics(method, annotation, metrics, metricGrpPrefix, metricTags);
    ConstructionContext context = new ConstructionContext(method, annotation, this);
    methodMetrics.put(definitionMethod, new RequestScopedMetrics(m, context));
  }
}
 
Example #11
Source File: DynamicCypherResource.java    From SciGraph with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #12
Source File: TransactionEventListener.java    From registry with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #13
Source File: TransactionEventListener.java    From registry with Apache License 2.0 5 votes vote down vote up
public UnitOfWorkEventListener(ConcurrentMap<ResourceMethod, Optional<UnitOfWork>> methodMap,
                               TransactionManager transactionManager,
                               boolean runWithTxnIfNotConfigured,
                               TransactionIsolation defaultTransactionIsolation) {
    this.methodMap = methodMap;
    this.transactionManager = transactionManager;
    this.runWithTxnIfNotConfigured = runWithTxnIfNotConfigured;
    this.defaultTransactionIsolation = defaultTransactionIsolation;
}
 
Example #14
Source File: RouterTest.java    From lambadaframework with MIT License 5 votes vote down vote up
@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);
}
 
Example #15
Source File: RouterTest.java    From lambadaframework with MIT License 5 votes vote down vote up
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;
    }
 
Example #16
Source File: JerseyRouteExecutionStrategyUtils.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private static void validateRouteExecutionStrategyAnnotationIfPresent(
        final Method method,
        final Class<?> clazz,
        final RouteExecutionStrategyFactory<HttpExecutionStrategy> strategyFactory,
        @Nullable final ResourceMethod resourceMethod,
        final Set<String> errors) {

    final Annotation annotation = RouteExecutionStrategyUtils
            .validateRouteExecutionStrategyAnnotationIfPresent(method, clazz, strategyFactory, errors);

    if (annotation == null) {
        return;
    }

    if (resourceMethod != null) {
        if (resourceMethod.isManagedAsyncDeclared()) {
            // ManagedAsync is Jersey's executor offloading mechanism: it can't be used conjointly with
            // our own offloading mechanism
            errors.add("Execution strategy annotations are not supported on @ManagedAsync: " + method);
        } else if (resourceMethod.isSuspendDeclared()) {
            // We use Jersey's async context to suspend/resume request processing when we offload to an
            // executor. This prevents other JAX-RS resources that use the same mechanism to work properly
            // like @Suspended AsyncResponse...
            errors.add("Execution strategy annotations are not supported on AsyncResponse: " + method);
        } else if (resourceMethod.isSse()) {
            // ...and Server-Sent Events
            errors.add("Execution strategy annotations are not supported on Server-Sent Events: " + method);
        }
    }

    if (CompletionStage.class.isAssignableFrom(method.getReturnType())) {
        // Jersey suspends/resumes request handling in case the response is a non-realized CompletionStage.
        // This makes such responses incompatible with our offloading because we use suspend/resume too
        // and a request can only be suspended once.
        // Users that need executor offloading with CompletionStage should return Single instead.
        errors.add("Execution strategy annotations are not supported on CompletionStage returning method: " +
                method + " Consider returning " + Single.class.getSimpleName() + " instead.");
    }
}
 
Example #17
Source File: DynamicCypherResourceTest.java    From SciGraph with Apache License 2.0 4 votes vote down vote up
@Test
public void resourceMethodsAreAdded() {
  DynamicCypherResource resource = new DynamicCypherResource(factory, "foo", path);
  ResourceMethod method = getOnlyElement(resource.getBuilder().build().getResourceMethods());
  assertThat(method.getHttpMethod(), is("GET"));
}
 
Example #18
Source File: AbstractMessageBodyReaderWriter.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
static boolean isSse(ContainerRequestContext requestCtx) {
    final ResourceMethod method = ((ExtendedUriInfo) requestCtx.getUriInfo()).getMatchedResourceMethod();
    return method != null && method.isSse();
}
 
Example #19
Source File: FakeExtendedUriInfo.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public ResourceMethod getMatchedResourceMethod() {
  return null;
}
 
Example #20
Source File: FakeExtendedUriInfo.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public List<ResourceMethod> getMatchedResourceLocators() {
  return null;
}
 
Example #21
Source File: JacksonSerializerMessageBodyReaderWriter.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
private static boolean isSse(ContainerRequestContext requestCtx) {
    final ResourceMethod method = ((ExtendedUriInfo) requestCtx.getUriInfo()).getMatchedResourceMethod();
    return method != null && method.isSse();
}
 
Example #22
Source File: OzarkModelProcessor.java    From ozark with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}
 
Example #23
Source File: KrazoModelProcessor.java    From krazo with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}