org.glassfish.jersey.server.model.Resource类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(15.0k)|赞(0)|评价(0)|浏览(139)

本文整理了Java中org.glassfish.jersey.server.model.Resource类的一些代码示例,展示了Resource类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Resource类的具体详情如下:
包路径:org.glassfish.jersey.server.model.Resource
类名称:Resource

Resource介绍

[英]Model of a single resource component.

Resource component model represents a collection of ResourceMethodgrouped under the same parent request path template. Resource class is also the main entry point to the programmatic resource modeling API that provides ability to programmatically extend the existing JAX-RS annotated resource classes or build new resource models that may be utilized by Jersey runtime.

For example:

@Path("hello") 
public class HelloResource { 
@GET 
@Produces("text/plain") 
public String sayHello() { 
return "Hello!"; 
} 
} 
... 
// Register the annotated resource. 
ResourceConfig resourceConfig = new ResourceConfig(HelloResource.class); 
// Add new "hello2" resource using the annotated resource class 
// and overriding the resource path. 
Resource.Builder resourceBuilder = 
Resource.builder(HelloResource.class, new LinkedList<ResourceModelIssue>()) 
.path("hello2"); 
// Add a new (virtual) sub-resource method to the "hello2" resource. 
resourceBuilder.addChildResource("world").addMethod("GET") 
.produces("text/plain") 
.handledBy(new Inflector<Request, String>() { 
@Override 
public String apply(Request request) { 
return "Hello World!"; 
} 
}); 
// Register the new programmatic resource in the application's configuration. 
resourceConfig.registerResources(resourceBuilder.build());

The following table illustrates the supported requests and provided responses for the application configured in the example above. RequestResponseMethod invoked"GET /hello""Hello!"HelloResource.sayHello()"GET /hello2""Hello!"HelloResource.sayHello()"GET /hello2/world""Hello World!"Inflector.apply()
[中]单个资源组件的模型。
资源组件模型表示在同一父请求路径模板下分组的ResourceMethod集合。资源类也是编程资源建模API的主要入口点,该API提供了以编程方式扩展现有JAX-RS注释的资源类或构建可供Jersey runtime使用的新资源模型的能力。
例如:

@Path("hello") 
public class HelloResource { 
@GET 
@Produces("text/plain") 
public String sayHello() { 
return "Hello!"; 
} 
} 
... 
// Register the annotated resource. 
ResourceConfig resourceConfig = new ResourceConfig(HelloResource.class); 
// Add new "hello2" resource using the annotated resource class 
// and overriding the resource path. 
Resource.Builder resourceBuilder = 
Resource.builder(HelloResource.class, new LinkedList<ResourceModelIssue>()) 
.path("hello2"); 
// Add a new (virtual) sub-resource method to the "hello2" resource. 
resourceBuilder.addChildResource("world").addMethod("GET") 
.produces("text/plain") 
.handledBy(new Inflector<Request, String>() { 
@Override 
public String apply(Request request) { 
return "Hello World!"; 
} 
}); 
// Register the new programmatic resource in the application's configuration. 
resourceConfig.registerResources(resourceBuilder.build());

下表说明了在上述示例中配置的应用程序支持的请求和提供的响应。RequestResponseMethod调用了“GET/hello”“hello!”你好。sayHello()“GET/hello2”“你好!”你好。sayHello()“GET/hello2/world”“你好,world!”拐点。应用()

代码示例

代码示例来源:origin: jersey/jersey

private Resource processResource(Resource resource) {
  Resource.Builder resourceBuilder = Resource.builder(resource.getPath());
  for (ResourceMethod resourceMethod : resource.getResourceMethods()) {
    ResourceMethod.Builder builder = resourceBuilder.addMethod(resourceMethod);
    if (resourceMethod.getInvocable().getHandlingMethod().isAnnotationPresent(Template.class)) {
      builder.routingResponseType(Viewable.class);
    }
  }
  if (resource.getResourceLocator() != null) {
    resourceBuilder.addMethod(resource.getResourceLocator());
  }
  for (Resource child : resource.getChildResources()) {
    resourceBuilder.addChildResource(processResource(child));
  }
  return resourceBuilder.build();
}

