Exemplo n.º 1
0
  @Override
  public boolean process(final Set<? extends TypeElement> elements, final RoundEnvironment env) {
    // processingEnv is a predefined member in AbstractProcessor class
    // Messager allows the processor to output messages to the environment
    final Messager messager = processingEnv.getMessager();

    // Create a hash table to hold the option switch to option bean mapping
    final HashMap<String, String> values = new HashMap<String, String>();

    // Loop through the annotations that we are going to process
    // In this case there should only be one: Option
    for (final TypeElement te : elements) {

      // Get the members that are annotated with Option
      for (final Element e : env.getElementsAnnotatedWith(te)) {
        // Process the members. processAnnotation is our own method
        processAnnotation(e, values, messager);
      }
    }

    // If there are any annotations, we will proceed to generate the annotation
    // processor in generateOptionProcessor method
    if (values.size() > 0) {
      try {
        // Generate the option process class
        generateOptionProcessor(processingEnv.getFiler(), values);
      } catch (final Exception e) {
        messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage());
      }
    }
    return true;
  }
  public Map<TypeElement, IntentBindingAdapterGenerator> findAndParseTargets(RoundEnvironment env) {
    Map<TypeElement, IntentBindingAdapterGenerator> targetClassMap =
        new LinkedHashMap<TypeElement, IntentBindingAdapterGenerator>();
    Set<String> erasedTargetNames = new LinkedHashSet<String>();

    // Process each @BindExtra
    for (Element element : env.getElementsAnnotatedWith(BindExtra.class)) {
      try {
        parseBindExtra(element, targetClassMap, erasedTargetNames);
      } catch (Exception e) {
        StringWriter stackTrace = new StringWriter();
        e.printStackTrace(new PrintWriter(stackTrace));
        error(element, "Unable to generate intent adapter for @BindExtra.\n\n%s", stackTrace);
      }
    }

    // Try to find a parent adapter for each adapter
    for (Map.Entry<TypeElement, IntentBindingAdapterGenerator> entry : targetClassMap.entrySet()) {
      TypeElement parent = findParent(entry.getKey(), erasedTargetNames);
      if (parent != null) {
        entry
            .getValue()
            .setParentAdapter(
                getPackageName(parent), parent.getSimpleName() + INTENT_ADAPTER_SUFFIX);
      }
    }

    return targetClassMap;
  }
Exemplo n.º 3
0
  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Processing @Implemented...");
    for (TypeElement annotation : annotations) {
      for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
        TypeElement serviceElement = (TypeElement) element;
        PackageElement packageElement = getPackage(serviceElement);
        final String packageName =
            packageElement == null ? "" : packageElement.getQualifiedName().toString();
        Implemented implemented = serviceElement.getAnnotation(Implemented.class);
        final String implName =
            "".equals(implemented.value())
                ? serviceElement.getSimpleName().toString() + "Impl"
                : implemented.value();
        final List<FieldDescriptor> fields = createFieldList(serviceElement);
        final String localName = determineLocalName(serviceElement);
        final boolean isPublic = serviceElement.getModifiers().contains(Modifier.PUBLIC);
        ImplementedDescriptor annotationDescriptor =
            new ImplementedDescriptor(isPublic, packageName, implName, localName, fields);
        createImplSourceFile(annotationDescriptor, serviceElement, packageName + "." + implName);
      }
    }

    return true;
  }
