Example usage for javax.tools JavaFileObject openOutputStream

List of usage examples for javax.tools JavaFileObject openOutputStream

Introduction

In this page you can find the example usage for javax.tools JavaFileObject openOutputStream.

Prototype

OutputStream openOutputStream() throws IOException;

Source Link

Document

Returns an OutputStream for this file object.

Usage

From source file:mbenson.annotationprocessing.CodeModelProcessorBase.java

@Override
public final boolean process(final Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    JCodeModel codeModel = new JCodeModel();
    boolean result = false;
    try {//  w  w  w .  ja v  a 2  s. c  o m
        result = processTo(codeModel, annotations, roundEnv);
    } catch (Throwable t) {
        error(t, "Error creating code model");
    }
    if (result) {
        try {
            final CodeWriter codeWriter = new CodeWriter() {

                @Override
                public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
                    JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(
                            StringUtils.join(pkg.name(), ".",
                                    StringUtils.removeEnd(fileName, JAVA_FILE_EXTENSION)),
                            annotations.toArray(new TypeElement[annotations.size()]));
                    return sourceFile.openOutputStream();
                }

                @Override
                public void close() throws IOException {
                }
            };
            codeModel.build(
                    new PrologCodeWriter(codeWriter, String.format("generated by %s\n", getClass().getName())));
        } catch (IOException e) {
            error(e, "Error generating code");
        }
    }
    return result;
}

From source file:com.mastfrog.parameters.processor.Processor.java

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

    SourceVersion sv = processingEnv.getSourceVersion();
    if (sv.ordinal() > SourceVersion.RELEASE_7.ordinal()) {
        optionalType = "java.util.Optional";
    } else {//  w  w  w  . j a  v a  2  s .c  om
        TypeElement el = processingEnv.getElementUtils().getTypeElement(optionalType);
        if (el == null) {
            optionalType = "com.mastfrog.util.Optional";
        } else {
            optionalType = "com.google.common.base.Optional";
            fromNullable = "fromNullable";
        }
    }

    Set<? extends Element> all = re.getElementsAnnotatedWith(Params.class);
    List<GeneratedParamsClass> interfaces = new LinkedList<>();
    outer: for (Element e : all) {
        TypeElement te = (TypeElement) e;
        if (te.getSimpleName().toString().endsWith("__GenPage")) {
            continue;
        }
        PackageElement pkg = findPackage(e);
        if (pkg == null) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                    "@Params may not be used in the default package", e);
            continue;
        }
        if (!isPageSubtype(te)) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                    "@Params must be used on a subclass of org.apache.wicket.Page", e);
            continue;
        }
        String className = te.getQualifiedName().toString();
        Params params = te.getAnnotation(Params.class);

        Map<String, List<String>> validators = validatorsForParam(e);
        GeneratedParamsClass inf = new GeneratedParamsClass(className, te, pkg, params, validators);

        if (!params.useRequestBody()) {
            checkConstructor(te, inf);
        }
        interfaces.add(inf);
        Set<String> names = new HashSet<>();
        for (Param param : params.value()) {
            //                if (param.required() && !param.defaultValue().isEmpty()) {
            //                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Don't set required to "
            //                            + "true if you are providing a default value - required makes it an error not "
            //                            + "to have a value, and if there is a default value, that error is an impossibility "
            //                            + "because it will always have a value.", e);
            //                    continue outer;
            //                }
            if (param.value().trim().isEmpty()) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Empty parameter name", e);
                continue outer;
            }
            if (!isJavaIdentifier(param.value())) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                        "Not a valid Java identifier: " + param.value(), e);
                continue outer;
            }
            if (!names.add(param.value())) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                        "Duplicate parameter name '" + param.value() + "'", e);
                continue outer;
            }
            for (char c : ";,./*!@&^/\\<>?'\"[]{}-=+)(".toCharArray()) {
                if (param.value().contains("" + c)) {
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                            "Param name may not contain the character '" + c + "'", e);
                }
            }
            inf.add(param);
        }
    }
    Filer filer = processingEnv.getFiler();
    StringBuilder listBuilder = new StringBuilder();
    for (GeneratedParamsClass inf : interfaces) {
        try {
            String pth = inf.packageAsPath() + '/' + inf.className;
            pth = pth.replace('/', '.');
            JavaFileObject obj = filer.createSourceFile(pth, inf.el);
            try (OutputStream out = obj.openOutputStream()) {
                out.write(inf.toString().getBytes("UTF-8"));
            }
            listBuilder.append(inf.className).append('\n');
        } catch (Exception ex) {
            ex.printStackTrace();
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                    "Error processing annotation: " + ex.getMessage(), inf.el);
            Logger.getLogger(Processor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if (re.processingOver()) {
        try {
            FileObject list = filer.createResource(StandardLocation.CLASS_OUTPUT, "",
                    "META-INF/paramanos/bind.list", all.toArray(new Element[0]));
            try (OutputStream out = list.openOutputStream()) {
                out.write(listBuilder.toString().getBytes("UTF-8"));
            }
        } catch (FilerException ex) {
            Logger.getLogger(Processor.class.getName()).log(Level.INFO, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Processor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return true;
}

From source file:org.cloudfoundry.tools.compiler.CloudFoundryJavaCompilerTest.java

@Test
public void shouldCompileVirtualFile() throws Exception {
    JavaFileObject sourceFile = mock(JavaFileObject.class);
    given(sourceFile.getKind()).willReturn(Kind.SOURCE);
    given(sourceFile.getName()).willReturn("Example.java");
    given(sourceFile.getCharContent(anyBoolean())).willReturn(getExampleJavaContent());
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    JavaFileObject classFile = mock(JavaFileObject.class);
    given(classFile.openOutputStream()).willReturn(outputStream);

    JavaFileManager fileManager = mock(JavaFileManager.class);
    given(fileManager.getJavaFileForOutput(Matchers.any(Location.class), anyString(), eq(Kind.CLASS),
            eq(sourceFile))).willReturn(classFile);
    Iterable<? extends JavaFileObject> compilationUnits = Collections.singleton(sourceFile);
    CompilationTask task = this.javaCompiler.getTask(null, fileManager, null, standardCompilerOptions(), null,
            compilationUnits);// www  . j a v  a  2s  .co m
    assertThat(task.call(), is(Boolean.TRUE));
    assertThat(outputStream.toByteArray().length, is(greaterThan(0)));
}