Esempio n. 1
0
 @Before
 public void setup() {
   ProcessingEnvironment env = ProcessingEnvironmentRunner.getProcessingEnvironment();
   elements = env.getElementUtils();
   TypeMUtils typeMUtils = new TypeMUtils();
   underTest = new BuilderModelProducer(env, typeMUtils);
 }
Esempio n. 2
0
 @Before
 public void init() {
   ProcessingEnvironment processingEnv = mock(ProcessingEnvironment.class);
   Elements elementUtils = mock(Elements.class);
   when(processingEnv.getElementUtils()).thenReturn(elementUtils);
   processor.init(processingEnv);
 }
  @Override
  public void writeFieldReadStatement(
      VariableElement field,
      Collection<ExecutableElement> postCreateChildMethods,
      JavaWriter writer)
      throws IOException {
    DeclaredType type = (DeclaredType) field.asType();
    TypeMirror itemType = type.getTypeArguments().get(0);
    TypeMirror itemTypeErasure = processingEnv.getTypeUtils().erasure(itemType);

    String collectionInitializer;
    try {
      collectionInitializer = initializers.findCollectionInitializer(type);
    } catch (InvalidTypeException e) {
      processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage(), field);
      collectionInitializer = "null";
    }
    writer.beginControlFlow("if (bundle.containsKey(\"%s\"))", field.getSimpleName());
    writer.emitStatement("object.%s = %s", field.getSimpleName(), collectionInitializer);
    writer.emitStatement(
        "%1$s.readCollectionFromBundle(object.%2$s, bundle, %3$s.class, \"%2$s\")",
        CollectionBundler.class.getCanonicalName(), field.getSimpleName(), itemTypeErasure);

    writePostCreateChildMethodCalls(field, itemType, postCreateChildMethods, writer);
    writer.endControlFlow();
  }
Esempio n. 4
0
 @Override
 public synchronized void init(ProcessingEnvironment env) {
   super.init(env);
   elementUtils = env.getElementUtils();
   typeUtils = env.getTypeUtils();
   filer = env.getFiler();
 }
 @Override
 public synchronized void init(ProcessingEnvironment processingEnv) {
   super.init(processingEnv);
   note("LensKit Shareable linting active");
   typeUtils = processingEnv.getTypeUtils();
   elementUtils = processingEnv.getElementUtils();
 }
Esempio n. 6
0
 @Override
 public synchronized void init(ProcessingEnvironment env) {
   super.init(env);
   mLogger = new Logger(env);
   mElements = env.getElementUtils();
   mTypes = env.getTypeUtils();
   mFiler = env.getFiler();
 }
Esempio n. 7
0
 @Override
 public void init(ProcessingEnvironment processingEnv) {
   super.init(processingEnv);
   this.processingEnv = processingEnv;
   errorListener =
       new ErrorReceiverImpl(
           processingEnv.getMessager(),
           processingEnv.getOptions().containsKey(Const.DEBUG_OPTION.getValue()));
 }
Esempio n. 8
0
  @Override
  public synchronized void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);

    Elements elementUtils = processingEnv.getElementUtils();
    Types typeUtils = processingEnv.getTypeUtils();
    Filer filer = processingEnv.getFiler();
    Messager messager = processingEnv.getMessager();
  }
 @Override
 public synchronized void init(ProcessingEnvironment processingEnv) {
   super.init(processingEnv);
   elements = processingEnv.getElementUtils();
   types = processingEnv.getTypeUtils();
   messager = processingEnv.getMessager();
   factoryWriter = new FactoryWriter(processingEnv.getFiler());
   providedChecker = new ProvidedChecker(messager);
   declarationFactory = new AutoFactoryDeclaration.Factory(elements, messager);
   factoryDescriptorGenerator =
       new FactoryDescriptorGenerator(messager, elements, declarationFactory);
 }
  @Override
  public void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);

    filer = processingEnv.getFiler();
    messager = processingEnv.getMessager();
    eltUtils = processingEnv.getElementUtils();

    outputDir = processingEnv.getOptions().get("structoutputdir");
    outputDir = outputDir == null ? "gensrc" : outputDir;

    basedir = processingEnv.getOptions().get("basedir");
  }
Esempio n. 11
0
 /**
  * Returns {@code true} if debug enabled otherwirse {@code false}.
  *
  * @param env the environment.
  * @return {@code true} if the debug option enabled otherwirse {@code false} .
  */
 public static boolean isDebugEnabled(ProcessingEnvironment env) {
   String debug = env.getOptions().get(Options.DEBUG);
   if (debug == null) {
     return false;
   }
   return Boolean.valueOf(debug).booleanValue();
 }
