Search in sources :

Example 1 with PackageFolder

use of com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder in project cobigen by devonfw.

the class JavaInputReader method read.

/**
 * Reads the data at the specified path.
 *
 * @param path the Path of the content to read
 * @param additionalArguments
 *        <ul>
 *        <li>In case of path pointing to a folder
 *        <ol>
 *        <li>packageName: String, required</li>
 *        <li>classLoader: ClassLoader, required</li>
 *        </ol>
 *        additional arguments are ignored</li>
 *        <li>In case of path pointing to a file
 *        <ol>
 *        </ol>
 *        </li>
 *        </ul>
 */
@Override
public Object read(Path path, Charset inputCharset, Object... additionalArguments) throws InputReaderException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Read input file {} by java plugin with charset {} and additional arguments {}...", path, inputCharset, Arrays.toString(additionalArguments));
    }
    ClassLoader classLoader = null;
    if (Files.isDirectory(path)) {
        LOG.debug("Path {} to be read is a directory", path);
        String packageName = null;
        for (Object addArg : additionalArguments) {
            if (packageName == null && addArg instanceof String) {
                packageName = (String) addArg;
            } else if (classLoader == null && addArg instanceof ClassLoader) {
                classLoader = new CompositeClassLoader(JavaInputReader.class.getClassLoader(), (ClassLoader) addArg);
            }
        }
        if (classLoader == null) {
            classLoader = createParsedClassLoader(path);
        }
        if (packageName == null || classLoader == null) {
            throw new IllegalArgumentException("Expected packageName:String and classLoader:ClassLoader as additional arguments but was " + toString(additionalArguments));
        }
        PackageFolder packageFolder = new PackageFolder(path.toUri(), packageName, classLoader);
        LOG.debug("Read {}.", packageFolder);
        return packageFolder;
    } else {
        Class<?> clazz = null;
        for (Object addArg : additionalArguments) {
            if (clazz == null && addArg instanceof Class) {
                clazz = (Class<?>) addArg;
            } else if (classLoader == null && addArg instanceof ClassLoader) {
                classLoader = new CompositeClassLoader(JavaInputReader.class.getClassLoader(), (ClassLoader) addArg);
            }
        }
        if (classLoader == null) {
            classLoader = createParsedClassLoader(path);
        }
        try (BufferedReader pathReader = Files.newBufferedReader(path, inputCharset)) {
            // lambdas
            if (clazz == null) {
                if (classLoader == null) {
                    JavaClass firstJavaClass = JavaParserUtil.getFirstJavaClass(pathReader);
                    LOG.debug("Reading {} without classloader support.", firstJavaClass);
                    return firstJavaClass;
                } else {
                    JavaClass firstJavaClass = JavaParserUtil.getFirstJavaClass(classLoader, pathReader);
                    try {
                        clazz = classLoader.loadClass(firstJavaClass.getCanonicalName());
                    } catch (ClassNotFoundException e) {
                        // ignore
                        LOG.warn("Class {} not found in classloader, ignoring as it might be neglectable.", firstJavaClass, e);
                        return firstJavaClass;
                    }
                    Object[] result = new Object[] { firstJavaClass, clazz };
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Read {}.", Arrays.toString(result));
                    }
                    return result;
                }
            } else {
                Object[] result = new Object[] { null, clazz };
                if (classLoader == null) {
                    result[0] = JavaParserUtil.getFirstJavaClass(pathReader);
                } else {
                    result[0] = JavaParserUtil.getFirstJavaClass(classLoader, pathReader);
                }
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Read {}.", Arrays.toString(result));
                }
                return result;
            }
        } catch (IOException e) {
            throw new InputReaderException("Could not read file " + path.toString(), e);
        } catch (ParseException e) {
            throw new InputReaderException("Failed to parse java sources in " + path.toString() + ".", e);
        }
    }
}
Also used : IOException(java.io.IOException) InputReaderException(com.devonfw.cobigen.api.exception.InputReaderException) JavaClass(com.thoughtworks.qdox.model.JavaClass) PackageFolder(com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder) BufferedReader(java.io.BufferedReader) JavaClass(com.thoughtworks.qdox.model.JavaClass) ParseException(com.thoughtworks.qdox.parser.ParseException)

