Example usage for javax.tools JavaFileObject toUri

List of usage examples for javax.tools JavaFileObject toUri

Introduction

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

Prototype

URI toUri();

Source Link

Document

Returns a URI identifying this file object.

Usage

From source file:com.github.cchacin.JsonSchemaProcessor.java

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

    for (final Element element : roundEnv.getElementsAnnotatedWith(JsonSchema.class)) {
        final TypeElement classElement = (TypeElement) element;
        final PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();

        processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
                "annotated class: " + classElement.getQualifiedName(), element);

        final String fqClassName = classElement.getQualifiedName().toString();
        final String className = classElement.getSimpleName().toString();
        final String packageName = packageElement.getQualifiedName().toString();

        final JsonSchema jsonSchema = element.getAnnotation(JsonSchema.class);

        try {/* w  w w .ja  v  a  2  s  .  c o m*/
            final JsonNode node = new ObjectMapper().readTree(
                    Thread.currentThread().getContextClassLoader().getResourceAsStream(jsonSchema.path()));
            vc.put("display", new DisplayTool());
            vc.put("json", node);

            vc.put("className", className);
            vc.put("packageName", packageName);

            final JavaFileObject jfo = filer.createSourceFile(fqClassName + "JsonSchema");

            processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
                    "creating source file: " + jfo.toUri());
            final Writer writer = jfo.openWriter();

            processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
                    "applying velocity template: " + vt.getName());

            vt.merge(vc, writer);

            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:me.bayes.vertx.vest.VestApplication.java

private void addScannedClasses() {

    PackageHelper helper = new PackageHelper(classLoader);

    for (String packageName : packagesToScan) {

        final String folderLocationName = packageName.replaceAll("[.]", "/");

        try {/*ww w . j  a v a 2s  . c om*/

            for (JavaFileObject javaObject : helper.find(packageName)) {

                try {

                    final String clazzUriString = javaObject.toUri().toString();
                    final String clazzName = clazzUriString
                            .substring(clazzUriString.lastIndexOf(folderLocationName),
                                    clazzUriString.lastIndexOf('.'))
                            .replaceAll("/", ".");
                    final Class<?> clazz = classLoader.loadClass(clazzName);

                    final Annotation[] annotations = clazz.getAnnotations();
                    Integer priority = DEFAULT_PROVIDER_PRIORITY;
                    Class<?> provider = null;
                    for (Annotation annotation : annotations) {
                        if (annotation.annotationType().equals(Path.class)) {
                            this.endpointClasses.add(clazz);
                            break;
                        } else if (annotation.annotationType().equals(Provider.class)) {
                            provider = clazz;
                        } else if (annotation.annotationType().equals(Priority.class)) {
                            priority = ((Priority) annotation).value();
                        }
                    }
                    if (provider != null) {
                        addProvider(priority, provider);
                    }
                } catch (ClassNotFoundException e) {
                    LOG.error(String.format("Error occurred scanning package %s.", packageName), e);
                }
            }

        } catch (IOException e) {
            LOG.error(String.format("Error occurred scanning package %s.", packageName), e);
        }
    }

}

From source file:com.dspot.declex.action.Actions.java

