Ejemplo n.º 1
0
  /**
   * Indicates the number of params of the Kind specified
   *
   * @param params
   * @param KIND kind of parameter eg. URL_PATH
   * @return int count
   */
  private static int paramsCount(List<ResourceParameter> params, KIND kind) {
    int numParams = 0;

    for (ResourceParameter resourceParameter : params) {
      if (kind.equals(resourceParameter.getParamType())) numParams++;
    }
    return numParams; // the default
  }
Ejemplo n.º 2
0
  /**
   * The resource parameters for a root resource include the constructor params.
   *
   * @param delegate The declaration.
   * @return The resource params.
   */
  @Override
  protected List<ResourceParameter> getResourceParameters(TypeDeclaration delegate) {
    List<ResourceParameter> resourceParams = super.getResourceParameters(delegate);

    if (getDelegate() == delegate && delegate instanceof ClassDeclaration) {
      // root resources also include constructor params.

      Collection<ConstructorDeclaration> constructors =
          ((ClassDeclaration) delegate).getConstructors();
      ConstructorDeclaration chosen = null;
      CONSTRUCTOR_LOOP:
      for (ConstructorDeclaration constructor : constructors) {
        // the one with the most params is the chosen one.
        if (chosen == null || constructor.getParameters().size() > chosen.getParameters().size()) {
          // Has more constructor parameters.  See if they're all Jersey-provided.
          for (ParameterDeclaration param : constructor.getParameters()) {
            if (!ResourceParameter.isResourceParameter(param)) {
              continue CONSTRUCTOR_LOOP;
            }
          }
          chosen = constructor;
        }
      }

      if (chosen != null) {
        chosen = DeclarationDecorator.decorate(chosen);
        for (ParameterDeclaration param : chosen.getParameters()) {
          resourceParams.add(new ResourceParameter(param));
        }
      }
    }

    return resourceParams;
  }
Ejemplo n.º 3
0
 /**
  * @param paramAnot
  * @return
  */
 private static ResourceParameter findResourceParameter(
     Annotation paramAnot, Class<?> resource, Method aMethod) {
   Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(paramAnot);
   ResourceParameter.KIND paramKind = (ResourceParameter.KIND) annotAttribs.get("kind");
   Class<?> dType = String.class;
   if (ResourceParameter.KIND.HTTP_BODY_OBJECT.equals(paramKind)) {
     dType = ResourceInspectorUtil.determineType(resource, aMethod);
   }
   return ResourceParameter.valueOf(
       String.valueOf(annotAttribs.get("name")),
       String.valueOf(annotAttribs.get("title")),
       String.valueOf(annotAttribs.get("description")),
       (Boolean) annotAttribs.get("required"),
       paramKind,
       (Boolean) annotAttribs.get("allowMultiple"),
       dType);
 }