Example 2 with PackageFolder

use of com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder in project cobigen by devonfw.

the class JavaInputReader method getInputObjects.

/**
 * Returns all input objects for the given container input.
 *
 * @param input container input (only {@link PackageFolder} instances will be supported)
 * @param inputCharset {@link Charset} to be used to read the children
 * @param recursively states, whether the children should be retrieved recursively
 * @return the list of children. In this case {@link File} objects
 */
public List<Object> getInputObjects(Object input, Charset inputCharset, boolean recursively) {
    LOG.debug("Retrieve input object for input {} {}", input, recursively ? "recursively" : "");
    List<Object> javaClasses = new LinkedList<>();
    if (input instanceof PackageFolder) {
        File packageFolder = new File(((PackageFolder) input).getLocation());
        List<File> files = retrieveAllJavaSourceFiles(packageFolder, recursively);
        for (File f : files) {
            ClassLibraryBuilder classLibraryBuilder = new ModifyableClassLibraryBuilder();
            classLibraryBuilder.appendDefaultClassLoaders();
            ClassLoader containerClassloader = ((PackageFolder) input).getClassLoader();
            if (containerClassloader != null) {
                classLibraryBuilder.appendClassLoader(containerClassloader);
            }
            try (FileInputStream fis = new FileInputStream(f);
                InputStreamReader isr = new InputStreamReader(fis, inputCharset)) {
                classLibraryBuilder.addSource(isr);
                JavaSource source = null;
                for (JavaSource s : classLibraryBuilder.getClassLibrary().getJavaSources()) {
                    source = s;
                    // only consider one class per file
                    break;
                }
                if (source != null) {
                    // save cast as given by the customized builder
                    if (source.getClasses().size() > 0) {
                        JavaClass javaClass = source.getClasses().get(0);
                        // try loading class
                        if (containerClassloader != null) {
                            try {
                                Class<?> loadedClass = containerClassloader.loadClass(javaClass.getCanonicalName());
                                javaClasses.add(new Object[] { javaClass, loadedClass });
                            } catch (ClassNotFoundException e) {
                                LOG.info("Could not load Java type '{}' with the containers class loader. " + "Just returning the parsed Java model.", javaClass.getCanonicalName());
                                javaClasses.add(javaClass);
                            }
                        } else {
                            javaClasses.add(javaClass);
                        }
                    }
                }
            } catch (IOException e) {
                LOG.error("The file {} could not be parsed as a java class", f.getAbsolutePath().toString(), e);
            }
        }
    }
    LOG.debug("{} java classes found!", javaClasses.size());
    return javaClasses;
}
Also used : InputStreamReader(java.io.InputStreamReader) ModifyableClassLibraryBuilder(com.devonfw.cobigen.javaplugin.merger.libextension.ModifyableClassLibraryBuilder) ClassLibraryBuilder(com.thoughtworks.qdox.library.ClassLibraryBuilder) ModifyableClassLibraryBuilder(com.devonfw.cobigen.javaplugin.merger.libextension.ModifyableClassLibraryBuilder) IOException(java.io.IOException) LinkedList(java.util.LinkedList) FileInputStream(java.io.FileInputStream) JavaClass(com.thoughtworks.qdox.model.JavaClass) PackageFolder(com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder) JavaSource(com.thoughtworks.qdox.model.JavaSource) File(java.io.File)

Example 3 with PackageFolder

use of com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder in project cobigen by devonfw.

the class JavaInputReaderTest method testGetInputObjectsRecursively_resultOrder.

/**
 * Test if the method input list returned by {@link JavaInputReader#getInputObjectsRecursively(Object, Charset)} has a
 * proper order to match the expected preview at any time
 */
