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

The following examples show how to use org.glassfish.jersey.server.model.Resource. 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: RouteHelper.java    From ameba with MIT License 6 votes vote down vote up
/**
 * <p>getRoutes.</p>
 *
 * @return a {@link java.util.List} object.
 */
@GET
public List<String> getRoutes() {
    List<Resource> resourceList = resourceContext.getResourceModel().getResources();
    List<String> routeList = Lists.newArrayList();
    for (Resource resource : resourceList) {
        String path = resource.getPath().startsWith("/") ? "" : "/" + resource.getPath();
        if (resource.getAllMethods().size() > 0) {
            routeList.add(path);
        }
        routeList.addAll(
                resource.getChildResources()
                        .stream()
                        .map(res -> path + (res.getPath().startsWith("/") ? "" : "/") + res.getPath())
                        .collect(Collectors.toList())
        );
    }
    return routeList;
}
 
Example #2
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 #3
Source File: JerseyUtil.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Registers any Guice-bound providers or root resources.
 */
public static void registerGuiceBound(Injector injector, final JerseyEnvironment environment) {
    while (injector != null) {
        for (Key<?> key : injector.getBindings().keySet()) {
            Type type = key.getTypeLiteral().getType();
            if (type instanceof Class) {
                Class<?> c = (Class) type;
                if (isProviderClass(c)) {
                    logger.info("Registering {} as a provider class", c.getName());
                    environment.register(c);
                } else if (isRootResourceClass(c)) {
                    // Jersey rejects resources that it doesn't think are acceptable
                    // Including abstract classes and interfaces, even if there is a valid Guice binding.
                    if (Resource.isAcceptable(c)) {
                        logger.info("Registering {} as a root resource class", c.getName());
                        environment.register(c);
                    } else {
                        logger.warn("Class {} was not registered as a resource. Bind a concrete implementation instead.", c.getName());
                    }
                }

            }
        }
        injector = injector.getParent();
    }
}
 
Example #4
Source File: DropwizardModule.java    From dropwizard-guicier with Apache License 2.0 6 votes vote down vote up
private void registerResourcesAndProviders(ResourceConfig config, Injector injector) {
  while (injector != null) {
    for (Key<?> key : injector.getBindings().keySet()) {
      Type type = key.getTypeLiteral().getType();
      if (type instanceof Class<?>) {
        Class<?> c = (Class<?>) type;
        if (isProviderClass(c)) {
          LOG.info("Registering {} as a provider class", c.getName());
          config.register(c);
        } else if (isResourceClass(c)) {
          // Jersey rejects resources that it doesn't think are acceptable
          // Including abstract classes and interfaces, even if there is a valid Guice binding.
          if(Resource.isAcceptable(c)) {
            LOG.info("Registering {} as a root resource class", c.getName());
            config.register(c);
          } else {
            LOG.warn("Class {} was not registered as a resource; bind a concrete implementation instead", c.getName());
          }
        }

      }
    }
    injector = injector.getParent();
  }
}
 
Example #5
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 #6
Source File: OpenAPIInflector.java    From swagger-inflector with Apache License 2.0 6 votes vote down vote up
private void addConsumesToResource(String mediaType, Resource.Builder builder, String method, OpenAPIOperationController controller) {
    if (StringUtils.isNotBlank(mediaType)) {
        try {
            MediaType media = MediaType.valueOf(mediaType);
            if (media.getSubtype().equals("yaml")) {
                builder.addMethod(method).handledBy(controller);
            } else {
                builder.addMethod(method).handledBy(controller).consumes(media.toString());
            }
        } catch (Exception e) {
            LOGGER.error("unable to find a matching mediatype for " + mediaType + " in " + controller.getMethodName());
        }
    }else{
        builder.addMethod(method).handledBy(controller);
    }
}
 
Example #7
Source File: OzarkModelProcessorTest.java    From ozark with Apache License 2.0 5 votes vote down vote up
@Test
public void processResourceModel() {
	ResourceModel.Builder rmb = new ResourceModel.Builder(false);
	Resource resource = Resource.builder(SomeController.class).build();
	rmb.addResource(resource);
	ResourceModel processedModel = new OzarkModelProcessor().processResourceModel(rmb.build(), null);
	Resource processedResource = processedModel.getResources().get(0);
	processedResource.getResourceMethods().forEach(m -> assertTrue(m.getProducedTypes().contains(MediaType.TEXT_HTML_TYPE)));
}
 
