Search in sources :

Example 1 with InputReaderException

use of com.devonfw.cobigen.api.exception.InputReaderException 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 InputReaderException

use of com.devonfw.cobigen.api.exception.InputReaderException in project cobigen by devonfw.

the class GenerateMojo method collectInputs.

/**
 * Collects/Converts all inputs from {@link #inputPackages} and {@link #inputFiles} into CobiGen compatible formats
 *
 * @param cobigen to interpret input objects
 * @return the list of CobiGen compatible inputs
 * @throws MojoFailureException if the project {@link ClassLoader} could not be retrieved
 */
private List<Object> collectInputs(CobiGen cobigen) throws MojoFailureException {
    getLog().debug("Collect inputs...");
    List<Object> inputs = new LinkedList<>();
    ClassLoader cl = getProjectClassLoader();
    if (this.inputPackages != null && !this.inputPackages.isEmpty()) {
        for (String inputPackage : this.inputPackages) {
            getLog().debug("Resolve package '" + inputPackage + "'");
            // collect all source roots to resolve input paths
            List<String> sourceRoots = new LinkedList<>();
            sourceRoots.addAll(this.project.getCompileSourceRoots());
            sourceRoots.addAll(this.project.getTestCompileSourceRoots());
            boolean sourceFound = false;
            List<Path> sourcePathsObserved = new LinkedList<>();
            for (String sourceRoot : sourceRoots) {
                String packagePath = inputPackage.replaceAll("\\.", Matcher.quoteReplacement(System.getProperty("file.separator")));
                Path sourcePath = Paths.get(sourceRoot, packagePath);
                getLog().debug("Checking source path " + sourcePath);
                if (exists(sourcePath) && isReadable(sourcePath) && isDirectory(sourcePath)) {
                    Object packageFolder;
                    try {
                        packageFolder = cobigen.read(Paths.get(sourcePath.toUri()), StandardCharsets.UTF_8, inputPackage, cl);
                        inputs.add(packageFolder);
                        sourceFound = true;
                    } catch (InputReaderException e) {
                        throw new MojoFailureException("Could not read input package " + sourcePath.toString(), e);
                    }
                } else {
                    sourcePathsObserved.add(sourcePath);
                }
            }
            if (!sourceFound) {
                throw new MojoFailureException("Currently, packages as inputs are only supported " + "if defined as sources in the current project to be build. Having searched for sources at paths: " + sourcePathsObserved);
            }
        }
    }
    if (this.inputFiles != null && !this.inputFiles.isEmpty()) {
        for (File file : this.inputFiles) {
            getLog().debug("Resolve file '" + file.toURI().toString() + "'");
            Object input = InputPreProcessor.process(cobigen, file, cl);
            inputs.add(input);
        }
    }
    getLog().debug(inputs.size() + " inputs collected.");
    return inputs;
}
Also used : Path(java.nio.file.Path) MojoFailureException(org.apache.maven.plugin.MojoFailureException) File(java.io.File) LinkedList(java.util.LinkedList) InputReaderException(com.devonfw.cobigen.api.exception.InputReaderException)

Example 3 with InputReaderException

use of com.devonfw.cobigen.api.exception.InputReaderException in project cobigen by devonfw.

the class XmlInputReader method read.

@Override
public Object read(Path path, Charset inputCharset, Object... additionalArguments) throws InputReaderException {
    if (!Files.isDirectory(path)) {
        try (InputStream fileIn = Files.newInputStream(path)) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            // disable validations by default to increase overall performance
            factory.setValidating(false);
            factory.setFeature("http://xml.org/sax/features/validation", false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            return factory.newDocumentBuilder().parse(fileIn);
        } catch (SAXException | IOException | ParserConfigurationException e) {
            throw new InputReaderException("Could not read file " + path.toString(), e);
        }
    }
    throw new IllegalArgumentException("Currently folders are not supported as Input by XmlInputReader#read");
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) InputStream(java.io.InputStream) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) InputReaderException(com.devonfw.cobigen.api.exception.InputReaderException)

Example 4 with InputReaderException

use of com.devonfw.cobigen.api.exception.InputReaderException in project cobigen by devonfw.

the class FileInputConverter method convertFile.

/**
 * Reads the input file content and convert it to CobiGen valid input.
 *
 * @param cobigen initialized {@link CobiGen} instance
 * @param inputFile the file with {@link Path} to the object and further information like charset.
 * @return the output Object corresponding to the inputFile
 * @throws GeneratorCreationException if the Reader couldn't read the input File or couldn't find the Plugin
 */
private static Object convertFile(CobiGen cobigen, IFile inputFile) throws GeneratorCreationException {
    Object output = null;
    Charset charset;
    try {
        charset = Charset.forName(inputFile.getCharset());
    } catch (CoreException e) {
        LOG.warn("Could not deterime charset for file " + inputFile.getLocationURI() + " reading with UTF-8.");
        charset = Charset.forName("UTF-8");
    }
    Path inputFilePath = Paths.get(inputFile.getLocationURI());
    try {
        output = cobigen.read(inputFilePath, charset);
    } catch (InputReaderException e) {
        LOG.trace("Could not read file {}", inputFile.getLocationURI(), e);
        throw new GeneratorCreationException("Could not read file " + inputFile.getLocationURI() + " with any input reader", e);
    } catch (PluginNotAvailableException e) {
        LOG.trace(e.getMessage(), e);
        throw new GeneratorCreationException("Could not read file " + inputFile.getLocationURI() + " as no Plug-in for the given type could be found.", e);
    }
    return output;
}
Also used : Path(java.nio.file.Path) CoreException(org.eclipse.core.runtime.CoreException) GeneratorCreationException(com.devonfw.cobigen.eclipse.common.exceptions.GeneratorCreationException) Charset(java.nio.charset.Charset) PluginNotAvailableException(com.devonfw.cobigen.api.exception.PluginNotAvailableException) InputReaderException(com.devonfw.cobigen.api.exception.InputReaderException)