Exemplo n.º 4
0
  private Set<TypeElement> getMappers(
      final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) {
    Set<TypeElement> mapperTypes = new HashSet<TypeElement>();

    for (TypeElement annotation : annotations) {
      // Indicates that the annotation's type isn't on the class path of the compiled
      // project. Let the compiler deal with that and print an appropriate error.
      if (annotation.getKind() != ElementKind.ANNOTATION_TYPE) {
        continue;
      }

      try {
        Set<? extends Element> annotatedMappers =
            roundEnvironment.getElementsAnnotatedWith(annotation);
        for (Element mapperElement : annotatedMappers) {
          TypeElement mapperTypeElement = asTypeElement(mapperElement);

          // on some JDKs, RoundEnvironment.getElementsAnnotatedWith( ... ) returns types with
          // annotations unknown to the compiler, even though they are not declared Mappers
          if (mapperTypeElement != null && MapperPrism.getInstanceOn(mapperTypeElement) != null) {
            mapperTypes.add(mapperTypeElement);
          }
        }
      } catch (Throwable t) { // whenever that may happen, but just to stay on the save side
        handleUncaughtError(annotation, t);
        continue;
      }
    }
    return mapperTypes;
  }
 @Override
 public Observable<ElementScanner> call(RoundEnvironment roundEnv, TypeElement element) {
   return Observable.from(roundEnv.getElementsAnnotatedWith(element))
       .map(new GetEnclosingElement())
       .filter(new NotNestedClass(mProcessingEnv))
       .filter(
           new Func1<Element, Boolean>() {
             @Override
             public Boolean call(Element element) {
               return mSingleHit.add(element);
             }
           })
       .map(
           new Func1<Element, ElementScanner>() {
             @Override
             public ElementScanner call(Element element) {
               if (mProcessingEnv.isSubtype(element.asType(), "android.app.Activity")) {
                 return new ActivityScanner(mProcessingEnv, (TypeElement) element);
               } else if (mProcessingEnv.isSubtype(element.asType(), "android.app.Fragment")) {
                 return new FragmentScanner(mProcessingEnv, (TypeElement) element);
               } else if (mProcessingEnv.isSubtype(element.asType(), "android.view.View")) {
                 return new ViewScanner(mProcessingEnv, (TypeElement) element);
               }
               return new ElementScanner(mProcessingEnv, (TypeElement) element) {
                 @Override
                 protected void scan() {
                   mProcessingEnv.printMessage(
                       Diagnostic.Kind.ERROR,
                       getOrigin(),
                       "Expected subtype of Activity, Fragment or View");
                 }
               };
             }
           });
 }
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   try {
     Set<? extends Element> set = roundEnv.getElementsAnnotatedWith(Parcelable.class);
     for (Element element : set) {
       try {
         TypeElement enclosingElement = (TypeElement) element;
         ProxyInfo pi = new ProxyInfo(enclosingElement.getQualifiedName().toString());
         writeLog(pi.getFullName());
         JavaFileObject jfo = filer.createSourceFile(pi.getFullName(), enclosingElement);
         Writer writer = jfo.openWriter();
         writeLog(pi.createCode());
         writer.write(pi.createCode());
         writer.flush();
         writer.close();
         writeLog("ok");
       } catch (Exception e) {
         e.printStackTrace();
         writeLog(e.getMessage());
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
     writeLog(e.getMessage());
   }
   return true;
 }
Exemplo n.º 7
0
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   // check if process was done on previous round
   if (OcelotProcessor.isDone()
       || roundEnv.processingOver()) { // Returns true if types generated by this round will not be
     // subject to a subsequent round of annotation processing; returns
     // false otherwise.
     return true; // if is it : stop
   }
   // Create provider of ocelot-services.js
   String js = createJSServicesProvider();
   // Create file ocelot-services.js
   try {
     FileObject resource = filer.createResource(StandardLocation.CLASS_OUTPUT, "", js);
     try (Writer writer = resource.openWriter()) {
       ElementVisitor visitor = new DataServiceVisitor(processingEnv);
       for (Element element : roundEnv.getElementsAnnotatedWith(DataService.class)) {
         messager.printMessage(
             Diagnostic.Kind.MANDATORY_WARNING, " javascript generation class : " + element);
         element.accept(visitor, writer);
       }
     }
   } catch (IOException e) {
     messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage());
   }
   OcelotProcessor.setDone(true);
   return true;
 }