private void createInformationForAction(String actionHolder, boolean isExternal) {

    TypeElement typeElement = env.getProcessingEnvironment().getElementUtils().getTypeElement(actionHolder);
    TypeElement generatedHolder = env.getProcessingEnvironment().getElementUtils()
            .getTypeElement(TypeUtils.getGeneratedClassName(typeElement, env));

    ActionFor actionForAnnotation = null;
    try {//  w ww  .j  ava2 s  . c  om
        actionForAnnotation = typeElement.getAnnotation(ActionFor.class);
    } catch (Exception e) {
        LOGGER.error("An error occurred processing the @ActionFor annotation", e);
    }

    if (actionForAnnotation != null) {

        for (String name : actionForAnnotation.value()) {

            ACTION_HOLDER_ELEMENT_FOR_ACTION.put("$" + name, typeElement);

            //Get model info
            final ActionInfo actionInfo = new ActionInfo(actionHolder);
            actionInfo.isGlobal = actionForAnnotation.global();
            actionInfo.isTimeConsuming = actionForAnnotation.timeConsuming();

            if (isExternal) {
                actionInfo.generated = false;
            }

            //This will work only for cached classes
            if (generatedHolder != null) {
                for (Element elem : generatedHolder.getEnclosedElements()) {
                    if (elem instanceof ExecutableElement) {
                        final String elemName = elem.getSimpleName().toString();
                        final List<? extends VariableElement> params = ((ExecutableElement) elem)
                                .getParameters();

                        if (elemName.equals("onViewChanged") && params.size() == 1 && params.get(0).asType()
                                .toString().equals(HasViews.class.getCanonicalName())) {
                            actionInfo.handleViewChanges = true;
                            break;
                        }
                    }
                }
            }

            addAction(name, actionHolder, actionInfo, false);

            String javaDoc = env.getProcessingEnvironment().getElementUtils().getDocComment(typeElement);
            actionInfo.setReferences(javaDoc);

            List<DeclaredType> processors = annotationHelper.extractAnnotationClassArrayParameter(typeElement,
                    ActionFor.class.getCanonicalName(), "processors");

            //Load processors
            if (processors != null) {
                for (DeclaredType processor : processors) {

                    Class<ActionProcessor> processorClass = null;

                    try {

                        ClassLoader loader = classLoaderForProcessor.get(processor.toString());
                        if (loader != null) {
                            processorClass = (Class<ActionProcessor>) Class.forName(processor.toString(), true,
                                    loader);
                        } else {
                            processorClass = (Class<ActionProcessor>) Class.forName(processor.toString());
                        }

                    } catch (ClassNotFoundException e) {

                        Element element = env.getProcessingEnvironment().getElementUtils()
                                .getTypeElement(processor.toString());
                        if (element == null) {
                            LOGGER.error("Processor \"" + processor.toString() + "\" couldn't be loaded",
                                    typeElement);
                        } else {

                            try {
                                //Get the file from which the class was loaded
                                java.lang.reflect.Field field = element.getClass().getField("classfile");
                                field.setAccessible(true);
                                JavaFileObject classfile = (JavaFileObject) field.get(element);

                                String jarUrl = classfile.toUri().toURL().toString();
                                jarUrl = jarUrl.substring(0, jarUrl.lastIndexOf('!') + 2);

                                //Create or use a previous created class loader for the given file
                                ClassLoader loader;
                                if (classLoaderForProcessor.containsKey(jarUrl)) {
                                    loader = classLoaderForProcessor.get(jarUrl);
                                } else {
                                    loader = new URLClassLoader(new URL[] { new URL(jarUrl) },
                                            Actions.class.getClassLoader());
                                    classLoaderForProcessor.put(processor.toString(), loader);
                                    classLoaderForProcessor.put(jarUrl, loader);
                                }

                                processorClass = (Class<ActionProcessor>) Class.forName(processor.toString(),
                                        true, loader);

                            } catch (Throwable e1) {
                                LOGGER.error("Processor \"" + processor.toString() + "\" couldn't be loaded: "
                                        + e1.getMessage(), typeElement);
                            }

                        }

                    } catch (ClassCastException e) {
                        LOGGER.error("Processor \"" + processor.toString() + "\" is not an Action Processor",
                                typeElement);
                    }

                    if (processorClass != null) {
                        try {
                            actionInfo.processors.add(processorClass.newInstance());
                        } catch (Throwable e) {
                            LOGGER.info("Processor \"" + processor.toString() + "\" couldn't be instantiated",
                                    typeElement);
                        }
                    }

                }
            }

            createInformationForMethods(typeElement, actionInfo);
        }

    }

}

From source file:com.webcohesion.enunciate.modules.java_json_client.JavaJSONClientModule.java

protected File getServerSideDestFile(File sourceDir, JavaFileObject sourceFile, TypeElement declaration) {
    File destDir = sourceDir;/* w w w .  j ava2 s.co  m*/
    String packageName = this.context.getProcessingEnvironment().getElementUtils().getPackageOf(declaration)
            .getQualifiedName().toString();
    for (StringTokenizer packagePaths = new StringTokenizer(packageName, "."); packagePaths.hasMoreTokens();) {
        String packagePath = packagePaths.nextToken();
        destDir = new File(destDir, packagePath);
    }
    destDir.mkdirs();
    String simpleFilename = sourceFile.toUri().toString();
    simpleFilename = simpleFilename.substring(simpleFilename.lastIndexOf('/'));
    return new File(destDir, simpleFilename);
}

From source file:org.cdmckay.coffeep.Program.java