Example 5 with InputReaderException

use of com.devonfw.cobigen.api.exception.InputReaderException in project cobigen by devonfw.

the class GenerateCommand method preprocess.

/**
 * For each input file it is going to get its matching templates or increments and then performs an intersection
 * between all of them, so that the user gets only the templates or increments that will work
 *
 * @param <T> type of generable artifacts to be pre-processed
 *
 * @param cg CobiGen initialized instance
 * @param c class type, specifies whether Templates or Increments should be preprocessed
 * @return List of templates that the user will be able to use
 */
@SuppressWarnings("unchecked")
private <T extends GenerableArtifact> Tuple<List<Object>, List<T>> preprocess(CobiGen cg, Class<T> c) {
    boolean isIncrements = c.getSimpleName().equals(IncrementTo.class.getSimpleName());
    boolean firstIteration = true;
    List<T> finalTos = new ArrayList<>();
    List<Object> generationInputs = new ArrayList<>();
    for (Path inputFile : this.inputFiles) {
        String extension = inputFile.getFileName().toString().toLowerCase();
        boolean isJavaInput = extension.endsWith(".java");
        boolean isOpenApiInput = extension.endsWith(".yaml") || extension.endsWith(".yml");
        // checks for output root path and project root being detectable
        if (this.outputRootPath == null && MavenUtil.getProjectRoot(inputFile, false) == null) {
            LOG.info("Did not detect the input as part of a maven project, the root directory of the maven project was not found.");
            LOG.info("Would you like to take '{}' as a root directory for output generation? \n" + "type yes/y to continue or no/n to cancel (or hit return for yes).", System.getProperty("user.dir"));
            setRootOutputDirectoryWithPrompt();
        }
        try {
            Object input = cg.read(inputFile, StandardCharsets.UTF_8);
            List<T> matching = (List<T>) (isIncrements ? cg.getMatchingIncrements(input) : cg.getMatchingTemplates(input));
            if (matching.isEmpty()) {
                ValidationUtils.throwNoTriggersMatched(inputFile, isJavaInput, isOpenApiInput);
            }
            if (firstIteration) {
                finalTos = matching;
                firstIteration = false;
            } else {
                // We do the intersection between the previous increments and the new ones
                finalTos = (List<T>) (isIncrements ? CobiGenUtils.retainAllIncrements(toIncrementTo(finalTos), toIncrementTo(matching)) : CobiGenUtils.retainAllTemplates(toTemplateTo(finalTos), toTemplateTo(matching)));
            }
            generationInputs.add(input);
        } catch (InputReaderException e) {
            LOG.error("Invalid input for CobiGen, please check your input file '{}'", inputFile.toString());
        }
    }
    if (finalTos.isEmpty()) {
        LOG.error("There are no common Templates/Increments which could be generated from every of your inputs. Please think about executing generation one by one input file.");
        throw new InputMismatchException("No compatible input files.");
    }
    List<T> selectedGenerableArtifacts = (List<T>) (isIncrements ? generableArtifactSelection(this.increments, toIncrementTo(finalTos), IncrementTo.class) : generableArtifactSelection(this.templates, toTemplateTo(finalTos), TemplateTo.class));
    return new Tuple<>(generationInputs, selectedGenerableArtifacts);
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) InputMismatchException(java.util.InputMismatchException) InputReaderException(com.devonfw.cobigen.api.exception.InputReaderException) IncrementTo(com.devonfw.cobigen.api.to.IncrementTo) ArrayList(java.util.ArrayList) List(java.util.List) TemplateTo(com.devonfw.cobigen.api.to.TemplateTo) Tuple(com.devonfw.cobigen.api.util.Tuple)

Aggregations

InputReaderException (com.devonfw.cobigen.api.exception.InputReaderException)8 IOException (java.io.IOException)3 Path (java.nio.file.Path)3 GeneratorCreationException (com.devonfw.cobigen.eclipse.common.exceptions.GeneratorCreationException)2 CoreException (org.eclipse.core.runtime.CoreException)2 MergeException (com.devonfw.cobigen.api.exception.MergeException)1 PluginNotAvailableException (com.devonfw.cobigen.api.exception.PluginNotAvailableException)1 TriggerInterpreter (com.devonfw.cobigen.api.extension.TriggerInterpreter)1 InputFileTo (com.devonfw.cobigen.api.externalprocess.to.InputFileTo)1 IncrementTo (com.devonfw.cobigen.api.to.IncrementTo)1 TemplateTo (com.devonfw.cobigen.api.to.TemplateTo)1 Tuple (com.devonfw.cobigen.api.util.Tuple)1 PackageFolder (com.devonfw.cobigen.javaplugin.inputreader.to.PackageFolder)1 JavaClass (com.thoughtworks.qdox.model.JavaClass)1 ParseException (com.thoughtworks.qdox.parser.ParseException)1 BufferedReader (java.io.BufferedReader)1 File (java.io.File)1 InputStream (java.io.InputStream)1 MalformedURLException (java.net.MalformedURLException)1 Charset (java.nio.charset.Charset)1