public static void generateNativeMethodStubs(
     AnnotationProcessorEnvironment env,
     TypeMap type_map,
     PrintWriter writer,
     InterfaceDeclaration d,
     boolean generate_error_checks,
     boolean context_specific) {
   for (MethodDeclaration method : d.getMethods()) {
     Alternate alt_annotation = method.getAnnotation(Alternate.class);
     if (alt_annotation != null && !alt_annotation.nativeAlt()) continue;
     generateMethodStub(
         env,
         type_map,
         writer,
         Utils.getQualifiedClassName(d),
         method,
         Mode.NORMAL,
         generate_error_checks,
         context_specific);
     if (Utils.hasMethodBufferObjectParameter(method))
       generateMethodStub(
           env,
           type_map,
           writer,
           Utils.getQualifiedClassName(d),
           method,
           Mode.BUFFEROBJECT,
           generate_error_checks,
           context_specific);
   }
 }
 public void process() {
   for (TypeDeclaration typeDecl : env.getSpecifiedTypeDeclarations()) {
     ExtractInterface annot = typeDecl.getAnnotation(ExtractInterface.class);
     if (annot == null) break;
     for (MethodDeclaration m : typeDecl.getMethods())
       if (m.getModifiers().contains(Modifier.PUBLIC)
           && !(m.getModifiers().contains(Modifier.STATIC))) interfaceMethods.add(m);
     if (interfaceMethods.size() > 0) {
       try {
         PrintWriter writer = env.getFiler().createSourceFile(annot.value());
         writer.println("package " + typeDecl.getPackage().getQualifiedName() + ";");
         writer.println("public interface " + annot.value() + " {");
         for (MethodDeclaration m : interfaceMethods) {
           writer.print("  public ");
           writer.print(m.getReturnType() + " ");
           writer.print(m.getSimpleName() + " (");
           int i = 0;
           for (ParameterDeclaration parm : m.getParameters()) {
             writer.print(parm.getType() + " " + parm.getSimpleName());
             if (++i < m.getParameters().size()) writer.print(", ");
           }
           writer.println(");");
         }
         writer.println("}");
         writer.close();
       } catch (IOException ioe) {
         throw new RuntimeException(ioe);
       }
     }
   }
 }
 public static boolean checkReturnType(
     AnnotationMirror mirror, MethodDeclaration methodDeclaration, EclipseMessager messager) {
   TypeMirror returnType = methodDeclaration.getReturnType();
   String returnTypeName = returnType.toString();
   if (!(returnTypeName.startsWith("java.util.List")
       || returnTypeName.startsWith("java.util.Collection"))) {
     messager.printFixableError(
         methodDeclaration.getPosition(),
         "Method should return java.util.List or java.util.Collection",
         PLUGIN_ID,
         ERROR_wrong_return_type);
     return false;
   }
   return true;
 }
 private boolean checkInheritedMethod(
     Thing data,
     String methodName,
     String returnType,
     ClassDeclaration superclass,
     boolean finalOk,
     InheritCheck inheritCheck) {
   if (inheritCheck != null) {
     if (inheritCheck.isInherited(data, superclass)) {
       return true;
     }
   }
   for (MethodDeclaration methodDeclaration : superclass.getMethods()) {
     if (methodName.equals(methodDeclaration.getSimpleName())
         && methodDeclaration.getParameters().isEmpty()
         && returnType.equals(methodDeclaration.getReturnType().toString())) {
       data.put(methodName + "Inherited", true);
       Collection<Modifier> modifiers = methodDeclaration.getModifiers();
       if ((modifiers.contains(Modifier.FINAL) || modifiers.contains(Modifier.PRIVATE))
           && !finalOk) {
         // TBD TBD TBD - ERROR!!! cannot extend class with superclass method like this - how to
         // report?
       } else if (modifiers.contains(Modifier.PROTECTED)) {
         data.put(methodName + "Modifiers", "protected");
       } else if (modifiers.contains(Modifier.PUBLIC)) {
         data.put(methodName + "Modifiers", "public");
       } else {
         data.put(methodName + "Modifiers", "");
       }
       return true;
     }
   }
   if (superclass.getSuperclass() != null) {
     if (superclass.getSuperclass().getDeclaration() != null) {
       if (checkInheritedMethod(
           data,
           methodName,
           returnType,
           superclass.getSuperclass().getDeclaration(),
           finalOk,
           inheritCheck)) {
         return true;
       }
     }
   }
   return false;
 }
 private static void generateBufferParameterAddresses(
     TypeMap type_map, PrintWriter writer, MethodDeclaration method, Mode mode) {
   boolean loopDeclared = false;
   for (ParameterDeclaration param : method.getParameters())
     if (Utils.isAddressableType(param.getType()) && param.getAnnotation(Result.class) == null)
       loopDeclared =
           generateBufferParameterAddress(type_map, writer, method, param, mode, loopDeclared);
 }
 //	private void defineListenerOrDelegate(boolean abstractOnly, Thing type, Declaration
 // declaration, String typeOfThing, String partOfBean, String packageName) {
 //		TypeDeclaration typeDeclaration = getType(declaration, (String) type.get("name"), packageName,
 // "Cannot find " + typeOfThing + " " + type.get("name") + " defined as an " + partOfBean + " in
 // @Bean (you probably need to fully-qualify it)");
 //		if (typeDeclaration == null) {
 //			return;
 //		}
 //		Collection<? extends MethodDeclaration> methods = typeDeclaration.getMethods();
 //		for (MethodDeclaration methodDeclaration : methods) {
 //			if (methodDeclaration.getModifiers().contains(Modifier.STATIC)) {
 //				continue;
 //			}
 //			if (abstractOnly) {
 //				if (!methodDeclaration.getModifiers().contains(Modifier.ABSTRACT)) {
 //					continue;
 //				}
 //			} else {
 //				if (!methodDeclaration.getModifiers().contains(Modifier.PUBLIC)) {
 //					continue;
 //				}
 //			}
 //			if (BeanAnnotationProcessor.METHODS_TO_SKIP.contains(methodDeclaration.getSimpleName())) {
 //				continue;
 //			}
 //
 //			type.add("methods", setupMethod(methodDeclaration, true));
 //		}
 //	}
 //
 private String getThrowsClause(MethodDeclaration methodDeclaration) {
   Collection<ReferenceType> thrownTypes = methodDeclaration.getThrownTypes();
   boolean first = true;
   if (!thrownTypes.isEmpty()) {
     String throwsClause = " throws ";
     for (ReferenceType thrownType : thrownTypes) {
       if (first) {
         first = false;
       } else {
         throwsClause += ", ";
       }
       throwsClause += Utils.getTypeName(thrownType);
     }
     return throwsClause;
   } else {
     return "";
   }
 }
  public static boolean checkTransferInfo(
      AnnotationMirror mirror,
      MethodDeclaration methodDeclaration,
      boolean checkReturnType,
      EclipseMessager messager) {
    Map<AnnotationTypeElementDeclaration, AnnotationValue> valueMap = mirror.getElementValues();
    Set<Map.Entry<AnnotationTypeElementDeclaration, AnnotationValue>> valueSet =
        valueMap.entrySet();

    boolean found = false;
    for (Map.Entry<AnnotationTypeElementDeclaration, AnnotationValue> annoKeyValue : valueSet) {
      if (annoKeyValue.getKey().getSimpleName().equals("transferInfo")) {
        found = true;
        checkTransferInfoType(annoKeyValue.getValue(), messager);
        checkIfAnnotationValueAttributeIsEntity(
            (AnnotationMirror) annoKeyValue.getValue().getValue(), "mappedBy", messager);
        break;
      }
    }
    if (!found && checkReturnType) {
      TypeMirror returnType = methodDeclaration.getReturnType();
      String returnTypeName = returnType.toString();
      if (returnTypeName.equals("java.util.List<?>")
          || returnTypeName.equals("java.util.List")
          || returnTypeName.equals("java.util.Collection<?>")
          || returnTypeName.equals("java.util.Collection")) {
        // System.out.println(returnType);
        SourcePosition pos = mirror.getPosition();
        messager.printFixableError(
            pos,
            CLASS_OF_THE_COLLECTION_ELEMENTS_IS_NOT_SPECIFIED_AND_TRANSFER_INFO_PARAMETER_IS_MISSING,
            PLUGIN_ID,
            ERROR_transferInfo_is_missing);
        return false;
      }
    }
    return true;
  }
  private static boolean generateBufferParameterAddress(
      TypeMap type_map,
      PrintWriter writer,
      MethodDeclaration method,
      ParameterDeclaration param,
      Mode mode,
      boolean loopDeclared) {
    NativeTypeTranslator translator = new NativeTypeTranslator(type_map, param);
    param.getType().accept(translator);
    writer.print("\t" + translator.getSignature() + param.getSimpleName());
    writer.print(BUFFER_ADDRESS_POSTFIX + " = ((");
    writer.print(translator.getSignature());
    Check check_annotation = param.getAnnotation(Check.class);
    writer.print(")");
    if (mode == Mode.BUFFEROBJECT && param.getAnnotation(BufferObject.class) != null) {
      writer.print(
          "offsetToPointer("
              + param.getSimpleName()
              + Utils.BUFFER_OBJECT_PARAMETER_POSTFIX
              + "))");
    } else {
      Class java_type = Utils.getJavaType(param.getType());
      if (Buffer.class.isAssignableFrom(java_type)
          || java_type.equals(CharSequence.class)
          || java_type.equals(CharSequence[].class)) {
        boolean explicitly_byte_sized =
            java_type.equals(Buffer.class)
                || translator.getAnnotationType().equals(type_map.getVoidType());
        if (explicitly_byte_sized) writer.print("(((char *)");
        if (method.getAnnotation(GenerateAutos.class) != null
            || (check_annotation != null && check_annotation.canBeNull())) {
          writer.print("safeGetBufferAddress(env, " + param.getSimpleName());
        } else {
          writer.print("(*env)->GetDirectBufferAddress(env, " + param.getSimpleName());
        }
        writer.print("))");
        writer.print(" + " + param.getSimpleName() + BUFFER_POSITION_POSTFIX);
        if (explicitly_byte_sized) writer.print("))");
      } else if (java_type.equals(String.class)) {
        writer.print("GetStringNativeChars(env, " + param.getSimpleName() + "))");
      } else throw new RuntimeException("Illegal type " + java_type);
    }
    writer.println(";");

    if (param.getAnnotation(StringList.class) != null) {
      if (Utils.getJavaType(param.getType()) != CharSequence[].class
          && (param.getAnnotation(GLchar.class) == null
              || param.getAnnotation(NullTerminated.class) == null
              || param.getAnnotation(NullTerminated.class).value().length() == 0))
        throw new RuntimeException(
            "StringList annotation can only be applied on null-terminated GLchar buffers.");

      if ("_str".equals(param.getSimpleName()))
        throw new RuntimeException(
            "The name '_str' is not valid for arguments annotated with StringList");

      // Declare loop counters and allocate string array
      if (!loopDeclared) {
        writer.println("\tunsigned int _str_i;");
        writer.println("\tGLchar *_str_address;");
        loopDeclared = true;
      }
      writer.println(
          "\tGLchar **"
              + param.getSimpleName()
              + STRING_LIST_POSTFIX
              + " = (GLchar **) malloc("
              + param.getAnnotation(StringList.class).value()
              + "*sizeof(GLchar*));");
    }
    return loopDeclared;
  }
  private static void generateMethodStub(
      AnnotationProcessorEnvironment env,
      TypeMap type_map,
      PrintWriter writer,
      String interface_name,
      MethodDeclaration method,
      Mode mode,
      boolean generate_error_checks,
      boolean context_specific) {
    if (!context_specific && method.getAnnotation(Alternate.class) == null) writer.print("static ");
    else writer.print("JNIEXPORT ");

    TypeMirror result_type = Utils.getMethodReturnType(method);

    if (method.getAnnotation(GLpointer.class) != null) {
      writer.print("jlong");
    } else {
      JNITypeTranslator translator = new JNITypeTranslator();
      result_type.accept(translator);
      writer.print(translator.getSignature());
    }
    writer.print(" JNICALL ");

    writer.print(
        Utils.getQualifiedNativeMethodName(
            interface_name, method, generate_error_checks, context_specific));
    if (mode == Mode.BUFFEROBJECT) writer.print(Utils.BUFFER_OBJECT_METHOD_POSTFIX);
    writer.print("(JNIEnv *env, jclass clazz");
    generateParameters(writer, method.getParameters(), mode);
    if (Utils.getNIOBufferType(result_type) != null) {
      CachedResult cached_result_annotation = method.getAnnotation(CachedResult.class);
      if (cached_result_annotation == null || !cached_result_annotation.isRange())
        writer.print(", jlong " + Utils.RESULT_SIZE_NAME);
      if (cached_result_annotation != null) writer.print(", jobject " + Utils.CACHED_BUFFER_NAME);
    }
    if (context_specific) {
      writer.print(", jlong " + Utils.FUNCTION_POINTER_VAR_NAME);
    }
    writer.println(") {");
    generateBufferParameterAddresses(type_map, writer, method, mode);
    Alternate alt_annotation = method.getAnnotation(Alternate.class);
    if (context_specific) {
      String typedef_name = Utils.getTypedefName(method);
      writer.print(
          "\t"
              + typedef_name
              + " "
              + (alt_annotation == null ? method.getSimpleName() : alt_annotation.value()));
      writer.print(" = (" + typedef_name + ")((intptr_t)");
      writer.println(Utils.FUNCTION_POINTER_VAR_NAME + ");");
    }
    generateStringListInits(writer, method.getParameters());
    writer.print("\t");
    if (!result_type.equals(env.getTypeUtils().getVoidType())) {
      Declaration return_declaration;
      ParameterDeclaration result_param = Utils.getResultParameter(method);
      if (result_param != null) return_declaration = result_param;
      else return_declaration = method;
      NativeTypeTranslator native_translator =
          new NativeTypeTranslator(type_map, return_declaration);
      result_type.accept(native_translator);
      writer.print(native_translator.getSignature() + " " + Utils.RESULT_VAR_NAME);
      if (result_param != null) {
        writer.println(";");
        writer.print("\t");
      } else writer.print(" = ");
    }
    writer.print((alt_annotation == null ? method.getSimpleName() : alt_annotation.value()) + "(");
    generateCallParameters(writer, type_map, method.getParameters());
    writer.print(")");
    writer.println(";");
    generateStringDeallocations(writer, method.getParameters());
    if (!result_type.equals(env.getTypeUtils().getVoidType())) {
      writer.print("\treturn ");
      Class java_result_type = Utils.getJavaType(result_type);
      if (Buffer.class.isAssignableFrom(java_result_type)) {
        if (method.getAnnotation(CachedResult.class) != null)
          writer.print("safeNewBufferCached(env, ");
        else writer.print("safeNewBuffer(env, ");
      } else if (String.class.equals(java_result_type)) {
        writer.print("NewStringNativeUnsigned(env, ");
      } else if (method.getAnnotation(GLpointer.class) != null) {
        writer.print("(intptr_t)");
      }
      writer.print(Utils.RESULT_VAR_NAME);
      if (Buffer.class.isAssignableFrom(java_result_type)) {
        writer.print(", ");
        if (method.getAnnotation(CachedResult.class) != null
            && method.getAnnotation(CachedResult.class).isRange())
          Utils.printExtraCallArguments(
              writer, method, method.getAnnotation(AutoResultSize.class).value());
        else Utils.printExtraCallArguments(writer, method, Utils.RESULT_SIZE_NAME);
      }
      if (Buffer.class.isAssignableFrom(java_result_type) || String.class.equals(java_result_type))
        writer.print(")");
      writer.println(";");
    }
    writer.println("}");
    writer.println();
  }