private static ClassFile getClassFile(JavaFileObject fileObject, CoffeepSystemInfo systemInfo)
        throws IOException, ConstantPoolException {
    if (fileObject == null) {
        throw new IllegalArgumentException("fileObject cannot be null");
    }/* ww  w  .j a v a 2  s.c o  m*/
    if (systemInfo == null) {
        throw new IllegalArgumentException("systemInfo cannot be null");
    }

    InputStream inputStream = fileObject.openInputStream();
    try {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            logger.warn("Exception while getting MD5 MessageDigest", e);
        }

        DigestInputStream digestInputStream = new DigestInputStream(inputStream, messageDigest);
        CountingInputStream countingInputStream = new CountingInputStream(digestInputStream);

        Attribute.Factory attributeFactory = new Attribute.Factory();
        ClassFile classFile = ClassFile.read(countingInputStream, attributeFactory);

        systemInfo.classFileUri = fileObject.toUri();
        systemInfo.classFileSize = countingInputStream.getSize();
        systemInfo.lastModifiedTimestamp = fileObject.getLastModified();
        if (messageDigest != null) {
            systemInfo.digestAlgorithm = messageDigest.getAlgorithm();
            systemInfo.digest = new BigInteger(1, messageDigest.digest()).toString(16);
        }

        return classFile;
    } finally {
        inputStream.close();
    }
}

From source file:org.evosuite.junit.JUnitAnalyzer.java

private static List<File> compileTests(List<TestCase> tests, File dir) {

    TestSuiteWriter suite = new TestSuiteWriter();
    suite.insertAllTests(tests);//from ww  w  .j  a v  a2s  .  c  o  m

    //to get name, remove all package before last '.'
    int beginIndex = Properties.TARGET_CLASS.lastIndexOf(".") + 1;
    String name = Properties.TARGET_CLASS.substring(beginIndex);
    name += "_" + (NUM++) + "_tmp_" + Properties.JUNIT_SUFFIX; //postfix

    try {
        //now generate the JUnit test case
        List<File> generated = suite.writeTestSuite(name, dir.getAbsolutePath(), Collections.EMPTY_LIST);
        for (File file : generated) {
            if (!file.exists()) {
                logger.error("Supposed to generate " + file + " but it does not exist");
                return null;
            }
        }

        //try to compile the test cases
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            logger.error("No Java compiler is available");
            return null;
        }

        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        Locale locale = Locale.getDefault();
        Charset charset = Charset.forName("UTF-8");
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, locale, charset);

        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromFiles(generated);

        List<String> optionList = new ArrayList<>();
        String evosuiteCP = ClassPathHandler.getInstance().getEvoSuiteClassPath();
        if (JarPathing.containsAPathingJar(evosuiteCP)) {
            evosuiteCP = JarPathing.expandPathingJars(evosuiteCP);
        }

        String targetProjectCP = ClassPathHandler.getInstance().getTargetProjectClasspath();
        if (JarPathing.containsAPathingJar(targetProjectCP)) {
            targetProjectCP = JarPathing.expandPathingJars(targetProjectCP);
        }

        String classpath = targetProjectCP + File.pathSeparator + evosuiteCP;

        optionList.addAll(Arrays.asList("-classpath", classpath));

        CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null,
                compilationUnits);
        boolean compiled = task.call();
        fileManager.close();

        if (!compiled) {
            logger.error("Compilation failed on compilation units: " + compilationUnits);
            logger.error("Classpath: " + classpath);
            //TODO remove
            logger.error("evosuiteCP: " + evosuiteCP);

            for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
                if (diagnostic.getMessage(null).startsWith("error while writing")) {
                    logger.error("Error is due to file permissions, ignoring...");
                    return generated;
                }
                logger.error("Diagnostic: " + diagnostic.getMessage(null) + ": " + diagnostic.getLineNumber());
            }

            StringBuffer buffer = new StringBuffer();
            for (JavaFileObject sourceFile : compilationUnits) {
                List<String> lines = FileUtils.readLines(new File(sourceFile.toUri().getPath()));

                buffer.append(compilationUnits.iterator().next().toString() + "\n");

                for (int i = 0; i < lines.size(); i++) {
                    buffer.append((i + 1) + ": " + lines.get(i) + "\n");
                }
            }
            logger.error(buffer.toString());
            return null;
        }

        return generated;

    } catch (IOException e) {
        logger.error("" + e, e);
        return null;
    }
}