Search in sources :

Example 81 with MojoFailureException

use of org.apache.maven.plugin.MojoFailureException in project camel by apache.

the class SpringBootAutoConfigurationMojo method writeComponentSpringFactorySource.

private void writeComponentSpringFactorySource(String packageName, String name) throws MojoFailureException {
    StringBuilder sb = new StringBuilder();
    sb.append("org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\\n");
    String lineToAdd = packageName + "." + name + "\n";
    sb.append(lineToAdd);
    // project root folder
    File root = classesDirectory.getParentFile().getParentFile();
    String fileName = "src/main/resources/META-INF/spring.factories";
    File target = new File(root, fileName);
    // create new file
    try {
        String header = "";
        if (includeLicenseHeader) {
            InputStream is = getClass().getClassLoader().getResourceAsStream("license-header.txt");
            header = loadText(is);
        }
        String code = sb.toString();
        // add empty new line after header
        code = header + "\n" + code;
        getLog().debug("Source code generated:\n" + code);
        FileUtils.write(target, code);
        getLog().info("Created file: " + target);
    } catch (Exception e) {
        throw new MojoFailureException("IOError with file " + target, e);
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) MojoFailureException(org.apache.maven.plugin.MojoFailureException) File(java.io.File) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Example 82 with MojoFailureException

use of org.apache.maven.plugin.MojoFailureException in project camel by apache.

the class ValidateMojo method execute.

// CHECKSTYLE:OFF
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    CamelCatalog catalog = new DefaultCamelCatalog();
    // add activemq as known component
    catalog.addComponent("activemq", "org.apache.activemq.camel.component.ActiveMQComponent");
    // enable did you mean
    catalog.setSuggestionStrategy(new LuceneSuggestionStrategy());
    // enable loading other catalog versions dynamically
    catalog.setVersionManager(new MavenVersionManager());
    // enable caching
    catalog.enableCache();
    if (downloadVersion) {
        String catalogVersion = catalog.getCatalogVersion();
        String version = findCamelVersion(project);
        if (version != null && !version.equals(catalogVersion)) {
            // the project uses a different Camel version so attempt to load it
            getLog().info("Downloading Camel version: " + version);
            boolean loaded = catalog.loadVersion(version);
            if (!loaded) {
                getLog().warn("Error downloading Camel version: " + version);
            }
        }
    }
    // if using the same version as the camel-maven-plugin we must still load it
    if (catalog.getLoadedVersion() == null) {
        catalog.loadVersion(catalog.getCatalogVersion());
    }
    if (catalog.getLoadedVersion() != null) {
        getLog().info("Using Camel version: " + catalog.getLoadedVersion());
    } else {
        // force load version from the camel-maven-plugin
        getLog().info("Using Camel version: " + catalog.getCatalogVersion());
    }
    List<CamelEndpointDetails> endpoints = new ArrayList<>();
    List<CamelSimpleExpressionDetails> simpleExpressions = new ArrayList<>();
    Set<File> javaFiles = new LinkedHashSet<File>();
    Set<File> xmlFiles = new LinkedHashSet<File>();
    // find all java route builder classes
    if (includeJava) {
        List list = project.getCompileSourceRoots();
        for (Object obj : list) {
            String dir = (String) obj;
            findJavaFiles(new File(dir), javaFiles);
        }
        if (includeTest) {
            list = project.getTestCompileSourceRoots();
            for (Object obj : list) {
                String dir = (String) obj;
                findJavaFiles(new File(dir), javaFiles);
            }
        }
    }
    // find all xml routes
    if (includeXml) {
        List list = project.getResources();
        for (Object obj : list) {
            Resource dir = (Resource) obj;
            findXmlFiles(new File(dir.getDirectory()), xmlFiles);
        }
        if (includeTest) {
            list = project.getTestResources();
            for (Object obj : list) {
                Resource dir = (Resource) obj;
                findXmlFiles(new File(dir.getDirectory()), xmlFiles);
            }
        }
    }
    for (File file : javaFiles) {
        if (matchFile(file)) {
            try {
                List<CamelEndpointDetails> fileEndpoints = new ArrayList<>();
                List<CamelSimpleExpressionDetails> fileSimpleExpressions = new ArrayList<>();
                List<String> unparsable = new ArrayList<>();
                // parse the java source code and find Camel RouteBuilder classes
                String fqn = file.getPath();
                String baseDir = ".";
                JavaType out = Roaster.parse(file);
                // we should only parse java classes (not interfaces and enums etc)
                if (out != null && out instanceof JavaClassSource) {
                    JavaClassSource clazz = (JavaClassSource) out;
                    RouteBuilderParser.parseRouteBuilderEndpoints(clazz, baseDir, fqn, fileEndpoints, unparsable, includeTest);
                    RouteBuilderParser.parseRouteBuilderSimpleExpressions(clazz, baseDir, fqn, fileSimpleExpressions);
                    // add what we found in this file to the total list
                    endpoints.addAll(fileEndpoints);
                    simpleExpressions.addAll(fileSimpleExpressions);
                    // was there any unparsable?
                    if (logUnparseable && !unparsable.isEmpty()) {
                        for (String uri : unparsable) {
                            getLog().warn("Cannot parse endpoint uri " + uri + " in java file " + file);
                        }
                    }
                }
            } catch (Exception e) {
                getLog().warn("Error parsing java file " + file + " code due " + e.getMessage(), e);
            }
        }
    }
    for (File file : xmlFiles) {
        if (matchFile(file)) {
            try {
                List<CamelEndpointDetails> fileEndpoints = new ArrayList<>();
                List<CamelSimpleExpressionDetails> fileSimpleExpressions = new ArrayList<>();
                // parse the xml source code and find Camel routes
                String fqn = file.getPath();
                String baseDir = ".";
                InputStream is = new FileInputStream(file);
                XmlRouteParser.parseXmlRouteEndpoints(is, baseDir, fqn, fileEndpoints);
                is.close();
                // need a new stream
                is = new FileInputStream(file);
                XmlRouteParser.parseXmlRouteSimpleExpressions(is, baseDir, fqn, fileSimpleExpressions);
                is.close();
                // add what we found in this file to the total list
                endpoints.addAll(fileEndpoints);
                simpleExpressions.addAll(fileSimpleExpressions);
            } catch (Exception e) {
                getLog().warn("Error parsing xml file " + file + " code due " + e.getMessage(), e);
            }
        }
    }
    int endpointErrors = 0;
    int unknownComponents = 0;
    int incapableErrors = 0;
    for (CamelEndpointDetails detail : endpoints) {
        getLog().debug("Validating endpoint: " + detail.getEndpointUri());
        EndpointValidationResult result = catalog.validateEndpointProperties(detail.getEndpointUri(), ignoreLenientProperties);
        boolean ok = result.isSuccess();
        if (!ok && ignoreUnknownComponent && result.getUnknownComponent() != null) {
            // if we failed due unknown component then be okay if we should ignore that
            unknownComponents++;
            ok = true;
        }
        if (!ok && ignoreIncapable && result.getIncapable() != null) {
            // if we failed due incapable then be okay if we should ignore that
            incapableErrors++;
            ok = true;
        }
        if (!ok) {
            if (result.getUnknownComponent() != null) {
                unknownComponents++;
            } else if (result.getIncapable() != null) {
                incapableErrors++;
            } else {
                endpointErrors++;
            }
            StringBuilder sb = new StringBuilder();
            sb.append("Endpoint validation error at: ");
            if (detail.getClassName() != null && detail.getLineNumber() != null) {
                // this is from java code
                sb.append(detail.getClassName());
                if (detail.getMethodName() != null) {
                    sb.append(".").append(detail.getMethodName());
                }
                sb.append("(").append(asSimpleClassName(detail.getClassName())).append(".java:");
                sb.append(detail.getLineNumber()).append(")");
            } else if (detail.getLineNumber() != null) {
                // this is from xml
                String fqn = stripRootPath(asRelativeFile(detail.getFileName()));
                if (fqn.endsWith(".xml")) {
                    fqn = fqn.substring(0, fqn.length() - 4);
                    fqn = asPackageName(fqn);
                }
                sb.append(fqn);
                sb.append("(").append(asSimpleClassName(fqn)).append(".xml:");
                sb.append(detail.getLineNumber()).append(")");
            } else {
                sb.append(detail.getFileName());
            }
            sb.append("\n\n");
            String out = result.summaryErrorMessage(false);
            sb.append(out);
            sb.append("\n\n");
            getLog().warn(sb.toString());
        } else if (showAll) {
            StringBuilder sb = new StringBuilder();
            sb.append("Endpoint validation passsed at: ");
            if (detail.getClassName() != null && detail.getLineNumber() != null) {
                // this is from java code
                sb.append(detail.getClassName());
                if (detail.getMethodName() != null) {
                    sb.append(".").append(detail.getMethodName());
                }
                sb.append("(").append(asSimpleClassName(detail.getClassName())).append(".java:");
                sb.append(detail.getLineNumber()).append(")");
            } else if (detail.getLineNumber() != null) {
                // this is from xml
                String fqn = stripRootPath(asRelativeFile(detail.getFileName()));
                if (fqn.endsWith(".xml")) {
                    fqn = fqn.substring(0, fqn.length() - 4);
                    fqn = asPackageName(fqn);
                }
                sb.append(fqn);
                sb.append("(").append(asSimpleClassName(fqn)).append(".xml:");
                sb.append(detail.getLineNumber()).append(")");
            } else {
                sb.append(detail.getFileName());
            }
            sb.append("\n");
            sb.append("\n\t").append(result.getUri());
            sb.append("\n\n");
            getLog().info(sb.toString());
        }
    }
    String endpointSummary;
    if (endpointErrors == 0) {
        int ok = endpoints.size() - endpointErrors - incapableErrors - unknownComponents;
        endpointSummary = String.format("Endpoint validation success: (%s = passed, %s = invalid, %s = incapable, %s = unknown components)", ok, endpointErrors, incapableErrors, unknownComponents);
    } else {
        int ok = endpoints.size() - endpointErrors - incapableErrors - unknownComponents;
        endpointSummary = String.format("Endpoint validation error: (%s = passed, %s = invalid, %s = incapable, %s = unknown components)", ok, endpointErrors, incapableErrors, unknownComponents);
    }
    if (endpointErrors > 0) {
        getLog().warn(endpointSummary);
    } else {
        getLog().info(endpointSummary);
    }
    int simpleErrors = 0;
    for (CamelSimpleExpressionDetails detail : simpleExpressions) {
        SimpleValidationResult result;
        boolean predicate = detail.isPredicate();
        if (predicate) {
            getLog().debug("Validating simple predicate: " + detail.getSimple());
            result = catalog.validateSimplePredicate(detail.getSimple());
        } else {
            getLog().debug("Validating simple expression: " + detail.getSimple());
            result = catalog.validateSimpleExpression(detail.getSimple());
        }
        if (!result.isSuccess()) {
            simpleErrors++;
            StringBuilder sb = new StringBuilder();
            sb.append("Simple validation error at: ");
            if (detail.getClassName() != null && detail.getLineNumber() != null) {
                // this is from java code
                sb.append(detail.getClassName());
                if (detail.getMethodName() != null) {
                    sb.append(".").append(detail.getMethodName());
                }
                sb.append("(").append(asSimpleClassName(detail.getClassName())).append(".java:");
                sb.append(detail.getLineNumber()).append(")");
            } else if (detail.getLineNumber() != null) {
                // this is from xml
                String fqn = stripRootPath(asRelativeFile(detail.getFileName()));
                if (fqn.endsWith(".xml")) {
                    fqn = fqn.substring(0, fqn.length() - 4);
                    fqn = asPackageName(fqn);
                }
                sb.append(fqn);
                sb.append("(").append(asSimpleClassName(fqn)).append(".xml:");
                sb.append(detail.getLineNumber()).append(")");
            } else {
                sb.append(detail.getFileName());
            }
            sb.append("\n");
            String[] lines = result.getError().split("\n");
            for (String line : lines) {
                sb.append("\n\t").append(line);
            }
            sb.append("\n");
            getLog().warn(sb.toString());
        } else if (showAll) {
            StringBuilder sb = new StringBuilder();
            sb.append("Simple validation passed at: ");
            if (detail.getClassName() != null && detail.getLineNumber() != null) {
                // this is from java code
                sb.append(detail.getClassName());
                if (detail.getMethodName() != null) {
                    sb.append(".").append(detail.getMethodName());
                }
                sb.append("(").append(asSimpleClassName(detail.getClassName())).append(".java:");
                sb.append(detail.getLineNumber()).append(")");
            } else if (detail.getLineNumber() != null) {
                // this is from xml
                String fqn = stripRootPath(asRelativeFile(detail.getFileName()));
                if (fqn.endsWith(".xml")) {
                    fqn = fqn.substring(0, fqn.length() - 4);
                    fqn = asPackageName(fqn);
                }
                sb.append(fqn);
                sb.append("(").append(asSimpleClassName(fqn)).append(".xml:");
                sb.append(detail.getLineNumber()).append(")");
            } else {
                sb.append(detail.getFileName());
            }
            sb.append("\n");
            sb.append("\n\t").append(result.getSimple());
            sb.append("\n\n");
            getLog().info(sb.toString());
        }
    }
    String simpleSummary;
    if (simpleErrors == 0) {
        int ok = simpleExpressions.size() - simpleErrors;
        simpleSummary = String.format("Simple validation success: (%s = passed, %s = invalid)", ok, simpleErrors);
    } else {
        int ok = simpleExpressions.size() - simpleErrors;
        simpleSummary = String.format("Simple validation error: (%s = passed, %s = invalid)", ok, simpleErrors);
    }
    if (failOnError && (endpointErrors > 0 || simpleErrors > 0)) {
        throw new MojoExecutionException(endpointSummary + "\n" + simpleSummary);
    }
    if (simpleErrors > 0) {
        getLog().warn(simpleSummary);
    } else {
        getLog().info(simpleSummary);
    }
}
Also used : MavenVersionManager(org.apache.camel.catalog.maven.MavenVersionManager) CamelEndpointDetails(org.apache.camel.parser.model.CamelEndpointDetails) LinkedHashSet(java.util.LinkedHashSet) ArrayList(java.util.ArrayList) LuceneSuggestionStrategy(org.apache.camel.catalog.lucene.LuceneSuggestionStrategy) ArrayList(java.util.ArrayList) List(java.util.List) SimpleValidationResult(org.apache.camel.catalog.SimpleValidationResult) DefaultCamelCatalog(org.apache.camel.catalog.DefaultCamelCatalog) CamelCatalog(org.apache.camel.catalog.CamelCatalog) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Resource(org.apache.maven.model.Resource) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) FileInputStream(java.io.FileInputStream) JavaType(org.jboss.forge.roaster.model.JavaType) EndpointValidationResult(org.apache.camel.catalog.EndpointValidationResult) DefaultCamelCatalog(org.apache.camel.catalog.DefaultCamelCatalog) CamelSimpleExpressionDetails(org.apache.camel.parser.model.CamelSimpleExpressionDetails) File(java.io.File)

