Search in sources :

Example 1 with ResourceMethod

use of org.glassfish.jersey.server.model.ResourceMethod in project jersey by jersey.

the class NaiveResourceMappingContext method buildMappings.

private void buildMappings() {
    if (mappings != null) {
        return;
    }
    mappings = new HashMap<>();
    erc.getResourceModel().accept(new ResourceModelVisitor() {

        Deque<PathPattern> stack = new LinkedList<>();

        private void processComponents(final ResourceModelComponent component) {
            final List<? extends ResourceModelComponent> components = component.getComponents();
            if (components != null) {
                for (final ResourceModelComponent rc : components) {
                    rc.accept(this);
                }
            }
        }

        @Override
        public void visitInvocable(final Invocable invocable) {
            processComponents(invocable);
        }

        @Override
        public void visitRuntimeResource(final RuntimeResource runtimeResource) {
            processComponents(runtimeResource);
        }

        @Override
        public void visitResourceModel(final ResourceModel resourceModel) {
            processComponents(resourceModel);
        }

        @Override
        public void visitResourceHandlerConstructor(final HandlerConstructor handlerConstructor) {
            processComponents(handlerConstructor);
        }

        @Override
        public void visitMethodHandler(final MethodHandler methodHandler) {
            processComponents(methodHandler);
        }

        @Override
        public void visitChildResource(final Resource resource) {
            visitResourceIntl(resource, false);
        }

        @Override
        public void visitResource(final Resource resource) {
            visitResourceIntl(resource, true);
        }

        private void visitResourceIntl(final Resource resource, final boolean isRoot) {
            try {
                stack.addLast(resource.getPathPattern());
                processComponents(resource);
                if (isRoot) {
                    Class likelyToBeRoot = null;
                    for (final Class next : resource.getHandlerClasses()) {
                        if (!(Inflector.class.isAssignableFrom(next))) {
                            likelyToBeRoot = next;
                        }
                    }
                    if (likelyToBeRoot != null) {
                        mappings.put(likelyToBeRoot, getMapping(getTemplate()));
                    }
                }
            } finally {
                stack.removeLast();
            }
        }

        @Override
        public void visitResourceMethod(final ResourceMethod resourceMethod) {
            if (resourceMethod.isExtended()) {
                return;
            }
            if (ResourceMethod.JaxrsType.SUB_RESOURCE_LOCATOR.equals(resourceMethod.getType())) {
                if (resourceMethod.getInvocable() != null) {
                    final Invocable i = resourceMethod.getInvocable();
                    final Type type = i.getResponseType();
                    final StringBuilder template = getTemplate();
                    mappings.put((Class) type, getMapping(template));
                    // Process sub resources ?
                    Resource.Builder builder = Resource.builder(i.getRawResponseType());
                    if (builder == null) {
                        // for example in the case the return type of the sub resource locator is Object
                        builder = Resource.builder().path(resourceMethod.getParent().getPath());
                    }
                    final Resource subResource = builder.build();
                    visitChildResource(subResource);
                }
            }
            processComponents(resourceMethod);
        }

        private StringBuilder getTemplate() {
            final StringBuilder template = new StringBuilder();
            for (final PathPattern pp : stack) {
                final String ppTemplate = pp.getTemplate().getTemplate();
                final int tlength = template.length();
                if (tlength > 0) {
                    if (template.charAt(tlength - 1) == '/') {
                        if (ppTemplate.startsWith("/")) {
                            template.append(ppTemplate, 1, ppTemplate.length());
                        } else {
                            template.append(ppTemplate);
                        }
                    } else {
                        if (ppTemplate.startsWith("/")) {
                            template.append(ppTemplate);
                        } else {
                            template.append("/");
                            template.append(ppTemplate);
                        }
                    }
                } else {
                    template.append(ppTemplate);
                }
            }
            return template;
        }
    });
}
Also used : Inflector(org.glassfish.jersey.process.Inflector) Resource(org.glassfish.jersey.server.model.Resource) RuntimeResource(org.glassfish.jersey.server.model.RuntimeResource) ResourceModelComponent(org.glassfish.jersey.server.model.ResourceModelComponent) LinkedList(java.util.LinkedList) RuntimeResource(org.glassfish.jersey.server.model.RuntimeResource) Invocable(org.glassfish.jersey.server.model.Invocable) PathPattern(org.glassfish.jersey.uri.PathPattern) HandlerConstructor(org.glassfish.jersey.server.model.HandlerConstructor) MethodHandler(org.glassfish.jersey.server.model.MethodHandler) Type(java.lang.reflect.Type) ResourceModelVisitor(org.glassfish.jersey.server.model.ResourceModelVisitor) ResourceModel(org.glassfish.jersey.server.model.ResourceModel) List(java.util.List) LinkedList(java.util.LinkedList) ResourceMethod(org.glassfish.jersey.server.model.ResourceMethod)

Example 2 with ResourceMethod