Exemplo n.º 8
0
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   // Here is where we store all attributes per class that we need to generate code for.
   List<CollectedClass> collectedClasses = new ArrayList<>();
   for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(PostmanEnabled.class)) {
     // Filter out everything but the classes
     CollectedClass collectedClass =
         CollectedClasses.obtain(mLogger, mTypes, mElements, annotatedElement);
     if (collectedClass != null) {
       collectedClasses.add(collectedClass);
     }
   }
   // Generate code
   for (CollectedClass annotatedClass : collectedClasses) {
     //            mLogger.other("Processing type %s", annotatedClass.toString());
     try {
       CollectedClassWriter writer = annotatedClass.getWriter();
       writer.writeToFile(mElements, mFiler);
     } catch (IOException e) {
       mLogger.error(
           annotatedClass.getClassElement(),
           "Unable to write code for type %s: %s",
           annotatedClass,
           e.getMessage());
     }
   }
   return true;
 }
Exemplo n.º 9
0
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   // System.out.println("supported options: "+
   // Arrays.toString(getSupportedOptions().toArray()));
   if (!roundEnv.processingOver()) {
     for (TypeElement currAnno : annotations) {
       // System.out.println("Found " + currAnno.getQualifiedName());
       if (currAnno.getQualifiedName().contentEquals(GENERATE_POJO_BUILDER_CLASS.getName())) {
         Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(currAnno);
         // System.out.println("[GenerateBuilder] annotatedElements="+
         // Arrays.toString(annotatedElements.toArray()));
         for (Element elem : annotatedElements) {
           if (elem.getKind() == ElementKind.CLASS) {
             TypeElement typeElem = (TypeElement) elem;
             GeneratePojoBuilder annotation = typeElem.getAnnotation(GENERATE_POJO_BUILDER_CLASS);
             generatePojoBuilderProcessor.process(typeElem, annotation);
           } else if (elem.getKind() == ElementKind.METHOD) {
             ExecutableElement execElem = (ExecutableElement) elem;
             GeneratePojoBuilder annotation = execElem.getAnnotation(GENERATE_POJO_BUILDER_CLASS);
             generatePojoBuilderProcessor.process(execElem, annotation);
           }
         }
       }
     }
   }
   return false;
 }
 private Collection<EnclosingView> processAnnotations(RoundEnvironment roundEnv) {
   Set<? extends Element> views = roundEnv.getElementsAnnotatedWith(ThreadDecoratedView.class);
   ArrayList<EnclosingView> modelViews = new ArrayList<>();
   for (Element e : views) {
     modelViews.add(processView(e));
   }
   return modelViews;
 }
Exemplo n.º 11
0
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   for (TypeElement t : annotations) {
     for (Element e : roundEnv.getElementsAnnotatedWith(t)) {
       System.out.println(e + " " + t);
     }
   }
   return true;
 }
 @Override
 protected boolean handleProcess(
     Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   for (Element el : roundEnv.getElementsAnnotatedWith(EventDoc.class)) {
     EventDoc event = el.getAnnotation(EventDoc.class);
     debug("Found event: " + event.module() + " " + event.code() + " " + event.desc());
     addLine(getLine(event), getFilePath(event));
   }
   return true;
 }
  private Map<TypeElement, ViewInjector> findAndParseTargets(RoundEnvironment env) {
    Map<TypeElement, ViewInjector> targetClassMap = new LinkedHashMap<TypeElement, ViewInjector>();
    Set<String> erasedTargetNames = new LinkedHashSet<String>();

    // Process each @InjectView element.
    for (Element element : env.getElementsAnnotatedWith(InjectView.class)) {
      try {
        parseInjectView(element, targetClassMap, erasedTargetNames);
      } catch (Exception e) {
        StringWriter stackTrace = new StringWriter();
        e.printStackTrace(new PrintWriter(stackTrace));

        error(element, "Unable to generate view injector for @InjectView.\n\n%s", stackTrace);
      }
    }

    // Process each @InjectViews element.
    for (Element element : env.getElementsAnnotatedWith(InjectViews.class)) {
      try {
        parseInjectViews(element, targetClassMap, erasedTargetNames);
      } catch (Exception e) {
        StringWriter stackTrace = new StringWriter();
        e.printStackTrace(new PrintWriter(stackTrace));

        error(element, "Unable to generate view injector for @InjectViews.\n\n%s", stackTrace);
      }
    }

    // Process each annotation that corresponds to a listener.
    for (Class<? extends Annotation> listener : LISTENERS) {
      findAndParseListener(env, listener, targetClassMap, erasedTargetNames);
    }

    // Try to find a parent injector for each injector.
    for (Map.Entry<TypeElement, ViewInjector> entry : targetClassMap.entrySet()) {
      String parentClassFqcn = findParentFqcn(entry.getKey(), erasedTargetNames);
      if (parentClassFqcn != null) {
        entry.getValue().setParentInjector(parentClassFqcn + SUFFIX);
      }
    }

    return targetClassMap;
  }
 /**
  * Check parameter annotations for being qualifiers.
  *
  * @param round The round environment.
  */
 private void checkParameters(RoundEnvironment round) {
   Set<? extends Element> params = round.getElementsAnnotatedWith(Parameter.class);
   note("processing %d parameter annotations", params.size());
   for (Element param : params) {
     Qualifier q = param.getAnnotation(Qualifier.class);
     if (q == null) {
       warning(param, "parameter %s is not annotated as a qualifier", param);
     }
   }
 }