Ejemplo n.º 4
0
  public ResourceMethod(MethodDeclaration delegate, Resource parent) {
    super(delegate);

    Set<String> httpMethods = new TreeSet<String>();
    Collection<AnnotationMirror> mirrors = delegate.getAnnotationMirrors();
    for (AnnotationMirror mirror : mirrors) {
      AnnotationTypeDeclaration annotationDeclaration = mirror.getAnnotationType().getDeclaration();
      HttpMethod httpMethodInfo = annotationDeclaration.getAnnotation(HttpMethod.class);
      if (httpMethodInfo != null) {
        // request method designator found.
        httpMethods.add(httpMethodInfo.value());
      }
    }

    if (httpMethods.isEmpty()) {
      throw new IllegalStateException(
          "A resource method must specify an HTTP method by using a request method designator annotation.");
    }

    this.httpMethods = httpMethods;

    Set<String> consumes;
    Consumes consumesInfo = delegate.getAnnotation(Consumes.class);
    if (consumesInfo != null) {
      consumes = new TreeSet<String>(Arrays.asList(JAXRSUtils.value(consumesInfo)));
    } else {
      consumes = new TreeSet<String>(parent.getConsumesMime());
    }
    this.consumesMime = consumes;

    Set<String> produces;
    Produces producesInfo = delegate.getAnnotation(Produces.class);
    if (producesInfo != null) {
      produces = new TreeSet<String>(Arrays.asList(JAXRSUtils.value(producesInfo)));
    } else {
      produces = new TreeSet<String>(parent.getProducesMime());
    }
    this.producesMime = produces;

    String subpath = null;
    Path pathInfo = delegate.getAnnotation(Path.class);
    if (pathInfo != null) {
      subpath = pathInfo.value();
    }

    ResourceEntityParameter entityParameter;
    List<ResourceEntityParameter> declaredEntityParameters =
        new ArrayList<ResourceEntityParameter>();
    List<ResourceParameter> resourceParameters;
    ResourceRepresentationMetadata outputPayload;
    ResourceMethodSignature signatureOverride =
        delegate.getAnnotation(ResourceMethodSignature.class);
    if (signatureOverride == null) {
      entityParameter = null;
      resourceParameters = new ArrayList<ResourceParameter>();
      // if we're not overriding the signature, assume we use the real method signature.
      for (ParameterDeclaration parameterDeclaration : getParameters()) {
        if (ResourceParameter.isResourceParameter(parameterDeclaration)) {
          resourceParameters.add(new ResourceParameter(parameterDeclaration));
        } else if (ResourceParameter.isFormBeanParameter(parameterDeclaration)) {
          resourceParameters.addAll(ResourceParameter.getFormBeanParameters(parameterDeclaration));
        } else if (parameterDeclaration.getAnnotation(Context.class) == null) {
          entityParameter = new ResourceEntityParameter(this, parameterDeclaration);
          declaredEntityParameters.add(entityParameter);
        }
      }

      DecoratedTypeMirror returnTypeMirror;
      TypeHint hintInfo = getAnnotation(TypeHint.class);
      if (hintInfo != null) {
        try {
          Class hint = hintInfo.value();
          AnnotationProcessorEnvironment env = net.sf.jelly.apt.Context.getCurrentEnvironment();
          if (TypeHint.NO_CONTENT.class.equals(hint)) {
            returnTypeMirror =
                (DecoratedTypeMirror)
                    TypeMirrorDecorator.decorate(env.getTypeUtils().getVoidType());
          } else {
            String hintName = hint.getName();

            if (TypeHint.NONE.class.equals(hint)) {
              hintName = hintInfo.qualifiedName();
            }

            if (!"##NONE".equals(hintName)) {
              TypeDeclaration type = env.getTypeDeclaration(hintName);
              returnTypeMirror =
                  (DecoratedTypeMirror)
                      TypeMirrorDecorator.decorate(env.getTypeUtils().getDeclaredType(type));
            } else {
              returnTypeMirror = (DecoratedTypeMirror) getReturnType();
            }
          }
        } catch (MirroredTypeException e) {
          returnTypeMirror = (DecoratedTypeMirror) TypeMirrorDecorator.decorate(e.getTypeMirror());
        }
        returnTypeMirror.setDocComment(((DecoratedTypeMirror) getReturnType()).getDocComment());
      } else {
        returnTypeMirror = (DecoratedTypeMirror) getReturnType();

        if (getJavaDoc().get("returnWrapped")
            != null) { // support jax-doclets. see http://jira.codehaus.org/browse/ENUNCIATE-690
          String fqn = getJavaDoc().get("returnWrapped").get(0);
          AnnotationProcessorEnvironment env = net.sf.jelly.apt.Context.getCurrentEnvironment();
          TypeDeclaration type = env.getTypeDeclaration(fqn);
          if (type != null) {
            returnTypeMirror =
                (DecoratedTypeMirror)
                    TypeMirrorDecorator.decorate(env.getTypeUtils().getDeclaredType(type));
          }
        }

        // in the case where the return type is com.sun.jersey.api.JResponse,
        // we can use the type argument to get the entity type
        if (returnTypeMirror.isClass()
            && returnTypeMirror.isInstanceOf("com.sun.jersey.api.JResponse")) {
          DecoratedClassType jresponse = (DecoratedClassType) returnTypeMirror;
          if (!jresponse.getActualTypeArguments().isEmpty()) {
            DecoratedTypeMirror responseType =
                (DecoratedTypeMirror)
                    TypeMirrorDecorator.decorate(
                        jresponse.getActualTypeArguments().iterator().next());
            if (responseType.isDeclared()) {
              responseType.setDocComment(returnTypeMirror.getDocComment());
              returnTypeMirror = responseType;
            }
          }
        }
      }

      outputPayload =
          returnTypeMirror.isVoid() ? null : new ResourceRepresentationMetadata(returnTypeMirror);
    } else {
      entityParameter = loadEntityParameter(signatureOverride);
      declaredEntityParameters.add(entityParameter);
      resourceParameters = loadResourceParameters(signatureOverride);
      outputPayload = loadOutputPayload(signatureOverride);
    }

    JavaDoc.JavaDocTagList doclets =
        getJavaDoc()
            .get(
                "RequestHeader"); // support jax-doclets. see
                                  // http://jira.codehaus.org/browse/ENUNCIATE-690
    if (doclets != null) {
      for (String doclet : doclets) {
        int firstspace = doclet.indexOf(' ');
        String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet;
        String doc =
            ((firstspace > 0) && (firstspace + 1 < doclet.length()))
                ? doclet.substring(firstspace + 1)
                : "";
        resourceParameters.add(
            new ExplicitResourceParameter(this, doc, header, ResourceParameterType.HEADER));
      }
    }

    ArrayList<ResponseCode> statusCodes = new ArrayList<ResponseCode>();
    ArrayList<ResponseCode> warnings = new ArrayList<ResponseCode>();
    StatusCodes codes = getAnnotation(StatusCodes.class);
    if (codes != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : codes.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        statusCodes.add(rc);
      }
    }

    doclets =
        getJavaDoc()
            .get("HTTP"); // support jax-doclets. see http://jira.codehaus.org/browse/ENUNCIATE-690
    if (doclets != null) {
      for (String doclet : doclets) {
        int firstspace = doclet.indexOf(' ');
        String code = firstspace > 0 ? doclet.substring(0, firstspace) : doclet;
        String doc =
            ((firstspace > 0) && (firstspace + 1 < doclet.length()))
                ? doclet.substring(firstspace + 1)
                : "";
        try {
          ResponseCode rc = new ResponseCode();
          rc.setCode(Integer.parseInt(code));
          rc.setCondition(doc);
          statusCodes.add(rc);
        } catch (NumberFormatException e) {
          // fall through...
        }
      }
    }

    Warnings warningInfo = getAnnotation(Warnings.class);
    if (warningInfo != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : warningInfo.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        warnings.add(rc);
      }
    }

    codes = parent.getAnnotation(StatusCodes.class);
    if (codes != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : codes.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        statusCodes.add(rc);
      }
    }

    warningInfo = parent.getAnnotation(Warnings.class);
    if (warningInfo != null) {
      for (org.codehaus.enunciate.jaxrs.ResponseCode code : warningInfo.value()) {
        ResponseCode rc = new ResponseCode();
        rc.setCode(code.code());
        rc.setCondition(code.condition());
        warnings.add(rc);
      }
    }

    ResponseHeaders responseHeaders = parent.getAnnotation(ResponseHeaders.class);
    if (responseHeaders != null) {
      for (ResponseHeader header : responseHeaders.value()) {
        this.responseHeaders.put(header.name(), header.description());
      }
    }

    responseHeaders = getAnnotation(ResponseHeaders.class);
    if (responseHeaders != null) {
      for (ResponseHeader header : responseHeaders.value()) {
        this.responseHeaders.put(header.name(), header.description());
      }
    }

    doclets =
        getJavaDoc()
            .get(
                "ResponseHeader"); // support jax-doclets. see
                                   // http://jira.codehaus.org/browse/ENUNCIATE-690
    if (doclets != null) {
      for (String doclet : doclets) {
        int firstspace = doclet.indexOf(' ');
        String header = firstspace > 0 ? doclet.substring(0, firstspace) : doclet;
        String doc =
            ((firstspace > 0) && (firstspace + 1 < doclet.length()))
                ? doclet.substring(firstspace + 1)
                : "";
        this.responseHeaders.put(header, doc);
      }
    }

    this.entityParameter = entityParameter;
    this.resourceParameters = resourceParameters;
    this.subpath = subpath;
    this.parent = parent;
    this.statusCodes = statusCodes;
    this.warnings = warnings;
    this.representationMetadata = outputPayload;
    this.declaredEntityParameters = declaredEntityParameters;
  }