Esempio n. 12
0
 @Override
 public Reader getResource(String resourcePath) throws IOException {
   return processingEnv
       .getFiler()
       .getResource(StandardLocation.CLASS_OUTPUT, "", resourcePath)
       .openReader(true);
 }
Esempio n. 13
0
  public void writeXSD(Model m) throws IOException {
    try {
      for (MainInfo main : m.getMains()) {
        List<Element> sources = new ArrayList<Element>();
        sources.add(main.getElement());
        sources.addAll(main.getInterceptorElements());

        FileObject o =
            processingEnv
                .getFiler()
                .createResource(
                    StandardLocation.CLASS_OUTPUT,
                    main.getAnnotation().outputPackage(),
                    main.getAnnotation().outputName(),
                    sources.toArray(new Element[0]));
        BufferedWriter bw = new BufferedWriter(o.openWriter());
        try {
          assembleXSD(bw, m, main);
        } finally {
          bw.close();
        }
      }
    } catch (FilerException e) {
      if (e.getMessage().contains("Source file already created")) return;
      throw e;
    }
  }
Esempio n. 14
0
 /**
  * エラーログ。スタックのフルダンプ。
  *
  * @param t 発生した例外
  */
 protected void error(Throwable t) {
   Messager messager = environment.getMessager();
   StringWriter sw = new StringWriter();
   PrintWriter pw = new PrintWriter(sw);
   t.printStackTrace(pw);
   messager.printMessage(Kind.ERROR, sw.toString());
 }
  /**
   * ソース生成.
   *
   * @throws IOException
   * @author vvakame
   */
  public void write() throws IOException {

    Filer filer = processingEnv.getFiler();
    String generateClassName = classElement.asType().toString() + postfix;
    JavaFileObject fileObject = filer.createSourceFile(generateClassName, classElement);
    Template.write(fileObject, g);
  }
Esempio n. 16
0
 public static FunctionMirror newInstance(ExecutableElement method, ProcessingEnvironment env) {
   assertNotNull(env);
   AnnotationMirror annotationMirror =
       ElementUtil.getAnnotationMirror(method, Function.class, env);
   if (annotationMirror == null) {
     return null;
   }
   FunctionMirror result = new FunctionMirror(annotationMirror, method.getSimpleName().toString());
   for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
       env.getElementUtils().getElementValuesWithDefaults(annotationMirror).entrySet()) {
     String name = entry.getKey().getSimpleName().toString();
     AnnotationValue value = entry.getValue();
     if ("catalog".equals(name)) {
       result.catalog = value;
     } else if ("schema".equals(name)) {
       result.schema = value;
     } else if ("name".equals(name)) {
       result.name = value;
     } else if ("queryTimeout".equals(name)) {
       result.queryTimeout = value;
     } else if ("mapKeyNaming".equals(name)) {
       result.mapKeyNaming = value;
     } else if ("ensureResultMapping".equals(name)) {
       result.ensureResultMapping = value;
     }
   }
   return result;
 }
 /**
  * INTERNAL: Visit a packing-info.java file. We currently don't support package level annotations,
  * but if we did and they impacted canonical model generation we would pick them up here. We
  * should never hit this visit since we filter out package elements, and package elements can not
  * be referenced from classes.
  */
 @Override
 public MetadataClass visitPackage(PackageElement packageElement, MetadataClass metadataClass) {
   processingEnv
       .getMessager()
       .printMessage(Kind.NOTE, "ElementVisitor Package NOT IMPLEMENTED : " + packageElement);
   return null;
 }
Esempio n. 18
0
 @Override
 public Writer newResource(String resourcePath) throws IOException {
   return processingEnv
       .getFiler()
       .createResource(StandardLocation.CLASS_OUTPUT, "", resourcePath)
       .openWriter();
 }
Esempio n. 19
0
 @Override
 public synchronized void init(ProcessingEnvironment processingEnv) {
   super.init(processingEnv);
   String option = processingEnv.getOptions().get("rootOverride");
   if (option != null) {
     setRootOverride(Arrays.asList(option.split(",")));
   }
 }
 private boolean isValidElementFound(String typeName) {
   try {
     @Nullable TypeElement typeElement = processing.getElementUtils().getTypeElement(typeName);
     return typeElement != null && typeElement.asType().getKind() != TypeKind.ERROR;
   } catch (Exception e) {
     // type loading problem
     return false;
   }
 }