Exemplo n.º 15
0
  /** {@inheritDoc} */
  @Override
  public boolean process(
      final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {

    for (final Element element : roundEnv.getElementsAnnotatedWith(Emits.class)) {
      final TypeElement typeElement = (TypeElement) element;
      for (final Emit emit : typeElement.getAnnotation(Emits.class).value()) {
        processEmit(emit, typeElement);
      }
    }
    for (final Element element : roundEnv.getElementsAnnotatedWith(Emit.class)) {
      final TypeElement typeElement = (TypeElement) element;
      processEmit(typeElement.getAnnotation(Emit.class), typeElement);
    }
    if (roundEnv.processingOver() && !roundEnv.errorRaised()) {
      try {
        final PrintWriter metaWriter =
            new PrintWriter(
                processingEnv
                    .getFiler()
                    .createResource(
                        StandardLocation.SOURCE_OUTPUT,
                        "",
                        "META-INF/services/javax.annotation.processing.Processor",
                        elementCollection.toArray(new Element[0]))
                    .openWriter());
        for (final String processor : annotationProcessors) {
          metaWriter.println(processor);
        }
        metaWriter.close();
      } catch (final IOException e) {
        final String msg =
            MessageFormat.format(
                LOG.getResourceBundle().getString("ioerror"),
                "META-INF/services/javax.annotation.processing.Processor",
                e.getMessage());
        processingEnv.getMessager().printMessage(Kind.ERROR, msg);
        throw new IllegalStateException(msg, e);
      }
    }
    return true;
  }
Exemplo n.º 16
0
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   for (TypeElement type :
       ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(RequireDefault.class))) {
     if (!type.getKind().isInterface() && type.getKind() != ElementKind.ANNOTATION_TYPE) {
       hasConstructor(type);
     }
   }
   for (TypeElement annotation : annotations) {
     RequireDefault constructor = annotation.getAnnotation(RequireDefault.class);
     if (constructor != null) {
       for (TypeElement type :
           ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(annotation))) {
         if (!type.getKind().isInterface()) {
           hasConstructor(type);
         }
       }
     }
   }
   return true;
 }
 @Override
 public Observable<ElementScanner> call(RoundEnvironment roundEnv, TypeElement element) {
   return Observable.from(roundEnv.getElementsAnnotatedWith(element))
       .map(new GetEnclosingElement())
       .filter(new NotNestedClass(mProcessingEnv))
       .map(
           new Func1<Element, ElementScanner>() {
             @Override
             public ElementScanner call(Element element) {
               return new LoaderCallbacksScanner(mProcessingEnv, (TypeElement) element);
             }
           });
 }