Example #8
Source File: Api1.java    From para with Apache License 2.0 5 votes vote down vote up
private void registerCrudApi(String path, Inflector<ContainerRequestContext, Response> handler,
		Inflector<ContainerRequestContext, Response> linksHandler) {
	Resource.Builder core = Resource.builder(path);
	// list endpoints (both do the same thing)
	core.addMethod(GET).produces(JSON).handledBy(handler);
	core.addChildResource("search/{querytype}").addMethod(GET).produces(JSON).handledBy(handler);
	core.addChildResource("search").addMethod(GET).produces(JSON).handledBy(handler);
	// CRUD endpoints (non-batch)
	core.addMethod(POST).produces(JSON).consumes(JSON).handledBy(handler);
	core.addChildResource("{id}").addMethod(GET).produces(JSON).handledBy(handler);
	core.addChildResource("{id}").addMethod(PUT).produces(JSON).consumes(JSON).handledBy(handler);
	core.addChildResource("{id}").addMethod(PATCH).produces(JSON).consumes(JSON).handledBy(handler);
	core.addChildResource("{id}").addMethod(DELETE).produces(JSON).handledBy(handler);
	// links CRUD endpoints
	core.addChildResource("{id}/links/{type2}/{id2}").addMethod(GET).produces(JSON).handledBy(linksHandler);
	core.addChildResource("{id}/links/{type2}").addMethod(GET).produces(JSON).handledBy(linksHandler);
	core.addChildResource("{id}/links/{id2}").addMethod(POST).produces(JSON).handledBy(linksHandler);
	core.addChildResource("{id}/links/{id2}").addMethod(PUT).produces(JSON).handledBy(linksHandler);
	core.addChildResource("{id}/links/{type2}/{id2}").addMethod(DELETE).produces(JSON).handledBy(linksHandler);
	core.addChildResource("{id}/links").addMethod(DELETE).produces(JSON).handledBy(linksHandler);
	// CRUD endpoints (batch)
	Resource.Builder batch = Resource.builder("_batch");
	batch.addMethod(POST).produces(JSON).consumes(JSON).handledBy(batchCreateHandler(null));
	batch.addMethod(GET).produces(JSON).handledBy(batchReadHandler(null));
	batch.addMethod(PUT).produces(JSON).consumes(JSON).handledBy(batchCreateHandler(null));
	batch.addMethod(PATCH).produces(JSON).consumes(JSON).handledBy(batchUpdateHandler(null));
	batch.addMethod(DELETE).produces(JSON).handledBy(batchDeleteHandler(null));

	registerResources(core.build());
	registerResources(batch.build());
}
 
Example #9
Source File: OpenAPIInflector.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
private void enableSwaggerYAML(OpenAPI openAPI, List<String> swaggerProcessors) {
    final Resource.Builder builder = Resource.builder();
    builder.path(basePath(originalBasePath, StringUtils.appendIfMissing(config.getSwaggerBase(), "/") + "openapi.yaml"))
            .addMethod(HttpMethod.GET)
            .produces("application/yaml")
            .handledBy(new OpenAPIResourceController(openAPI, swaggerProcessors))
            .build();

    registerResources(builder.build());
}
 
Example #10
Source File: OpenAPIInflector.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
private void enableSwaggerJSON(OpenAPI openAPI, List<String> swaggerProcessors) {
    final Resource.Builder builder = Resource.builder();
    builder.path(basePath(originalBasePath, StringUtils.appendIfMissing(config.getSwaggerBase(), "/") + "openapi.json"))
            .addMethod(HttpMethod.GET)
            .produces(MediaType.APPLICATION_JSON)
            .handledBy(new OpenAPIResourceController(openAPI, swaggerProcessors))
            .build();

    registerResources(builder.build());
}
 
Example #11
Source File: OzarkModelProcessor.java    From ozark with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if a resource is a controller.
 *
 * @param resource resource to test.
 * @return outcome of controller test.
 */
private static boolean isController(Resource resource) {
    final Boolean b1 = resource.getHandlerClasses().stream()
            .map(c -> c.isAnnotationPresent(Controller.class))
            .reduce(Boolean.FALSE, Boolean::logicalOr);
    final Boolean b2 = resource.getHandlerInstances().stream()
            .map(o -> o.getClass().isAnnotationPresent(Controller.class))
            .reduce(Boolean.FALSE, Boolean::logicalOr);
    return b1 || b2;
}
 