代码示例来源:origin: jersey/jersey

@Override
  public ResourceModel processSubResource(ResourceModel subResource, Configuration configuration) {
    final Resource resource = Resource.builder()
        .mergeWith(Resource.from(EnhancedSubResourceSingleton.class))
        .mergeWith(Resource.from(EnhancedSubResource.class))
        .mergeWith(subResource.getResources().get(0)).build();
    return new ResourceModel.Builder(true).addResource(resource).build();
  }
}

代码示例来源:origin: Graylog2/graylog2-server

@Override
public ResourceModel processResourceModel(ResourceModel model, Configuration config) {
  // Create new resource model.
  final ResourceModel.Builder resourceModelBuilder = new ResourceModel.Builder(false);
  for (final Resource resource : model.getResources()) {
    for (Class handlerClass : resource.getHandlerClasses()) {
      final String packageName = handlerClass.getPackage().getName();
      final Optional<String> packagePrefix = packagePrefixes.entrySet().stream()
          .filter(entry -> packageName.startsWith(entry.getKey()))
          .sorted((o1, o2) -> -o1.getKey().compareTo(o2.getKey()))
          .map(Map.Entry::getValue)
          .findFirst();
      if (packagePrefix.isPresent()) {
        final String prefixedPath = prefixPath(packagePrefix.get(), resource.getPath());
        final Resource newResource = Resource.builder(resource)
            .path(prefixedPath)
            .build();
        resourceModelBuilder.addResource(newResource);
      } else {
        resourceModelBuilder.addResource(resource);
      }
    }
  }
  return resourceModelBuilder.build();
}

代码示例来源:origin: Graylog2/graylog2-server

public static String getPathFromResource(Resource resource) {
    String path = resource.getPath();
    Resource parent = resource.getParent();

    while (parent != null) {
      if (!path.startsWith("/")) {
        path = "/" + path;
      }

      path = parent.getPath() + path;
      parent = parent.getParent();
    }

    return path;

  }
}

代码示例来源:origin: jersey/jersey

@Override
  public List<? extends ResourceModelComponent> getComponents() {
    List<ResourceModelComponent> components = new LinkedList<>();

    components.addAll(getChildResources());
    components.addAll(getResourceMethods());

    final ResourceMethod resourceLocator = getResourceLocator();
    if (resourceLocator != null) {
      components.add(resourceLocator);
    }
    return components;
  }
}

代码示例来源:origin: jersey/jersey

/**
 * Provides resource methods and resource locator are available on the resource. The list is ordered so that resource
 * methods are positioned first before resource locator.
 *
 * @return List of resource methods and resource locator.
 */
public List<ResourceMethod> getAllMethods() {
  final LinkedList<ResourceMethod> methodsAndLocators = new LinkedList<>(getResourceMethods());
  final ResourceMethod loc = getResourceLocator();
  if (loc != null) {
    methodsAndLocators.add(loc);
  }
  return methodsAndLocators;
}

代码示例来源:origin: jersey/jersey