Exemplo n.º 18
0
  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
      return true;
    }

    for (Element element : roundEnv.getElementsAnnotatedWith(ServiceProvider.class)) {
      assert element.getKind().isClass();
      processElement((TypeElement) element);
    }

    return true;
  }
  private Collection<EnclosingOutput> processAnnotations(RoundEnvironment roundEnv) {
    Set<? extends Element> elementOutputs = roundEnv.getElementsAnnotatedWith(Output.class);
    Map<String, EnclosingOutput> outputs = new HashMap<>();

    for (Element e : elementOutputs) {
      OutputModel outputModel = processOutput(e);
      String parentClassName = outputModel.getParentClassName();
      if (!outputs.containsKey(parentClassName)) {
        outputs.put(parentClassName, createParent(e));
      }
      outputs.get(parentClassName).getOutputs().add(outputModel);
    }
    return outputs.values();
  }
 /**
  * Check shareable components for serializability.
  *
  * @param round The round environment.
  */
 private void checkShareableComponents(RoundEnvironment round) {
   Set<? extends Element> elts = round.getElementsAnnotatedWith(Shareable.class);
   note("processing %d shareable elements", elts.size());
   TypeMirror serializable = elementUtils.getTypeElement("java.io.Serializable").asType();
   for (Element elt : elts) {
     note("examining %s", elt);
     TypeMirror type = elt.asType();
     if (typeUtils.isAssignable(type, serializable)) {
       note("shareable type %s is serializable", type);
     } else {
       warning(elt, "shareable type %s is not serializable", type);
     }
   }
 }
Exemplo n.º 21
0
 @Override
 public boolean process(
     final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
   System.out.println(roundEnv);
   System.out.println(annotations);
   for (Element elem : roundEnv.getElementsAnnotatedWith(Decoder.class)) {
     Decoder decoder = elem.getAnnotation(Decoder.class);
     String message =
         String.format(
             "Annotation found in %s with decoder %s.", elem.getSimpleName(), decoder.value());
     processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, message);
   }
   return true;
 }
Exemplo n.º 22
0
  @Override
  protected boolean onProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (Element e : roundEnv.getElementsAnnotatedWith(BeanFactoryExtension.class)) {
      TypeElement factoryElement = (TypeElement) e;
      factories.add(factoryElement.getQualifiedName().toString());
    }

    for (Element e : roundEnv.getElementsAnnotatedWith(AutoBeanFactory.Category.class)) {
      AnnotationMirror categoryAnnotation =
          MoreElements.getAnnotationMirror(e, AutoBeanFactory.Category.class).get();
      AnnotationValue value = AnnotationMirrors.getAnnotationValue(categoryAnnotation, "value");
      Collection<String> categories = extractValue(value);
      this.categories.addAll(categories);
    }

    if (!factories.isEmpty()) {
      debug("Generating composite bean factory");
      code(
          BEAN_FACTORY_TEMPLATE,
          BEAN_FACTORY_PACKAGE,
          BEAN_FACTORY_CLASS,
          () -> {
            Map<String, Object> context = new HashMap<>();
            context.put("packageName", BEAN_FACTORY_PACKAGE);
            context.put("className", BEAN_FACTORY_CLASS);
            context.put("factories", factories);
            context.put("categories", categories);
            return context;
          });

      info("Successfully generated composite bean factory [%s].", BEAN_FACTORY_CLASS);
      factories.clear();
      categories.clear();
    }
    return false;
  }
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   this.metadataCollector.processing(roundEnv);
   Elements elementUtils = this.processingEnv.getElementUtils();
   TypeElement annotationType = elementUtils.getTypeElement(configurationPropertiesAnnotation());
   if (annotationType != null) { // Is @ConfigurationProperties available
     for (Element element : roundEnv.getElementsAnnotatedWith(annotationType)) {
       processElement(element);
     }
   }
   if (roundEnv.processingOver()) {
     writeMetaData();
   }
   return false;
 }