use of org.glassfish.jersey.server.model.ResourceMethod in project jersey by jersey.

the class ServerScopeProvider method getFilteringScopes.

@Override
public Set<String> getFilteringScopes(final Annotation[] entityAnnotations, final boolean defaultIfNotFound) {
    Set<String> filteringScope = super.getFilteringScopes(entityAnnotations, false);
    if (filteringScope.isEmpty()) {
        final ExtendedUriInfo uriInfo = uriInfoProvider.get();
        final String path = uriInfo.getPath();
        if (uriToContexts.containsKey(path)) {
            return uriToContexts.get(path);
        }
        for (final ResourceMethod method : ServerScopeProvider.getMatchedMethods(uriInfo)) {
            final Invocable invocable = method.getInvocable();
            mergeFilteringScopes(filteringScope, getFilteringScopes(invocable.getHandlingMethod(), invocable.getHandler().getHandlerClass()));
            if (!filteringScope.isEmpty()) {
                uriToContexts.putIfAbsent(path, filteringScope);
                return filteringScope;
            }
        }
    }
    // Use default scope if not in other scope.
    return returnFilteringScopes(filteringScope, defaultIfNotFound);
}
Also used : Invocable(org.glassfish.jersey.server.model.Invocable) ResourceMethod(org.glassfish.jersey.server.model.ResourceMethod) ExtendedUriInfo(org.glassfish.jersey.server.ExtendedUriInfo)

Example 3 with ResourceMethod

use of org.glassfish.jersey.server.model.ResourceMethod in project jersey by jersey.

the class MonitoringStatisticsTest method testUrisWithProgrammaticResourcesAndExecution.

@Test
public void testUrisWithProgrammaticResourcesAndExecution() {
    final MonitoringStatisticsImpl.Builder statBuilder = getProgStats();
    final Resource.Builder resourceBuilder = Resource.builder();
    resourceBuilder.addMethod("GET").handledBy(MyInflector.class);
    resourceBuilder.addMethod("POST").handledBy(MyInflector.class);
    final Resource res = resourceBuilder.build();
    ResourceMethod getMethod;
    ResourceMethod postMethod;
    if (res.getResourceMethods().get(0).getHttpMethod().equals("GET")) {
        getMethod = res.getResourceMethods().get(0);
        postMethod = res.getResourceMethods().get(1);
    } else {
        getMethod = res.getResourceMethods().get(1);
        postMethod = res.getResourceMethods().get(0);
    }
    statBuilder.addExecution("/new/elefant", getMethod, 10, 5, 8, 8);
    statBuilder.addExecution("/new/elefant", getMethod, 20, 12, 18, 10);
    statBuilder.addExecution("/new/elefant", postMethod, 30, 2, 28, 4);
    final MonitoringStatisticsImpl stat = statBuilder.build();
    final Iterator<Map.Entry<String, ResourceStatistics>> it = stat.getUriStatistics().entrySet().iterator();
    check(it, "/hello", 2);
    check(it, "/hello/world", 1);
    check(it, "/new/elefant", 2);
    check(it, "/prog", 1);
    check(it, "/test-resource", 1);
    check(it, "/test-resource/child", 3);
    check(it, "/test-resource/prog-child", 1);
    final Map<ResourceMethod, ResourceMethodStatistics> resourceMethodStatistics = stat.getUriStatistics().get("/new/elefant").getResourceMethodStatistics();
    for (ResourceMethodStatistics methodStatistics : resourceMethodStatistics.values()) {
        final ResourceMethod method = methodStatistics.getResourceMethod();
        final ExecutionStatistics st = methodStatistics.getMethodStatistics();
        if (method.getHttpMethod().equals("GET")) {
            Assert.assertEquals(20, st.getLastStartTime().getTime());
        } else if (method.getHttpMethod().equals("POST")) {
            Assert.assertEquals(30, st.getLastStartTime().getTime());
        } else {
            Assert.fail();
        }
    }
}
Also used : ExecutionStatistics(org.glassfish.jersey.server.monitoring.ExecutionStatistics) ResourceMethodStatistics(org.glassfish.jersey.server.monitoring.ResourceMethodStatistics) Resource(org.glassfish.jersey.server.model.Resource) ResourceMethod(org.glassfish.jersey.server.model.ResourceMethod) Test(org.junit.Test)

Example 4 with ResourceMethod

use of org.glassfish.jersey.server.model.ResourceMethod in project jersey by jersey.

the class ModelProcessorUtil method enhanceResource.

/**
     * Enhance the runtime resource referenced by {@code resource} parameter with a list of additional methods.
     *
     * The new {@code methods} are added to the runtime resource. In case of method conflicts, the existing resource methods
     * will be preserved and will not be 'overridden' by any new method from the {@code methods} list.
     * Overriding check takes into account media types of methods so that new resource methods with same HTTP method
     * can be defined only for a more more specific media type.
     *
     * @param resource Runtime resource to be enhanced.
     * @param enhancedModelBuilder Builder for the enhanced resource model to be used.
     * @param methods List of enhancing methods.
     * @param extended This flag will initialize the property
     *                  {@link org.glassfish.jersey.server.model.ResourceMethod#isExtended()}.
     */
