Java Code Examples for javax.annotation.processing.Filer#createResource()

The following examples show how to use javax.annotation.processing.Filer#createResource() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IncrementalAnnotationProcessorProcessor.java    From gradle-incap-helper with Apache License 2.0 6 votes vote down vote up
private void generateConfigFiles() {
  Filer filer = processingEnv.getFiler();
  try {
    // TODO: merge with an existing file (in case of incremental compilation, in a
    // non-incremental-compile-aware environment; e.g. Maven)
    FileObject fileObject =
        filer.createResource(StandardLocation.CLASS_OUTPUT, "", RESOURCE_FILE);
    try (PrintWriter out =
        new PrintWriter(
            new OutputStreamWriter(fileObject.openOutputStream(), StandardCharsets.UTF_8))) {
      processors.forEach((processor, type) -> out.println(processor + "," + type.name()));
      if (out.checkError()) {
        throw new IOException("Error writing to the file");
      }
    }
  } catch (IOException e) {
    fatalError("Unable to create " + RESOURCE_FILE + ", " + e);
  }
}
 
Example 2
Source File: AbstractServiceProviderProcessor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void writeServices() {
    for (Map.Entry<Filer,Map<String,SortedSet<ServiceLoaderLine>>> outputFiles : outputFilesByProcessor.entrySet()) {
        Filer filer = outputFiles.getKey();
        for (Map.Entry<String,SortedSet<ServiceLoaderLine>> entry : outputFiles.getValue().entrySet()) {
            try {
                FileObject out = filer.createResource(StandardLocation.CLASS_OUTPUT, "", entry.getKey(),
                        originatingElementsByProcessor.get(filer).get(entry.getKey()).toArray(new Element[0]));
                OutputStream os = out.openOutputStream();
                try {
                    PrintWriter w = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
                    for (ServiceLoaderLine line : entry.getValue()) {
                        line.write(w);
                    }
                    w.flush();
                    w.close();
                } finally {
                    os.close();
                }
            } catch (IOException x) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "Failed to write to " + entry.getKey() + ": " + x.toString());
            }
        }
    }
}
 
Example 3
Source File: AnnotationProcessorUtil.java    From kumuluzee with MIT License 6 votes vote down vote up
private static void writeFile(Set<String> content, String resourceName, FileObject overrideFile, Filer filer) throws IOException {
    FileObject file = overrideFile;
    if (file != null) {
        //check if file content equals required content
        final Set<String> fileContent = new BufferedReader(new InputStreamReader(file.openInputStream())).lines().collect(Collectors.toSet());

        if (content.containsAll(fileContent) && fileContent.containsAll(content)) {
            return;
        }
    }
    file = filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceName);
    try (Writer writer = file.openWriter()) {
        for (String serviceClassName : content) {
            writer.write(serviceClassName);
            writer.write(System.lineSeparator());
        }
    }
}
 
Example 4
Source File: TypeJumpingProcessor.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  final Elements elements = processingEnv.getElementUtils();
  Filer filer = processingEnv.getFiler();
  for (Element element : roundEnv.getElementsAnnotatedWith(Annotation.class)) {
    try {
      TypeElement step = (TypeElement) element;
      TypeElement cls = elements.getTypeElement(step.getQualifiedName() + "Jump");
      if (cls != null) {
        String resName = cls.getQualifiedName().toString();
        Element[] origins = new Element[] { cls }; // purposely underspecified originating elements
        FileObject res = filer.createResource(StandardLocation.CLASS_OUTPUT, "", resName, origins);
        res.openWriter().close();
      }
    } catch (IOException e) {
      e.printStackTrace();
      processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage(), element);
    }
  }
  return false;
}
 
Example 5
Source File: Processor_dummyOutput.java    From takari-lifecycle with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  final Filer filer = processingEnv.getFiler();
  final Messager messager = processingEnv.getMessager();

  for (Element element : roundEnv.getElementsAnnotatedWith(Annotation.class)) {
    try {
      filer.createResource(StandardLocation.SOURCE_OUTPUT, "",
          "dummy" + System.currentTimeMillis(), element);
    } catch (IOException e) {
      messager.printMessage(Kind.ERROR, e.getMessage(), element);
    }
  }

  return false;
}
 