Exemplo n.º 24
0
 private void parseOnChangedTarget(
     RoundEnvironment env,
     Map<TypeElement, BindingClass> targetClassMap,
     Set<String> erasedTargetNames,
     Class... annotationClasses) {
   for (Class clazz : annotationClasses) {
     for (Element element : env.getElementsAnnotatedWith(clazz)) {
       if (!SuperficialValidation.validateElement(element)) continue;
       try {
         parseOnChanged(element, targetClassMap, erasedTargetNames, clazz);
       } catch (Exception e) {
         logParsingError(element, clazz, e);
       }
     }
   }
 }
 @Override
 public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
   for (Element element : roundEnv.getElementsAnnotatedWith(Test.class)) {
     if (element.getKind() == ElementKind.METHOD) {
       String methodName = element.getSimpleName().toString();
       String className =
           ((TypeElement) (element.getEnclosingElement())).getQualifiedName().toString();
       List<String> points = pointsOfTestCase(element);
       if (!points.isEmpty()) {
         String testName = className + " " + methodName;
         testDescs.add(new TestDesc(testName, ImmutableList.copyOf(points)));
       }
     }
   }
   return false;
 }
Exemplo n.º 26
0
  @Override
  public boolean process(
      Set<? extends TypeElement> supportedAnnotations, RoundEnvironment roundEnvironment) {

    // short-circuit if there are multiple rounds
    if (_isComplete) {
      return true;
    }

    Collection<String> processedPackageNames = new LinkedHashSet<String>();
    for (Element e : roundEnvironment.getElementsAnnotatedWith(RequestMapping.class)) {
      if (e instanceof ExecutableElement) {
        addPackageName(processedPackageNames, e);
        processRequestMappingMethod((ExecutableElement) e);
      }
    }

    if (_docs.getResources().size() > 0) {

      OutputStream fout = null;
      try {
        FileObject file = getOutputFile();
        boolean exists = new File(file.getName()).exists();
        fout = file.openOutputStream();
        _docs.toStream(fout);
        processingEnv
            .getMessager()
            .printMessage(
                Diagnostic.Kind.NOTE,
                String.format(
                    "Wrote REST docs for %s endpoints to %s file at %s",
                    _docs.getResources().size(), exists ? "existing" : "new", file.getName()));
      } catch (Exception e) {
        throw new RuntimeException(e); // TODO wrap in something nicer
      } finally {
        if (fout != null) {
          try {
            fout.close();
          } catch (IOException ignored) {
            // ignored
          }
        }
      }
    }
    _isComplete = true;
    return true;
  }
Exemplo n.º 27
0
  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (Element elem : roundEnv.getElementsAnnotatedWith(FixedRecord.class)) {
      String classPackage =
          processingEnv.getElementUtils().getPackageOf(elem).getQualifiedName().toString();
      ClassWrapper classWrapper = new ClassWrapper(classPackage, elem.getSimpleName().toString());

      List<Element> listGetter = getFixedFieldAnnotateMethod(elem);

      for (Element elemMethod : listGetter) {
        TypeWrapper typeWrapper;
        MethodWrapper methodWrapper = new MethodWrapper();
        FixedField fixedField = elemMethod.getAnnotation(FixedField.class);
        String decoratorClass = getDecoratorClass(fixedField);

        methodWrapper.setName(elemMethod.getSimpleName().toString());
        methodWrapper.setFixedField(fixedField);
        methodWrapper.setDecoratorClass(decoratorClass);

        String fullName = ((ExecutableType) elemMethod.asType()).getReturnType().toString();
        if (fullName.contains("<") && fixedField.collectionSize() > 0) {
          fullName = fullName.substring(fullName.indexOf("<") + 1, fullName.indexOf(">"));
        }
        String packageName = fullName.substring(0, fullName.lastIndexOf("."));
        String typeName = fullName.substring(packageName.length() + 1);

        if (fixedField.length() == 0 && fixedField.collectionSize() == 0) {
          methodWrapper.setBean(true);
        } else if (fixedField.collectionSize() > 0) {
          methodWrapper.setList(true);
        }

        typeWrapper = new TypeWrapper(packageName, typeName);
        methodWrapper.setType(typeWrapper);
        classWrapper.addMethod(methodWrapper);
      }

      parser.createParserClass(classWrapper);
      // TODO
      processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "");
    }
    if (roundEnv.processingOver()) {
      parser.getJavaFileBuilder().writeJavaFile(processingEnv);
      return false;
    }
    return true; // no further processing of this annotation type
  }
