Package javax.annotation.processing

Examples of javax.annotation.processing.Filer


@SupportedAnnotationTypes("TestMe")
public class T6413690 extends AbstractProcessor {
    public boolean process(Set<? extends TypeElement> annotations,
                           RoundEnvironment roundEnvironment) {
        Elements elements = processingEnv.getElementUtils();
        Filer filer = processingEnv.getFiler();
        TypeElement testMe = elements.getTypeElement(TestMe.class.getName());
        Set<? extends Element> supers = roundEnvironment.getElementsAnnotatedWith(testMe);
        try {
            for (Element sup : supers) {
                Writer sub = filer.createSourceFile(sup.getSimpleName() + "_GENERATED").openWriter();
                sub.write(String.format("class %s_GENERATED extends %s {}",
                                        sup.getSimpleName(),
                                        ((TypeElement)sup).getQualifiedName()));
                sub.close();
            }
View Full Code Here


                        elementList.add(target);
                    }
                }
            }

            Filer filer = processingEnv.getFiler();

            JAXBContext context = JAXBContext.newInstance(MountPoint.class);
            MountPoint mountPoint = readExistingData(filer, context);

            FileObject file = createXmlFile(filer, messager, elementList);
View Full Code Here

      providers.put(providerTypeName, providerImplementerName);
    }
  }

  private void generateConfigFiles() {
    Filer filer = processingEnv.getFiler();

    for (String providerInterface : providers.keySet()) {
      String resourceFile = "META-INF/services/" + providerInterface;
      log("Working on resource file: " + resourceFile);
      try {
        SortedSet<String> allServices = Sets.newTreeSet();
        try {
          // would like to be able to print the full path
          // before we attempt to get the resource in case the behavior
          // of filer.getResource does change to match the spec, but there's
          // no good way to resolve CLASS_OUTPUT without first getting a resource.
          FileObject existingFile = filer.getResource(StandardLocation.CLASS_OUTPUT, "",
              resourceFile);
          log("Looking for existing resource file at " + existingFile.toUri());
          Set<String> oldServices = ServicesFiles.readServiceFile(existingFile.openInputStream());
          log("Existing service entries: " + oldServices);
          allServices.addAll(oldServices);
        } catch (IOException e) {
          // According to the javadoc, Filer.getResource throws an exception
          // if the file doesn't already exist.  In practice this doesn't
          // appear to be the case.  Filer.getResource will happily return a
          // FileObject that refers to a non-existent file but will throw
          // IOException if you try to open an input stream for it.
          log("Resource file did not already exist.");
        }

        Set<String> newServices = new HashSet<String>(providers.get(providerInterface));
        if (allServices.containsAll(newServices)) {
          log("No new service entries being added.");
          return;
        }

        allServices.addAll(newServices);
        log("New service file contents: " + allServices);
        FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "",
            resourceFile);
        OutputStream out = fileObject.openOutputStream();
        ServicesFiles.writeServiceFile(allServices, out);
        out.close();
        log("Wrote to: " + fileObject.toUri());
View Full Code Here

  @Override
  public boolean process(Set<? extends TypeElement> type, RoundEnvironment env) {

    Elements elementUtils = processingEnv.getElementUtils();
    Types typeUtils = processingEnv.getTypeUtils();
    Filer filer = processingEnv.getFiler();
    TypeElement fragmentType = elementUtils.getTypeElement("android.app.Fragment");
    TypeElement supportFragmentType =
        elementUtils.getTypeElement("android.support.v4.app.Fragment");
    Map<TypeElement, Set<Element>> fieldsByType = new HashMap<TypeElement, Set<Element>>(100);

    Element[] origHelper = null;

    for (Element element : env.getElementsAnnotatedWith(Arg.class)) {
      TypeElement enclosingElement = (TypeElement) element.getEnclosingElement();

      // Check if its a fragment
      if (!((fragmentType != null && typeUtils.isSubtype(enclosingElement.asType(),
          fragmentType.asType())) || (supportFragmentType != null && typeUtils.isSubtype(
          enclosingElement.asType(), supportFragmentType.asType())))) {
        error(element, "@Arg can only be used on fragment fields (%s.%s)",
            enclosingElement.getQualifiedName(), element);
        continue;
      }

      if (element.getModifiers().contains(Modifier.FINAL) || element.getModifiers()
          .contains(Modifier.STATIC) || element.getModifiers().contains(Modifier.PRIVATE) || element
          .getModifiers()
          .contains(Modifier.PROTECTED)) {
        error(element, "@Arg fields must not be private, protected, final or static (%s.%s)",
            enclosingElement.getQualifiedName(), element);
        continue;
      }

      Set<Element> fields = fieldsByType.get(enclosingElement);
      if (fields == null) {
        fields = new LinkedHashSet<Element>(10);
        fieldsByType.put(enclosingElement, fields);
      }
      fields.add(element);
    }

    // Store the key - value for the generated FragmentArtMap class
    Map<String, String> autoMapping = new HashMap<String, String>();

    for (Map.Entry<TypeElement, Set<Element>> entry : fieldsByType.entrySet()) {
      try {
        // Skip abstract classes
        if (entry.getKey().getModifiers().contains(Modifier.ABSTRACT)) {
          continue;
        }

        String builder = entry.getKey().getSimpleName() + "Builder";
        List<Element> originating = new ArrayList<Element>(10);
        originating.add(entry.getKey());
        TypeMirror superClass = entry.getKey().getSuperclass();
        while (superClass.getKind() != TypeKind.NONE) {
          TypeElement element = (TypeElement) typeUtils.asElement(superClass);
          if (element.getQualifiedName().toString().startsWith("android.")) {
            break;
          }
          originating.add(element);
          superClass = element.getSuperclass();
        }

        String qualifiedFragmentName = entry.getKey().getQualifiedName().toString();
        String qualifiedBuilderName = qualifiedFragmentName + "Builder";

        Element[] orig = originating.toArray(new Element[originating.size()]);
        origHelper = orig;
        JavaFileObject jfo = filer.createSourceFile(qualifiedBuilderName, orig);
        Writer writer = jfo.openWriter();
        JavaWriter jw = new JavaWriter(writer);
        writePackage(jw, entry.getKey());
        jw.emitImports("android.os.Bundle");
        jw.beginType(builder, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL));
View Full Code Here

            final MustacheFactory factory = new DefaultMustacheFactory();
            final Mustache mustache = factory.compile("templates/template.mustache");

            try {
                final Filer filer = processingEnv.getFiler();
                final JavaFileObject file = filer.createSourceFile(type.getName().getQualified());

                try (Writer writer = file.openWriter()) {
                    mustache.execute(writer, type).flush();
                }
            } catch (IOException e) {
View Full Code Here

        {

            return true;
        }

        Filer filer = processingEnv.getFiler();

        try
        {

            for (Element e : roundEnv.getElementsAnnotatedWith(SystemConfigFactoryConstructor.class))
View Full Code Here

            config.setLocalizedLookup(false);

            final Template template = config.getTemplate("templates/template.ftl");

            for (Type type : types) {
                final Filer filer = processingEnv.getFiler();
                final JavaFileObject file = filer.createSourceFile(type.getName().getQualified());

                try (Writer writer = file.openWriter()) {
                    //mustache.execute(writer, type).flush();
                    template.process(type, writer);
                }
View Full Code Here

    if (annotations.isEmpty()) {
      return true;
    }

    try {
      Filer filer = processingEnv.getFiler();
      Map<String, MessageBundleInfo> messageBundles = new HashMap<String, MessageBundleInfo>();

      for (Element e : roundEnv
          .getElementsAnnotatedWith(MessageBundle.class)) {
        if (e instanceof TypeElement) {
          TypeElement messageBundleElement = (TypeElement) e;
          String messageBundle = messageBundleElement
              .getQualifiedName().toString();
          String messageBundleSimpleName = messageBundleElement.getSimpleName().toString();
          String messageBundleEnumName = messageBundle + "Enum";
          Set<String> messages = new HashSet<String>();

          for (Element messageBundleChild : messageBundleElement
              .getEnclosedElements()) {
            if (messageBundleChild instanceof ExecutableElement) {
              messages.add(getKey((ExecutableElement) messageBundleChild));
            }
          }

          if (!messages.isEmpty()) {
            String baseName = messageBundle.replaceAll("\\.", "/");
            FileObject javaFileObject;
           
            try {
              javaFileObject = filer.getResource(
                StandardLocation.SOURCE_PATH, "", baseName
                    + ".java");
            } catch(FileNotFoundException ex) {
              throw new IllegalArgumentException("Could not find the source file '" + baseName + ".java' that actually triggered the enum generation process", ex);
            }
           
            long lastModified = javaFileObject.getLastModified();
            Set<Locale> locales = new TreeSet<Locale>(LOCALE_COMPARATOR);
            URI baseUri = null;

            // Here we assume that the resources are present in the
            // source output location

            try {
              // Normally there is an english properties file
              try {
                baseUri = filer.getResource(
                    StandardLocation.CLASS_PATH, "",
                    baseName + "_en.properties").toUri();
              } catch (FileNotFoundException ex1) {
                try {
                  baseUri = filer.getResource(
                      StandardLocation.CLASS_OUTPUT, "",
                      baseName + "_en.properties").toUri();
                } catch (FileNotFoundException ex2) {
                  baseUri = filer.getResource(
                      StandardLocation.SOURCE_PATH, "",
                      baseName + "_en.properties").toUri();
                }
              }
            } catch (FileNotFoundException ex1) {
              // Otherwise we have to go through all available
              // locales
              for (Locale l : Locale.getAvailableLocales()) {
                String path;

                try {
                  path = baseName + "_" + l.getLanguage()
                      + ".properties";
                  baseUri = filer.getResource(
                      StandardLocation.CLASS_PATH, "",
                      path).toUri();
                  break;
                } catch (FileNotFoundException ex2) {
                  try {
                    path = baseName + "_" + l.getLanguage()
                        + ".properties";
                    baseUri = filer.getResource(
                        StandardLocation.CLASS_OUTPUT, "",
                        path).toUri();
                    break;
                  } catch (FileNotFoundException ex3) {
                    try {
                      path = baseName + "_" + l.getLanguage()
                          + ".properties";
                      baseUri = filer.getResource(
                          StandardLocation.SOURCE_PATH, "",
                          path).toUri();
                      break;
                    } catch (FileNotFoundException ex4) {
                      // Nothing we can do about it
                    }
                  }
                }

                if (l.getCountry() != null
                    && !l.getCountry().isEmpty()) {


                  try {
                    path = baseName + "_" + l.getLanguage()
                        + "_" + l.getCountry()
                        + ".properties";
                    baseUri = filer.getResource(
                        StandardLocation.CLASS_PATH,
                        "", path).toUri();
                    break;
                  } catch (FileNotFoundException ex2) {
                    try {
                      path = baseName + "_" + l.getLanguage()
                          + "_" + l.getCountry()
                          + ".properties";
                      baseUri = filer.getResource(
                          StandardLocation.CLASS_OUTPUT,
                          "", path).toUri();
                      break;
                    } catch (FileNotFoundException ex3) {
                      try {
                        path = baseName + "_" + l.getLanguage()
                            + "_" + l.getCountry()
                            + ".properties";
                        baseUri = filer.getResource(
                            StandardLocation.SOURCE_PATH,
                            "", path).toUri();
                        break;
                      } catch (FileNotFoundException ex4) {
                        // Nothing we can do about it
                      }
                    }
                  }
                }
              }
            }

            if (baseUri == null) {
              throw new IllegalArgumentException(
                  "No properties files could be found for '"
                      + messageBundle + "'");
            }

            File baseDir = new File(baseUri).getParentFile();
           
            if(!baseDir.exists() || !baseDir.isDirectory()) {
              throw new IllegalArgumentException("The base directory for the properties files could not be found!");
            }

            for (File propertiesFile : baseDir.listFiles()) {
                // Only check properties files that belong to the message bundle
                if(propertiesFile.getName().startsWith(messageBundleSimpleName + "_") || propertiesFile.getName().equals(messageBundleSimpleName + ".properties")) {
                  checkPropertiesFile(propertiesFile, messages);
                  String name = propertiesFile.getName();
                  int index = name.indexOf('_');
                  int dotIndex = name.lastIndexOf('.');
   
                  if (index > -1 && dotIndex > -1) {
                    locales.add(LocaleUtils.getLocale(name
                        .substring(index + 1, dotIndex)));
                  }
                }
            }

            MessageBundleInfo info = new MessageBundleInfo(
                baseName, lastModified, locales, messages);
            messageBundles.put(messageBundleEnumName, info);
          }
        }
      }

      for (Map.Entry<String, MessageBundleInfo> entry : messageBundles
          .entrySet()) {
        String className = entry.getKey();
        JavaFileObject jfo = filer.createSourceFile(className);

        if (jfo.getLastModified() == entry.getValue().getLastModified()) {
          // Skip unchanged files
          continue;
        }
View Full Code Here

{

    @Override
    public boolean process( Set<? extends TypeElement> annotations, RoundEnvironment roundEnv )
    {
        Filer filer = processingEnv.getFiler();

        Elements elementUtils = processingEnv.getElementUtils();

        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith( SimpleAnnotation.class );

        for ( Element element : elements )
        {
            Name name = element.getSimpleName();

            PackageElement packageElement = elementUtils.getPackageOf( element );

            try
            {
                FileObject resource =
                    filer.createResource( StandardLocation.SOURCE_OUTPUT, packageElement.getQualifiedName(), name
                        + ".txt", element );

                Writer writer = resource.openWriter();
                writer.write( name.toString() );
                writer.close();
View Full Code Here

            final MustacheFactory factory = new DefaultMustacheFactory();
            final Mustache mustache = factory.compile("templates/template.mustache");

            try {
                final Filer filer = processingEnv.getFiler();
                final JavaFileObject file = filer.createSourceFile(type.getName().getQualified());

                try (Writer writer = file.openWriter()) {
                    mustache.execute(writer, type).flush();
                }
            } catch (IOException e) {
View Full Code Here

TOP

Related Classes of javax.annotation.processing.Filer

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.