Esempio n. 21
0
 /**
  * Returns the java version.
  *
  * @param env the environment.
  * @return java version
  */
 public static double getJavaVersion(ProcessingEnvironment env) {
   String version = env.getOptions().get(Options.JAVA_VERSION);
   if (version != null) {
     try {
       return Double.valueOf(version);
     } catch (NumberFormatException ignored) {
     }
   }
   return javaVersion;
 }
Esempio n. 22
0
 /**
  * Default constructor for ProcessorContext. Sets all settings to their default values.
  *
  * @param processingEnv the ProcessingEnvironment which is provided by the Java Annotation
  *     Processor
  */
 public ProcessorContext(final ProcessingEnvironment processingEnv) {
   System.out.println(processingEnv.getOptions());
   final Map<String, String> options = OptionsSplitter.splitOptions(processingEnv.getOptions());
   System.out.println(options);
   this.processingEnv = processingEnv;
   this.debug = getBoolean(options, DEBUG, false);
   this.acceptJavaPersistenceAnnotations =
       getBoolean(options, ACCEPT_JAVA_PERSISTENCE_ANNOTATIONS, false);
   setAbstractBuilderClassPrefix(options.get(BUILDER_CLASS_PREFIX));
   setBuilderClassPostfix(options.get(BUILDER_CLASS_POSTFIX));
   setBuildMethodName(options.get(BUILD_METHOD_NAME));
   setMethodPrefix(options.get(METHOD_PREFIX));
   setStaticCreate(getBoolean(options, GENERATE_STATIC_CREATE_METHOD, true));
   setStaticCreateMethodName(options.get(STATIC_CREATE_METHOD_NAME));
   setVarArgsForCollections(getBoolean(options, GENERATE_VARARGS_FOR_COLLECTIONS, true));
   setIgnoredClassPrefix(options.get(IGNORED_CLASS_PREFIX));
   setUseIndefiniteArticles(getBoolean(options, USE_INDEFINITE_ARTICLES, true));
   setIgnoreFields(options.get(IGNORE_FIELDS));
 }
  /**
   * @param env the environment
   * @param annUtil utils
   * @param d the method
   */
  public MethodHandler(
      final ProcessingEnvironment env, final AnnUtil annUtil, final ExecutableElement d) {
    this.env = env;
    this.annUtil = annUtil;
    msg = env.getMessager();

    staticMethod = d.getModifiers().contains(Modifier.STATIC);
    methName = d.getSimpleName().toString();
    getter = methName.startsWith("get");
    setter = methName.startsWith("set");

    immutable = d.getAnnotation(Immutable.class) != null;

    CloneForOverride cfo = d.getAnnotation(CloneForOverride.class);
    cloneForOverride = cfo != null;
    if (cloneForOverride) {
      cloneCollectionType = cfo.cloneCollectionType();
      cloneElementType = cfo.cloneElementType();
    }

    returnType = d.getReturnType();
    returnsVoid = env.getTypeUtils().getNoType(TypeKind.VOID).equals(returnType);

    pars = d.getParameters();
    thrownTypes = d.getThrownTypes();

    if ((setter) && (pars != null) && (pars.size() == 1)) {
      fieldType = pars.iterator().next().asType();
      basicType = fieldType.getKind().isPrimitive();
    }

    if (getter) {
      fieldType = returnType;
      basicType = returnType.getKind().isPrimitive();
    }

    if (setter || getter) {
      ucFieldName = methName.substring(3);
      fieldName = ucFieldName.substring(0, 1).toLowerCase() + ucFieldName.substring(1);
    }
  }