Example #12
Source File: KrazoModelProcessorTest.java    From krazo with Apache License 2.0 5 votes vote down vote up
@Test
public void processResourceModel() {
	ResourceModel.Builder rmb = new ResourceModel.Builder(false);
	Resource resource = Resource.builder(SomeController.class).build();
	rmb.addResource(resource);
	ResourceModel processedModel = new KrazoModelProcessor().processResourceModel(rmb.build(), null);
	Resource processedResource = processedModel.getResources().get(0);
	processedResource.getResourceMethods().forEach(m -> assertTrue(m.getProducedTypes().contains(MediaType.TEXT_HTML_TYPE)));
}
 
Example #13
Source File: KrazoModelProcessor.java    From krazo with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if a resource is a controller.
 *
 * @param resource resource to test.
 * @return outcome of controller test.
 */
private static boolean isController(Resource resource) {
    final Boolean b1 = resource.getHandlerClasses().stream()
            .map(c -> c.isAnnotationPresent(Controller.class))
            .reduce(Boolean.FALSE, Boolean::logicalOr);
    final Boolean b2 = resource.getHandlerInstances().stream()
            .map(o -> o.getClass().isAnnotationPresent(Controller.class))
            .reduce(Boolean.FALSE, Boolean::logicalOr);
    return b1 || b2;
}
 
Example #14
Source File: ProfileAPI.java    From hugegraph with Apache License 2.0 5 votes vote down vote up
@GET
@Timed
@Produces(MediaType.APPLICATION_JSON)
public String getProfile(@Context Application application) {
    // May init multi times by multi threads, but no effect on the results
    if (SERVER_PROFILES != null) {
        return SERVER_PROFILES;
    }

    Map<String, Object> profiles = InsertionOrderUtil.newMap();
    profiles.put("service", SERVICE);
    profiles.put("version", CoreVersion.VERSION.toString());
    profiles.put("doc", DOC);
    profiles.put("api_doc", API_DOC);
    Set<String> apis = new TreeSet<>();
    for (Class<?> clazz : application.getClasses()) {
        if (!isAnnotatedPathClass(clazz)) {
            continue;
        }
        Resource resource = Resource.from(clazz);
        APICategory apiCategory = APICategory.parse(resource.getName());
        apis.add(apiCategory.dir);
    }
    profiles.put("apis", apis);
    SERVER_PROFILES = JsonUtil.toJson(profiles);
    return SERVER_PROFILES;
}
 
Example #15
Source File: FakeExtendedUriInfo.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public List<Resource> getLocatorSubResources() {
  return null;
}
 
Example #16
Source File: FakeExtendedUriInfo.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public Resource getMatchedModelResource() {
  return null;
}
 
Example #17
Source File: JerseyRouteExecutionStrategyUtils.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
@Override
public void visitResource(final Resource resource) {
    processComponents(resource);
}
 
Example #18
Source File: DynamicCypherResource.java    From SciGraph with Apache License 2.0 4 votes vote down vote up
public Resource.Builder getBuilder() {
  return resourceBuilder;
}
 
Example #19
Source File: JerseyRouteExecutionStrategyUtils.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
@Override
public void visitChildResource(final Resource resource) {
    processComponents(resource);
}
 
Example #20
Source File: Application.java    From ameba with MIT License 2 votes vote down vote up
/**
 * <p>registerResources.</p>
 *
 * @param resources a {@link java.util.Set} object.
 * @return a {@link ameba.core.Application} object.
 */
public Application registerResources(Set<Resource> resources) {
    config.registerResources(resources);
    return this;
}
 
Example #21
Source File: Application.java    From ameba with MIT License 2 votes vote down vote up
/**
 * <p>registerResources.</p>
 *
 * @param resources a {@link org.glassfish.jersey.server.model.Resource} object.
 * @return a {@link ameba.core.Application} object.
 */
public Application registerResources(Resource... resources) {
    config.registerResources(resources);
    return this;
}
 
Example #22
Source File: Application.java    From ameba with MIT License 2 votes vote down vote up
/**
 * <p>getResources.</p>
 *
 * @return a {@link java.util.Set} object.
 */
public Set<Resource> getResources() {
    return config.getResources();
}