Ejemplo n.º 5
0
  /**
   * Inspects the Method to find any @WebApiParameters and @WebApiParam
   *
   * @param resource the class
   * @param aMethod the method
   * @param httpMethod
   * @return a List of parameters
   */
  private static List<ResourceParameter> inspectParameters(
      Class<?> resource, Method aMethod, HttpMethod httpMethod) {
    List<ResourceParameter> params = new ArrayList<ResourceParameter>();
    Annotation annot = AnnotationUtils.findAnnotation(aMethod, WebApiParameters.class);
    if (annot != null) {
      Map<String, Object> annotAttribs = AnnotationUtils.getAnnotationAttributes(annot);
      WebApiParam[] apiParams = (WebApiParam[]) annotAttribs.get("value");
      for (int i = 0; i < apiParams.length; i++) {
        params.add(findResourceParameter(apiParams[i], resource, aMethod));
      }
    } else {
      Annotation paramAnot = AnnotationUtils.findAnnotation(aMethod, WebApiParam.class);
      if (paramAnot != null) {
        params.add(findResourceParameter(paramAnot, resource, aMethod));
      }
    }

    // Setup default parameters
    switch (httpMethod) {
      case POST:
        if (paramsCount(params, ResourceParameter.KIND.URL_PATH) == 0) {
          params.add(ResourceParameter.ENTITY_PARAM);
        }
        if (paramsCount(params, ResourceParameter.KIND.HTTP_BODY_OBJECT) == 0) {
          Class<?> dType = ResourceInspectorUtil.determineType(resource, aMethod);
          params.add(
              ResourceParameter.valueOf(
                  dType.getSimpleName().toUpperCase(),
                  "The entity",
                  "Unique entity properties",
                  true,
                  ResourceParameter.KIND.HTTP_BODY_OBJECT,
                  true,
                  dType));
        }
        break;
      case PUT:
        int urlPathForPut = paramsCount(params, ResourceParameter.KIND.URL_PATH);
        if (urlPathForPut == 0) {
          params.add(ResourceParameter.ENTITY_PARAM);
        }
        if (RelationshipResourceAction.Update.class.isAssignableFrom(resource)
            && urlPathForPut < 2) {
          params.add(ResourceParameter.RELATIONSHIP_PARAM);
        }
        if (paramsCount(params, ResourceParameter.KIND.HTTP_BODY_OBJECT) == 0) {
          Class<?> dType = ResourceInspectorUtil.determineType(resource, aMethod);
          params.add(
              ResourceParameter.valueOf(
                  dType.getSimpleName().toUpperCase(),
                  "The entity",
                  "Unique entity properties",
                  true,
                  ResourceParameter.KIND.HTTP_BODY_OBJECT,
                  true,
                  dType));
        }
        break;
      case GET:
        int urlPathForGet = paramsCount(params, ResourceParameter.KIND.URL_PATH);
        if (urlPathForGet == 0
            && (EntityResourceAction.ReadById.class.isAssignableFrom(resource)
                && READ_BY_ID_METHODNAME.equals(aMethod.getName()))) {
          params.add(ResourceParameter.ENTITY_PARAM);
        } else if (RelationshipResourceAction.ReadById.class.isAssignableFrom(resource)
            || RelationshipResourceAction.Read.class.isAssignableFrom(resource)) {
          // Its a RelationshipResourceAction
          if (urlPathForGet == 0) {
            params.add(ResourceParameter.ENTITY_PARAM);
          }
          // This method is what we are inspecting not what the class implements.
          if (READ_BY_ID_METHODNAME.equals(aMethod.getName()) && urlPathForGet < 2) {
            params.add(ResourceParameter.RELATIONSHIP_PARAM);
          }
        }
        if (!READ_BY_ID_METHODNAME.equals(aMethod.getName())) {
          params.add(ResourceParameter.SKIP_PARAM);
          params.add(ResourceParameter.MAX_ITEMS_PARAM);
          params.add(ResourceParameter.PROPS_PARAM);
        }
        break;
      case DELETE:
        int urlPathForDelete = paramsCount(params, ResourceParameter.KIND.URL_PATH);
        if (urlPathForDelete == 0) {
          params.add(ResourceParameter.ENTITY_PARAM);
        }
        // Add relationship param ?
        if (RelationshipResourceAction.Delete.class.isAssignableFrom(resource)
            && urlPathForDelete < 2) {
          params.add(ResourceParameter.RELATIONSHIP_PARAM);
        }
    }

    return params;
  }