public static void enhanceResource(RuntimeResource resource, ResourceModel.Builder enhancedModelBuilder, List<Method> methods, boolean extended) {
    final Resource firstResource = resource.getResources().get(0);
    if (methodsSuitableForResource(firstResource, methods)) {
        for (Method method : methods) {
            final Set<MediaType> produces = new HashSet<>(method.produces);
            for (ResourceMethod resourceMethod : resource.getResourceMethods()) {
                for (final MediaType produce : method.produces) {
                    if (ModelProcessorUtil.isMethodOverridden(resourceMethod, method.httpMethod, method.consumes.get(0), produce)) {
                        produces.remove(produce);
                    }
                }
            }
            if (!produces.isEmpty()) {
                final Resource parentResource = resource.getParentResources().get(0);
                if (parentResource != null && method.path != null) {
                    continue;
                }
                final Resource.Builder resourceBuilder = Resource.builder(firstResource.getPath());
                final Resource.Builder builder = method.path != null ? resourceBuilder.addChildResource(method.path) : resourceBuilder;
                final ResourceMethod.Builder methodBuilder = builder.addMethod(method.httpMethod).consumes(method.consumes).produces(produces);
                if (method.inflector != null) {
                    methodBuilder.handledBy(method.inflector);
                } else {
                    methodBuilder.handledBy(method.inflectorClass);
                }
                methodBuilder.extended(extended);
                final Resource newResource = resourceBuilder.build();
                if (parentResource != null) {
                    final Resource.Builder parentBuilder = Resource.builder(parentResource.getPath());
                    parentBuilder.addChildResource(newResource);
                    enhancedModelBuilder.addResource(parentBuilder.build());
                } else {
                    enhancedModelBuilder.addResource(newResource);
                }
            }
        }
    }
    for (RuntimeResource child : resource.getChildRuntimeResources()) {
        enhanceResource(child, enhancedModelBuilder, methods, extended);
    }
}
Also used : Resource(org.glassfish.jersey.server.model.Resource) RuntimeResource(org.glassfish.jersey.server.model.RuntimeResource) MediaType(javax.ws.rs.core.MediaType) HttpMethod(javax.ws.rs.HttpMethod) ResourceMethod(org.glassfish.jersey.server.model.ResourceMethod) ResourceMethod(org.glassfish.jersey.server.model.ResourceMethod) HashSet(java.util.HashSet) RuntimeResource(org.glassfish.jersey.server.model.RuntimeResource)

Example 5 with ResourceMethod

use of org.glassfish.jersey.server.model.ResourceMethod in project jersey by jersey.

the class ModelProcessorUtil method getAllowedMethods.

/**
     * Return allowed methods for the given {@code resource}. OPTIONS and HEAD are always returned in the result.
     *
     * @param resource Resource for which resource methods should be found.
     * @return Set of resource methods that can be invoked on the given resource.
     */
public static Set<String> getAllowedMethods(RuntimeResource resource) {
    boolean getFound = false;
    Set<String> allowedMethods = new HashSet<>();
    for (ResourceMethod resourceMethod : resource.getResourceMethods()) {
        final String httpMethod = resourceMethod.getHttpMethod();
        allowedMethods.add(httpMethod);
        if (!getFound && httpMethod.equals(HttpMethod.GET)) {
            getFound = true;
        }
    }
    allowedMethods.add(HttpMethod.OPTIONS);
    if (getFound) {
        allowedMethods.add(HttpMethod.HEAD);
    }
    return allowedMethods;
}
Also used : ResourceMethod(org.glassfish.jersey.server.model.ResourceMethod) HashSet(java.util.HashSet)

Aggregations

ResourceMethod (org.glassfish.jersey.server.model.ResourceMethod)32 Method (java.lang.reflect.Method)13 Resource (org.glassfish.jersey.server.model.Resource)10 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)6 ResponseMetered (com.codahale.metrics.annotation.ResponseMetered)6 Invocable (org.glassfish.jersey.server.model.Invocable)6 Metered (com.codahale.metrics.annotation.Metered)4 Timed (com.codahale.metrics.annotation.Timed)4 MediaType (javax.ws.rs.core.MediaType)4 HashSet (java.util.HashSet)3 AcceptableMediaType (org.glassfish.jersey.message.internal.AcceptableMediaType)3 RuntimeResource (org.glassfish.jersey.server.model.RuntimeResource)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 Map (java.util.Map)2 HttpMethod (javax.ws.rs.HttpMethod)2 ExtendedUriInfo (org.glassfish.jersey.server.ExtendedUriInfo)2 ResourceMethodStatistics (org.glassfish.jersey.server.monitoring.ResourceMethodStatistics)2 Test (org.junit.Test)2