@Test
public void testGetInputObjectsRecursively_resultOrder() {
    File javaSourceFile = new File(testFileRootPath + "packageFolder");
    PackageFolder pkg = new PackageFolder(javaSourceFile.toURI(), "notOfInterest");
    assertThat(pkg).isNotNull();
    JavaInputReader input = new JavaInputReader();
    List<Object> list = input.getInputObjectsRecursively(pkg, Charsets.UTF_8);
    assertThat(list).hasSize(3);
    List<String> simpleNames = Lists.newArrayList();
    for (Object o : list) {
        if (o instanceof JavaClass) {
            simpleNames.add(((JavaClass) o).getName());
        }
    }
    assertThat(simpleNames).containsExactlyInAnyOrder("RootClass", "SuperClass1", "SuperClass2");
}
Also used : JavaClass(com.thoughtworks.qdox.model.JavaClass) PackageFolder(com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder) JavaInputReader(com.devonfw.cobigen.javaplugin.inputreader.JavaInputReader) File(java.io.File) Test(org.junit.Test)

Example 4 with PackageFolder

use of com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder in project cobigen by devonfw.

the class JavaMatcher method matches.

@Override
public boolean matches(MatcherTo matcher) {
    try {
        MatcherType matcherType = Enum.valueOf(MatcherType.class, matcher.getType().toUpperCase());
        switch(matcherType) {
            case FQN:
                String fqn = getFqn(matcher);
                LOG.debug("Matching input FQN {} against regex '{}'", fqn, matcher.getValue());
                return fqn != null && fqn.matches(matcher.getValue());
            case PACKAGE:
                return matcher.getTarget() instanceof PackageFolder && ((PackageFolder) matcher.getTarget()).getPackageName().matches(matcher.getValue());
            case EXPRESSION:
                Object target = matcher.getTarget();
                if (target instanceof Object[]) {
                    // expression
                    if (((Object[]) target)[0] instanceof Class<?>) {
                        target = ((Object[]) target)[0];
                    } else {
                        target = ((Object[]) target)[1];
                    }
                }
                if (target instanceof Class<?>) {
                    TriggerExpressionResolver resolver = new TriggerExpressionResolver((Class<?>) target);
                    return resolver.evaluateExpression(matcher.getValue());
                }
                if (target instanceof JavaClass) {
                    TriggerExpressionResolver resolver = new TriggerExpressionResolver((JavaClass) target);
                    return resolver.evaluateExpression(matcher.getValue());
                }
        }
    } catch (IllegalArgumentException e) {
        LOG.info("Matcher type '{}' not registered --> no match!", matcher.getType());
    }
    return false;
}
Also used : TriggerExpressionResolver(com.devonfw.cobigen.javaplugin.matcher.resolver.TriggerExpressionResolver) JavaClass(com.thoughtworks.qdox.model.JavaClass) PackageFolder(com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder) JavaClass(com.thoughtworks.qdox.model.JavaClass)

Example 5 with PackageFolder

use of com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder in project cobigen by devonfw.

the class ParsedJavaModelBuilderTest method testCorrectExtractionOfInheritedFields_input_packageFolder.

/**
 * Tests the correct extraction of 'methodAccessibleFields' for {@link PackageFolder} as input.
 */