Esempio n. 24
0
 /**
  * Whether the specified element is assignable to the fqTn parameter
  *
  * @param processingEnvironment The environment this runs in
  * @param fqTn THe fully qualified type name of the element we want to check
  * @param element The element to check that implements
  * @return true if element implements the fqTn
  */
 public static boolean isSubclass(
     ProcessingEnvironment processingEnvironment, String fqTn, TypeElement element) {
   TypeElement typeElement = processingEnvironment.getElementUtils().getTypeElement(fqTn);
   if (typeElement == null) {
     processingEnvironment
         .getMessager()
         .printMessage(
             Diagnostic.Kind.ERROR,
             "Type Element was null for: "
                 + fqTn
                 + ""
                 + "ensure that the visibility of the class is not private.");
     return false;
   } else {
     TypeMirror classMirror = typeElement.asType();
     return classMirror != null
         && element != null
         && element.asType() != null
         && processingEnvironment.getTypeUtils().isSubtype(element.asType(), classMirror);
   }
 }
  @Override
  public void writeFieldWriteStatement(VariableElement field, JavaWriter writer)
      throws IOException {
    DeclaredType type = (DeclaredType) field.asType();
    TypeMirror itemType = type.getTypeArguments().get(0);
    TypeMirror itemTypeErasure = processingEnv.getTypeUtils().erasure(itemType);

    writer.beginControlFlow("if (object.%s != null)", field.getSimpleName());
    writer.emitStatement(
        "%1$s.writeCollectionToBundle(object.%2$s, bundle, %3$s.class, \"%2$s\")",
        CollectionBundler.class.getCanonicalName(), field.getSimpleName(), itemTypeErasure);
    writer.endControlFlow();
  }
  @Test
  public void testBuilderPackage() {
    // Given:
    TypeElement pojoTypeElement = env.getElementUtils().getTypeElement(ADDRESS_DTO_CLASSNAME);

    // When:
    Output output = underTest.produce(new Input(pojoTypeElement));
    BuilderM builder = output.getBuilder();

    // Then:
    assertEquals("builder classname", "AddressDTOBuilder", builder.getType().getSimpleName());
    assertEquals("package", "testdata.builder", builder.getType().getPackage());
  }
Esempio n. 27
0
  /**
   * Velocity の実行(Javaソース用)。出力先はパッケージ名とクラス名から自動生成。
   *
   * @param context VelocityContext
   * @param pkgName パッケージ名
   * @param clsName クラス名
   * @param templ Velocityテンプレート名。
   * @throws Exception
   */
  protected void applyTemplate(
      VelocityContext context, String pkgName, String clsName, String templ) throws Exception {
    context.put("packageName", pkgName);
    context.put("className", clsName);
    context.put("environment", environment);

    Template template = getVelocityTemplate(templ);
    Filer filer = environment.getFiler();
    JavaFileObject file = filer.createSourceFile(pkgName + '.' + clsName);
    PrintWriter writer = new PrintWriter(file.openWriter());
    template.merge(context, writer);
    writer.close();
  }
Esempio n. 28
0
 private void assembleAttributeDeclaration(Writer w, AttributeInfo ai) throws IOException {
   // TODO: default value
   w.append(
       "<xsd:attribute name=\""
           + ai.getXMLName()
           + "\" type=\""
           + ai.getXSDType(processingEnv.getTypeUtils())
           + "\" "
           + (ai.isRequired() ? "use=\"required\"" : "")
           + ">\r\n");
   assembleDocumentation(w, ai);
   w.append("</xsd:attribute>\r\n");
 }
  public Option<IRClass> find(AndroidManifest manifest) {
    Elements elementUtils = processingEnv.getElementUtils();
    String rClass = getRClassPackageName(manifest) + ".R";
    TypeElement rType = elementUtils.getTypeElement(rClass);

    if (rType == null) {
      LOGGER.error("The generated {} class cannot be found", rClass);
      return Option.absent();
    }

    LOGGER.info("Found project R class: {}", rType.toString());

    return Option.<IRClass>of(new RClass(rType));
  }
  public ValidateDescriptor(ModelDescriptor modelDescriptor, Element field) {
    super(modelDescriptor, field);
    this.validateIf = field.getAnnotation(ValidateIf.class);
    this.validateIfValue = field.getAnnotation(ValidateIfValue.class);

    ProcessingEnvironment processingEnv = modelDescriptor.getProcessingEnvironment();
    Types typeUtils = processingEnv.getTypeUtils();
    this.isMethodValidation = getField().getKind().equals(ElementKind.METHOD);

    if (this.isMethodValidation) {
      // Make sure our method validation returns a boolean value
      if (!((ExecutableElement) this.field).getReturnType().getKind().equals(TypeKind.BOOLEAN)) {
        modelDescriptor
            .getMessager()
            .printMessage(
                Diagnostic.Kind.ERROR,
                "Methods annotated with @Validate must return a boolean value!",
                field);
      }

      methodAnnotation = getField().getAnnotation(Validate.class);
      if (this.methodAnnotation == null) {
        modelDescriptor
            .getMessager()
            .printMessage(Diagnostic.Kind.ERROR, "Could not retrieve method validation annotation");
      }
    } else {
      this.isList =
          typeUtils.isAssignable(
              field.asType(),
              typeUtils.getDeclaredType(
                  processingEnv
                      .getElementUtils()
                      .getTypeElement(ListContainer.class.getCanonicalName()),
                  typeUtils.getWildcardType(null, null)));
    }
  }