Example 83 with MojoFailureException

use of org.apache.maven.plugin.MojoFailureException in project camel by apache.

the class BomGeneratorMojo method execute.

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        DependencyManagement mng = project.getDependencyManagement();
        List<Dependency> filteredDependencies = enhance(filter(mng.getDependencies()));
        Set<String> externallyManagedDependencies = getExternallyManagedDependencies();
        checkConflictsWithExternalBoms(filteredDependencies, externallyManagedDependencies);
        Document pom = loadBasePom();
        // transform
        overwriteDependencyManagement(pom, filteredDependencies);
        writePom(pom);
    } catch (MojoFailureException ex) {
        throw ex;
    } catch (MojoExecutionException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new MojoExecutionException("Cannot generate the output BOM file", ex);
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Dependency(org.apache.maven.model.Dependency) Document(org.w3c.dom.Document) DependencyManagement(org.apache.maven.model.DependencyManagement) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Example 84 with MojoFailureException

use of org.apache.maven.plugin.MojoFailureException in project camel by apache.

the class PackageModelMojo method execute.

/**
     * Execute goal.
     *
     * @throws org.apache.maven.plugin.MojoExecutionException execution of the main class or one of the
     *                 threads it generated failed.
     * @throws org.apache.maven.plugin.MojoFailureException something bad happened...
     */
public void execute() throws MojoExecutionException, MojoFailureException {
    File camelMetaDir = new File(outDir, "META-INF/services/org/apache/camel/");
    Set<File> jsonFiles = new TreeSet<File>();
    // find all json files in camel-core
    if (buildDir != null && buildDir.isDirectory()) {
        File target = new File(buildDir, "classes/org/apache/camel/model");
        PackageHelper.findJsonFiles(target, jsonFiles, new PackageHelper.CamelComponentsModelFilter());
    }
    File outFile = new File(camelMetaDir, "model.properties");
    try {
        camelMetaDir.mkdirs();
        Properties properties = new Properties();
        properties.store(new FileWriter(outFile), "Generated by camel-package-maven-plugin");
        List<String> models = new ArrayList<String>();
        // sort the names
        for (File file : jsonFiles) {
            String name = file.getName();
            if (name.endsWith(".json")) {
                // strip out .json from the name
                String modelName = name.substring(0, name.length() - 5);
                models.add(modelName);
            }
        }
        Collections.sort(models);
        FileOutputStream fos = new FileOutputStream(outFile, true);
        for (String name : models) {
            fos.write(name.getBytes());
            fos.write("\n".getBytes());
        }
        fos.close();
        getLog().info("Generated " + outFile + " containing " + models.size() + " Camel models");
    } catch (IOException e) {
        throw new MojoFailureException("Error writing to file " + outFile);
    }
}
Also used : FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) MojoFailureException(org.apache.maven.plugin.MojoFailureException) IOException(java.io.IOException) Properties(java.util.Properties) TreeSet(java.util.TreeSet) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 85 with MojoFailureException