Exemplo n.º 28
0
  @Override
  public boolean process(
      Set<? extends TypeElement> typeElements, RoundEnvironment roundEnvironment) {
    logger = new Logger(processingEnv.getMessager());

    // Get holding class
    for (TypeElement typeElement : typeElements) {
      Set<? extends Element> annotatedElements =
          roundEnvironment.getElementsAnnotatedWith(typeElement);
      for (Element annotatedElement : annotatedElements) {
        TypeElement enclosingElement = (TypeElement) annotatedElement.getEnclosingElement();
        manageType(enclosingElement, logger);
      }
    }

    return true;
  }
Exemplo n.º 29
0
  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
      return true;
    }
    final List<LabelTemplateMethod> methods = new ArrayList<LabelTemplateMethod>();
    for (Element element : roundEnv.getElementsAnnotatedWith(MessageBundle.class)) {
      if (element.getKind() != ElementKind.INTERFACE) {
        continue;
      }
      final TypeElement bundleType = (TypeElement) element;
      processLabels(bundleType, methods);
      try {

        FileObject file = null;
        switch (generationType) {
          case SOURCE:
            file =
                processingEnv
                    .getFiler()
                    .createSourceFile(getTargetClassName(bundleType), bundleType);
            break;

          case RESSOURCE:
            file =
                processingEnv
                    .getFiler()
                    .createResource(
                        SOURCE_OUTPUT,
                        bundleType.getEnclosingElement().toString(),
                        getTargetSimpleName(bundleType) + ".properties");
            break;
        }

        final Writer writer = file.openWriter();
        writer.write(getCode(bundleType, methods));
        writer.close();
      } catch (IOException e) {
        processingEnv.getMessager().printMessage(Kind.ERROR, e.getMessage(), bundleType);
      } finally {
        methods.clear();
      }
    }
    return false;
  }
  /** {@inheritDoc} */
  @Override
  public boolean process(
      final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
    boolean process = true;

    Types typesUtil = processingEnv.getTypeUtils();
    Validator validator = Validator.buildValidator(processingEnv);

    // Call jboss logging tools
    for (TypeElement annotation : annotations) {
      if (isValidAnnotation(annotation)) {
        Set<? extends TypeElement> elements =
            typesIn(roundEnv.getElementsAnnotatedWith(annotation));
        Collection<ValidationMessage> errorMessages = validator.validate(elements);
        for (ValidationMessage error : errorMessages) {
          if (error.type() == ValidationMessage.MessageType.ERROR) {
            logger.error(error.getElement(), error.getMessage());
            process = false;
          } else {
            logger.warn(error.getElement(), error.getMessage());
          }
        }
        if (process) {
          for (TypeElement element : elements) {

            if (element.getKind().isInterface()
                && !element.getModifiers().contains(Modifier.PRIVATE)) {

              Collection<ExecutableElement> methods = getInterfaceMethods(element, typesUtil);
              final MethodDescriptors methodDescriptors =
                  MethodDescriptors.of(processingEnv.getElementUtils(), typesUtil, methods);

              for (AbstractTool processor : processors) {
                logger.debug("Executing processor %s", processor.getName());
                processor.processTypeElement(annotation, element, methodDescriptors);
              }
            }
          }
        }
      }
    }

    return process;
  }