Exemplo n.º 10
0
  private void processDefaultMethods(Thing data, ClassDeclaration classDeclaration) {
    // find any methods that have default parameters
    boolean error = false;
    for (ConstructorDeclaration constructorDeclaration : classDeclaration.getConstructors()) {
      Collection<ParameterDeclaration> parameters = constructorDeclaration.getParameters();
      for (ParameterDeclaration parameterDeclaration : parameters) {
        Default annotation = parameterDeclaration.getAnnotation(Default.class);
        if (annotation != null) {
          error(parameterDeclaration, "@Default is not legal in constructor parameters");
          error = true;
        }
      }
    }
    if (error) {
      return;
    }

    boolean atLeastOneDefault = false;
    methods:
    for (MethodDeclaration methodDeclaration : classDeclaration.getMethods()) {
      Collection<ParameterDeclaration> parameters = methodDeclaration.getParameters();
      boolean seenDefault = false;
      String[] names = new String[parameters.size()];
      String[] types = new String[parameters.size()];
      String[] defaults = new String[parameters.size()];
      int n = 0;
      for (ParameterDeclaration parameterDeclaration : parameters) {
        Default annotation = parameterDeclaration.getAnnotation(Default.class);
        names[n] = parameterDeclaration.getSimpleName();
        types[n] = parameterDeclaration.getType().toString();
        if (annotation != null) {
          seenDefault = true;
          if ("java.lang.String".equals(types[n])) {
            defaults[n] = '"' + annotation.value() + '"';
          } else {
            defaults[n] = annotation.value();
          }
        } else if (seenDefault) {
          error(
              parameterDeclaration,
              "All parameters after a parameter annotated with @Default must be annotated with @Default");
          continue methods;
        }
        n++;
      }

      if (seenDefault) {
        atLeastOneDefault = true;
        if (methodDeclaration.getModifiers().contains(Modifier.PRIVATE)) {
          error(methodDeclaration, "Private methods cannot use @Default parameters");
        }
        if (methodDeclaration.getModifiers().contains(Modifier.STATIC)) {
          error(methodDeclaration, "Static methods cannot use @Default parameters");
        }
        String modifiers3 = "";
        if (methodDeclaration.getModifiers().contains(Modifier.PUBLIC)) {
          modifiers3 = "public ";
        } else if (methodDeclaration.getModifiers().contains(Modifier.PROTECTED)) {
          modifiers3 = "protected ";
        }
        String throwsClause = getThrowsClause(methodDeclaration);
        String returnType = methodDeclaration.getReturnType().toString();
        String methodName = methodDeclaration.getSimpleName();
        String argDecl = "";
        String callArgs = "";
        for (int i = 0; i < n; i++) {
          if (defaults[i] != null) {
            String callArgsWithDefaults = callArgs;
            for (int j = i; j < n; j++) {
              if (j > 0) {
                callArgsWithDefaults += ", ";
              }
              callArgsWithDefaults += defaults[j];
            }
            Thing method = new Thing("method");
            method.put("name", methodName);
            method.put("returnType", returnType);
            method.put("throwsClause", throwsClause);
            method.put("argDecls", argDecl);
            method.put("modifiers", modifiers3);
            method.put("args", callArgsWithDefaults);
            data.add("defaultMethods", method);
          }
          if (i > 0) {
            argDecl += ", ";
            callArgs += ", ";
          }
          argDecl += types[i] + ' ' + names[i];
          callArgs += names[i];
        }
        Thing method = new Thing("method");
        method.put("name", methodName);
        method.put("returnType", returnType);
        method.put("throwsClause", throwsClause);
        method.put("modifiers", modifiers3);
        method.put("abstract", true);
        method.put("argDecls", argDecl);
        data.add("defaultMethods", method);
      }
    }
    data.put("atLeastOneDefault", atLeastOneDefault);
    if (!atLeastOneDefault) {
      data.setEmpty("defaultMethods");
    }
  }