use of org.apache.maven.plugin.MojoFailureException in project camel by apache.

the class PrepareCatalogKarafMojo method executeDataFormats.

protected void executeDataFormats(Set<String> features) throws MojoExecutionException, MojoFailureException {
    getLog().info("Copying all Camel dataformat json descriptors");
    // lets use sorted set/maps
    Set<File> jsonFiles = new TreeSet<File>();
    Set<File> dataFormatFiles = new TreeSet<File>();
    // find all data formats from the components directory
    if (componentsDir != null && componentsDir.isDirectory()) {
        File[] dataFormats = componentsDir.listFiles();
        if (dataFormats != null) {
            for (File dir : dataFormats) {
                if (dir.isDirectory() && !"target".equals(dir.getName())) {
                    // skip camel-spring-dm
                    if (dir.isDirectory() && "camel-spring-dm".equals(dir.getName())) {
                        continue;
                    }
                    // the directory must be in the list of known features
                    if (!features.contains(dir.getName())) {
                        continue;
                    }
                    File target = new File(dir, "target/classes");
                    findDataFormatFilesRecursive(target, jsonFiles, dataFormatFiles, new CamelDataFormatsFileFilter());
                }
            }
        }
    }
    if (coreDir != null && coreDir.isDirectory()) {
        File target = new File(coreDir, "target/classes");
        findDataFormatFilesRecursive(target, jsonFiles, dataFormatFiles, new CamelDataFormatsFileFilter());
    }
    getLog().info("Found " + dataFormatFiles.size() + " dataformat.properties files");
    getLog().info("Found " + jsonFiles.size() + " dataformat json files");
    // make sure to create out dir
    dataFormatsOutDir.mkdirs();
    for (File file : jsonFiles) {
        File to = new File(dataFormatsOutDir, file.getName());
        try {
            copyFile(file, to);
        } catch (IOException e) {
            throw new MojoFailureException("Cannot copy file from " + file + " -> " + to, e);
        }
    }
    File all = new File(dataFormatsOutDir, "../dataformats.properties");
    try {
        FileOutputStream fos = new FileOutputStream(all, false);
        String[] names = dataFormatsOutDir.list();
        List<String> dataFormats = new ArrayList<String>();
        // sort the names
        for (String name : names) {
            if (name.endsWith(".json")) {
                // strip out .json from the name
                String dataFormatName = name.substring(0, name.length() - 5);
                dataFormats.add(dataFormatName);
            }
        }
        Collections.sort(dataFormats);
        for (String name : dataFormats) {
            fos.write(name.getBytes());
            fos.write("\n".getBytes());
        }
        fos.close();
    } catch (IOException e) {
        throw new MojoFailureException("Error writing to file " + all);
    }
}
Also used : TreeSet(java.util.TreeSet) FileOutputStream(java.io.FileOutputStream) MojoFailureException(org.apache.maven.plugin.MojoFailureException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) File(java.io.File)

Aggregations

MojoFailureException (org.apache.maven.plugin.MojoFailureException)157 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)94 File (java.io.File)93 IOException (java.io.IOException)91 ArrayList (java.util.ArrayList)50 TreeSet (java.util.TreeSet)33 FileInputStream (java.io.FileInputStream)32 FileOutputStream (java.io.FileOutputStream)21 List (java.util.List)21 Map (java.util.Map)21 MavenProject (org.apache.maven.project.MavenProject)18 Set (java.util.Set)15 MalformedURLException (java.net.MalformedURLException)14 HashMap (java.util.HashMap)13 HashSet (java.util.HashSet)13 InputStream (java.io.InputStream)12 URLClassLoader (java.net.URLClassLoader)12 Matcher (java.util.regex.Matcher)12 Artifact (org.apache.maven.artifact.Artifact)12 AbstractMojo (org.apache.maven.plugin.AbstractMojo)12