try {
  if (!detailedWadl && resource.isExtended()) {
    return null;
  final ResourceMethod locator = resource.getResourceLocator();
  if (locator != null) {
    try {
      org.glassfish.jersey.server.model.Resource.Builder builder = org.glassfish.jersey.server.model.Resource
          .builder(locator.getInvocable().getRawResponseType());
      if (builder == null) {
        builder = org.glassfish.jersey.server.model.Resource.builder().path(resource.getPath());
      org.glassfish.jersey.server.model.Resource subResource = builder.build();
      Resource wadlSubResource = generateResource(subResource, resource.getPath(), visitedResources);
      if (wadlSubResource == null) {
        return null;
  for (org.glassfish.jersey.server.model.ResourceMethod method : resource.getResourceMethods()) {
    if (!detailedWadl && method.isExtended()) {
      continue;
  for (org.glassfish.jersey.server.model.Resource childResource : resource.getChildResources()) {
    Resource childWadlResource = generateResource(childResource, childResource.getPath(),
        visitedResources);
    if (childWadlResource == null) {

代码示例来源:origin: org.codehaus.fabric3/fabric3-binding-rs-jersey

private Resource createResource(F3ResourceHandler handler) {
  Resource template = Resource.from(handler.getInterface());
  Resource.Builder resourceBuilder = Resource.builder(template.getPath());
  for (ResourceMethod resourceMethod : template.getAllMethods()) {
    createMethod(resourceBuilder, resourceMethod, handler);
  }
  for (Resource childTemplate : template.getChildResources()) {
    Resource.Builder childResourceBuilder = Resource.builder(childTemplate.getPath());
    for (ResourceMethod resourceMethod : childTemplate.getAllMethods()) {
      createMethod(childResourceBuilder, resourceMethod, handler);
    }
    resourceBuilder.addChildResource(childResourceBuilder.build());
  }
  return resourceBuilder.build();
}

代码示例来源:origin: jersey/jersey

final Class<?> handlerClass = resourceMethod.getInvocable().getHandler().getHandlerClass();
final Class<?>[] paramTypes = resourceMethod.getInvocable().getHandlingMethod().getParameterTypes();
this.name = resourceMethod.getInvocable().getHandlingMethod().getName();
StringBuilder params = new StringBuilder();
for (Class<?> type : paramTypes) {
  path = "N/A";
} else {
  path = resourceMethod.getParent().getParent() == null ? "" : resourceMethod.getParent().getPath();

代码示例来源:origin: dropwizard/dropwizard

private List<EndpointLogLine> logMethodLines(Resource resource, String contextPath) {
  final List<EndpointLogLine> methodLines = new ArrayList<>();
  for (ResourceMethod method : resource.getAllMethods()) {
    if ("OPTIONS".equalsIgnoreCase(method.getHttpMethod())) {
      continue;
    final String path = cleanUpPath(contextPath + Strings.nullToEmpty(resource.getPath()));
    final Class<?> handler = method.getInvocable().getHandler().getHandlerClass();
    switch (method.getType()) {
      case RESOURCE_METHOD:
        methodLines.add(new EndpointLogLine(method.getHttpMethod(), path, handler));
            responseType.getErasedType();
        final Resource res = Resource.from(erasedType);
        if (res == null) {
          methodLines.add(new EndpointLogLine(method.getHttpMethod(), path, handler));

代码示例来源:origin: jersey/jersey

@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);
}

代码示例来源:origin: jersey/jersey

/**
 * Create a resource model builder initialized by introspecting an annotated
 * JAX-RS resource class.
 *
 * @param resourceClass resource class to be modelled.
 * @return resource model builder initialized by the class or {@code null} if the
 * class does not represent a resource.
 */
public static Builder builder(Class<?> resourceClass) {
  return builder(resourceClass, false);
}

代码示例来源:origin: Graylog2/graylog2-server

private <T> Set<Resource> prefixResources(String prefix, Set<Class<? extends T>> resources) {
  final String pathPrefix = prefix.endsWith("/") ? prefix.substring(0, prefix.length() - 1) : prefix;
  return resources
      .stream()
      .map(resource -> {
        final javax.ws.rs.Path pathAnnotation = Resource.getPath(resource);
        final String resourcePathSuffix = Strings.nullToEmpty(pathAnnotation.value());
        final String resourcePath = resourcePathSuffix.startsWith("/") ? pathPrefix + resourcePathSuffix : pathPrefix + "/" + resourcePathSuffix;
        return Resource
            .builder(resource)
            .path(resourcePath)
            .build();
      })
      .collect(Collectors.toSet());
}

代码示例来源:origin: Graylog2/graylog2-server

private void checkResources(List<Resource> resources) {
    for (ResourceMethod method : resource.getResourceMethods()) {
      final Method m = method.getInvocable().getDefinitionMethod();
          LOG.warn("REST endpoint not included in audit trail: {}", String.format(Locale.US, "%6s %s", method.getHttpMethod(), getPathFromResource(resource)));
          LOG.debug("Missing @AuditEvent or @NoAuditEvent annotation: {}#{}", m.getDeclaringClass().getCanonicalName(), m.getName());
        } else {
                  String.format(Locale.US, "%6s %s", method.getHttpMethod(), getPathFromResource(resource)), annotation.type());
              LOG.debug("Make sure the audit event types are registered in a class that implements PluginAuditEventTypes: {}#{}",
                  m.getDeclaringClass().getCanonicalName(), m.getName());
    checkResources(resource.getChildResources());

代码示例来源:origin: com.thesett.jenerator.utils/jenerator_util_dropwizard_0.9

public void onEvent(ApplicationEvent event) {
  if (event.getType() == ApplicationEvent.Type.INITIALIZATION_APP_FINISHED) {
    for (Resource resource : event.getResourceModel().getResources()) {
      for (ResourceMethod method : resource.getAllMethods()) {
        registerUnitOfWorkWithDetachAnnotations(method);
      }
      for (Resource childResource : resource.getChildResources()) {
        for (ResourceMethod method : childResource.getAllMethods()) {
          registerUnitOfWorkWithDetachAnnotations(method);
        }
      }
    }
  }
}

代码示例来源:origin: jersey/jersey

private void checkResource(final Resource resource) {
  if (!resource.getResourceMethods().isEmpty() && resource.getResourceLocator() != null) {
    Errors.warning(resource, LocalizationMessages.RESOURCE_CONTAINS_RES_METHODS_AND_LOCATOR(resource,
        resource.getPath()));
  }
  if (resource.getPath() != null
      && resource.getResourceMethods().isEmpty()
      && resource.getChildResources().isEmpty()
      && resource.getResourceLocator() == null) {
    Errors.warning(resource, LocalizationMessages.RESOURCE_EMPTY(resource, resource.getPath()));
  }
}

代码示例来源:origin: jersey/jersey

/**
 * Create a new builder and initialize it from resource model.
 *
 * @param resourceModel resource model.
 */
Builder(final ResourceModel resourceModel) {
  this();
  for (final Resource resource : resourceModel.getRootResources()) {
    processResource(resource, "");
    for (final Resource child : resource.getChildResources()) {
      final String path = resource.getPath();
      processResource(child, path.startsWith("/") ? path : "/" + path);
    }
  }
}

代码示例来源:origin: org.glassfish.ozark/ozark

/**
 * 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();
}

代码示例来源:origin: jersey/jersey

final String path = resource.getPath();
  if (path == null && !subResourceModel) {
    separateResources.add(resource);
      resourceMap.put(path, resource);
    } else {
      resourceMap.put(path, Resource.builder(fromMap).mergeWith(resource).build());
return new ResourceModel(rootResources, allResources);

代码示例来源:origin: org.graylog2/graylog2-shared

private void logResources(List<Resource> resources) {
  final List<ResourceDescription> resourceDescriptions = new ArrayList<>();
  for (Resource resource : resources) {
    for (ResourceMethod resourceMethod : resource.getAllMethods()) {
      String path = resource.getPath();
      Resource parent = resource.getParent();
      while (parent != null) {
        if (!path.startsWith("/")) {
          path = "/" + path;
        }
        path = parent.getPath() + path;
        parent = parent.getParent();
      }
      resourceDescriptions.add(new ResourceDescription(resourceMethod.getHttpMethod(), path, resource.getHandlerClasses()));
    }
  }
  Collections.sort(resourceDescriptions);
  for (ResourceDescription resource : resourceDescriptions) {
    LOG.debug(resource.toString());
  }
}

相关文章