Exemplo n.º 11
0
 private Thing setupMethod(ExecutableDeclaration declaration, boolean forceNonAbstract) {
   String name = null;
   String returnType = null;
   boolean isAbstract = false;
   String nullBody = null;
   String throwsClause = "";
   if (declaration instanceof ConstructorDeclaration) {
     name = "<init>";
   } else {
     MethodDeclaration methodDeclaration = (MethodDeclaration) declaration;
     name = methodDeclaration.getSimpleName();
     returnType = methodDeclaration.getReturnType().toString();
     if (!forceNonAbstract) {
       isAbstract = methodDeclaration.getModifiers().contains(Modifier.ABSTRACT);
     }
     if ("void".equals(returnType)) {
       nullBody = "// null object implementation; do nothing";
     } else if ("boolean".equals(returnType)) {
       nullBody = "false; // null object implementation";
     } else if ("char".equals(returnType)) {
       nullBody = "' '; // null object implementation";
     } else if (BeanAnnotationProcessor.PRIMITIVE_TYPES.contains(returnType)) {
       nullBody = "0; // null object implementation";
     } else {
       nullBody = "null; // null object implementation";
     }
   }
   Collection<ReferenceType> thrownTypes = declaration.getThrownTypes();
   if (!thrownTypes.isEmpty()) {
     throwsClause = "throws " + commaSeparate(thrownTypes);
   }
   String genericDecls = null;
   String argDecls = null;
   String args = null;
   String modifiers = "";
   Collection<ParameterDeclaration> parameters = declaration.getParameters();
   for (ParameterDeclaration parameterDeclaration : parameters) {
     argDecls =
         addWithCommasBetween(
             argDecls,
             parameterDeclaration.getType() + " " + parameterDeclaration.getSimpleName());
     args = addWithCommasBetween(args, parameterDeclaration.getSimpleName());
   }
   Collection<TypeParameterDeclaration> formalTypeParameters =
       declaration.getFormalTypeParameters();
   for (TypeParameterDeclaration typeParameterDeclaration : formalTypeParameters) {
     genericDecls = addWithCommasBetween(genericDecls, typeParameterDeclaration);
   }
   Collection<Modifier> modifiers2 = declaration.getModifiers();
   for (Modifier modifier : modifiers2) {
     if (!"abstract".equals(modifier.toString())) {
       modifiers += modifier.toString() + ' ';
     }
   }
   if (genericDecls == null) {
     genericDecls = "";
   } else {
     genericDecls = '<' + genericDecls + "> ";
   }
   Thing method = new Thing("method");
   method.put("name", name);
   method.put("returnType", returnType);
   method.put("abstract", isAbstract);
   method.put("nullBody", nullBody);
   method.put("modifiers", modifiers); // do not normalize; already "" or has ' ' at end
   method.put("argDecls", normalizeList(argDecls));
   method.put("args", normalizeList(args));
   method.put("genericDecls", genericDecls);
   method.put("throwsClause", throwsClause);
   return method;
 }
Exemplo n.º 12
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;
  }
Exemplo n.º 13
0
 public String methodToString(MethodDeclaration method) {
   StringBuffer buf = new StringBuffer(method.getSimpleName());
   for (ParameterDeclaration param : method.getParameters())
     buf.append(";" + param.getType().toString());
   return buf.toString();
 }