@Test
@Ignore("see com.devonfw.cobigen.javaplugin.inputreader.ParsedJavaModelBuilder.extractMethodAccessibleFields#L115")
public void testCorrectExtractionOfInheritedFields_input_packageFolder() {
    File packageFolderFile = new File(testFileRootPath + "packageFolder");
    PackageFolder packageFolder = new PackageFolder(packageFolderFile.toURI(), RootClass.class.getPackage().getName());
    JavaInputReader javaInputReader = new JavaInputReader();
    List<Object> objects = javaInputReader.getInputObjects(packageFolder, Charsets.UTF_8);
    assertThat(objects).as("The package folder does not contain any java sources!").isNotNull();
    assertThat(objects).hasSize(2);
    boolean found = false;
    for (Object o : objects) {
        Map<String, Object> model = javaInputReader.createModel(o);
        assertThat(model).as("No model has been created!").isNotNull();
        if (RootClass.class.getSimpleName().equals(JavaModelUtil.getName(model))) {
            List<Map<String, Object>> methodAccessibleFields = JavaModelUtil.getMethodAccessibleFields(model);
            assertThat(methodAccessibleFields).isNotNull();
            assertThat(methodAccessibleFields).hasSize(3);
            Map<String, Object> field = JavaModelUtil.getMethodAccessibleField(model, "value");
            assertThat(field).as("Field 'value' not found!").isNotNull();
            assertThat(field.get(ModelConstant.NAME)).isEqualTo("value");
            assertThat(field.get(ModelConstant.TYPE)).isEqualTo("String");
            assertThat(field.get(ModelConstant.CANONICAL_TYPE)).isEqualTo("java.lang.String");
            field = JavaModelUtil.getMethodAccessibleField(model, "setterVisibleByte");
            assertThat(field).as("Field 'setterVisibleByte' not found!").isNotNull();
            assertThat(field.get(ModelConstant.NAME)).isEqualTo("setterVisibleByte");
            assertThat(field.get(ModelConstant.TYPE)).isEqualTo("byte");
            assertThat(field.get(ModelConstant.CANONICAL_TYPE)).isEqualTo("byte");
            field = JavaModelUtil.getMethodAccessibleField(model, "genericAccessible");
            assertThat(field).as("Field 'genericAccessible' not found!").isNotNull();
            assertThat(field.get(ModelConstant.NAME)).isEqualTo("genericAccessible");
            // TODO: Known Issue, this is not possible as the SuperClass2 is not in the same folder and
            // thus not parsed. Thus, due to type erasure the parametric type will be lost.
            // assertThat(field.get(ModelConstant.TYPE)).isEqualTo("List<RootClass>");
            // assertThat(field.get(ModelConstant.CANONICAL_TYPE)).isEqualTo("java.util.List<RootClass>");
            assertThat(field.get(ModelConstant.TYPE)).isEqualTo("List");
            assertThat(field.get(ModelConstant.CANONICAL_TYPE)).isEqualTo("java.util.List");
            found = true;
        }
    }
    assertTrue("Class " + RootClass.class.getName() + "could not be found as child of the package folder.", found);
}
Also used : RootClass(com.devonfw.cobigen.javaplugin.unittest.inputreader.testdata.RootClass) PackageFolder(com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder) JavaInputReader(com.devonfw.cobigen.javaplugin.inputreader.JavaInputReader) File(java.io.File) Map(java.util.Map) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

PackageFolder (com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder)5 JavaClass (com.thoughtworks.qdox.model.JavaClass)4 File (java.io.File)3 JavaInputReader (com.devonfw.cobigen.javaplugin.inputreader.JavaInputReader)2 IOException (java.io.IOException)2 Test (org.junit.Test)2 InputReaderException (com.devonfw.cobigen.api.exception.InputReaderException)1 TriggerExpressionResolver (com.devonfw.cobigen.javaplugin.matcher.resolver.TriggerExpressionResolver)1 ModifyableClassLibraryBuilder (com.devonfw.cobigen.javaplugin.merger.libextension.ModifyableClassLibraryBuilder)1 RootClass (com.devonfw.cobigen.javaplugin.unittest.inputreader.testdata.RootClass)1 ClassLibraryBuilder (com.thoughtworks.qdox.library.ClassLibraryBuilder)1 JavaSource (com.thoughtworks.qdox.model.JavaSource)1 ParseException (com.thoughtworks.qdox.parser.ParseException)1 BufferedReader (java.io.BufferedReader)1 FileInputStream (java.io.FileInputStream)1 InputStreamReader (java.io.InputStreamReader)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 Ignore (org.junit.Ignore)1