Example 6
Source File: AnnotationUtils.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
public static void writeFile(Filer filer, String c, List<String> lines){
    if(lines.isEmpty())
        return;
    try {
        String outputFile = "META-INF/konduit-serving/" + c;
        FileObject file = filer.createResource(StandardLocation.CLASS_OUTPUT, "", outputFile);

        try (Writer w = file.openWriter()) {
            w.write(String.join("\n", lines));
        }

    } catch (Throwable t) {
        throw new RuntimeException("Error in annotation processing", t);
    }
}
 
Example 7
Source File: TransportProcessor.java    From transport with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Generates the UDF metadata resource file in a pretty-printed JSON format
 */
private void generateUDFMetadataFile() {
  Filer filer = processingEnv.getFiler();
  try {
    FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "", Constants.UDF_RESOURCE_FILE_PATH);
    try (Writer writer = fileObject.openWriter()) {
      _transportUdfMetadata.toJson(writer);
    }
    debug("Wrote Transport UDF metadata file to: " + fileObject.toUri());
  } catch (IOException e) {
    fatalError(String.format("Unable to create UDF metadata resource file: %s", e));
  }
}
 
Example 8
Source File: PluggableProcessor.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void generateServiceFiles(Filer filer)
{
    for(String serviceName : factoryImplementations.keySet())
    {
        processingEnv.getMessager()
                .printMessage(Diagnostic.Kind.NOTE, "Generating service file for " + serviceName);

        String relativeName = "META-INF/services/" + serviceName;
        loadExistingServicesFile(filer, serviceName);
        try
        {
            FileObject serviceFile = filer.createResource(StandardLocation.CLASS_OUTPUT, "", relativeName);
            try(PrintWriter pw = new PrintWriter(new OutputStreamWriter(serviceFile.openOutputStream(), "UTF-8")))
            {
                for (String headerLine : License.LICENSE)
                {
                    pw.println("#" + headerLine);
                }
                pw.println("#");
                pw.println("# Note: Parts of this file are auto-generated from annotations.");
                pw.println("#");
                for (String implementation : factoryImplementations.get(serviceName))
                {
                    pw.println(implementation);
                }
            }
        }
        catch (IOException e)
        {
            processingEnv.getMessager()
                    .printMessage(Diagnostic.Kind.ERROR,
                                  "Failed to write services file: "
                                  + relativeName
                                  + " - "
                                  + e.getLocalizedMessage()
                                 );
        }
    }
}
 
Example 9
Source File: ResourcecifyProcessor.java    From sundrio with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    Filer filer = processingEnv.getFiler();

    for (TypeElement typeElement : annotations) {
        for (Element element : env.getElementsAnnotatedWith(typeElement)) {
            Resourcecify resourcecify = element.getAnnotation(Resourcecify.class);
            if (resourcecify == null) {
                continue;
            }

            if (element instanceof Symbol.ClassSymbol) {
                Symbol.ClassSymbol s = (Symbol.ClassSymbol) element;
                try {
                    String packageName = getPackageName(s);

                    JavaFileObject source = s.sourcefile;
                    File sourceFile = new File(source.getName()).getAbsoluteFile();
                    String sourceFileName = sourceFile.getName();

                    FileObject target = filer.createResource(StandardLocation.CLASS_OUTPUT, packageName, sourceFileName, s);
                    copy(source, target);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        }
    }
    return false;
}
 
Example 10
Source File: AnnotationProcessor.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (!roundEnv.processingOver() && !generated) {
    try {
      Filer filer = processingEnv.getFiler();

      JavaFileObject cSource = filer.createSourceFile("ImmutableC");
      try (OutputStream outputStream = cSource.openOutputStream()) {
        outputStream.write("public class ImmutableC { }".getBytes());
      }

      JavaFileObject dSource = filer.createSourceFile("RemovableD");
      try (OutputStream outputStream = dSource.openOutputStream()) {
        outputStream.write("public class RemovableD { }".getBytes());
      }

      FileObject dResource =
          filer.createResource(StandardLocation.CLASS_OUTPUT, "", "RemovableD");
      try (OutputStream outputStream = dResource.openOutputStream()) {
        outputStream.write("foo".getBytes());
      }

      generated = true;
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

  return true;
}
 
Example 11
Source File: JServiceCodeGenerator.java    From jackdaw with Apache License 2.0 4 votes vote down vote up
private FileObject createResource(final Filer filer, final String path) throws Exception {
    return filer.createResource(CLASS_OUTPUT, StringUtils.EMPTY, path);
}