Example usage for org.apache.maven.plugin.logging Log error

List of usage examples for org.apache.maven.plugin.logging Log error

Introduction

In this page you can find the example usage for org.apache.maven.plugin.logging Log error.

Prototype

void error(Throwable error);

Source Link

Document

Send an exception to the user in the error error level.
The stack trace for this exception will be output when this error level is enabled.

Usage

From source file:de.tarent.maven.plugins.pkg.packager.IpkPackager.java

License:Open Source License

/**
 * Validates arguments and test tools.//from   w w  w.ja va2  s.  co  m
 * 
 * @throws MojoExecutionException
 */
public void checkEnvironment(Log l, WorkspaceSession workspaceSession) throws MojoExecutionException {
    TargetConfiguration targetConfiguration = workspaceSession.getTargetConfiguration();

    boolean error = false;

    l.info("Maintainer               : " + targetConfiguration.getMaintainer());

    if (targetConfiguration.getMaintainer() == null) {
        l.error("The maintainer field of the distro configuration is not set, however this is mandatory for IPK packaging!");
        error = true;
    }

    /*
     * The ipkg-build tool, needed by this class is delivered within this
     * package in the ipkg-utils-050831.tar.gz archive. It will be extracted
     * to a temporary location and deleted as soon as the vm exits.
     */

    ArchiveFile IpkUtilsGZip;
    try {
        IpkUtilsGZip = new GZipTarFile(
                new File(IpkPackager.class.getResource("ipkg-utils-050831.tar.gz").toURI()));
    } catch (URISyntaxException ex) {
        throw new MojoExecutionException("Location for Zip file is malformed.", ex);
    }

    IPKGBUILD = Utils.getFileFromArchive(IpkUtilsGZip, "ipkg-utils-050831/ipkg-build");
    // The tool needs to be executable
    IPKGBUILD.setExecutable(true);

    if (error) {
        throw new MojoExecutionException("Aborting due to earlier errors.");
    }
}

From source file:de.tarent.maven.plugins.pkg.Utils.java

License:Open Source License

/**
 * Returns the default Distro to use for a certain TargetConfiguration.
 * //from w  w  w  . j  a va  2  s . c om
 * @param configuration
 * @return
 * @throws MojoExecutionException
 */
public static String getDefaultDistro(String targetString, List<TargetConfiguration> targetConfigurations,
        Log l) throws MojoExecutionException {
    String distro = null;
    TargetConfiguration target = Utils.getTargetConfigurationFromString(targetString, targetConfigurations);

    if (target.getDefaultDistro() != null) {
        distro = target.getDefaultDistro();
        l.info("Default distribution is set to \"" + distro + "\".");
    } else
        switch (target.getDistros().size()) {
        case 0:
            throw new MojoExecutionException("No distros defined for configuration " + targetString);
        case 1:
            distro = (String) target.getDistros().iterator().next();
            l.info(String.format("Only one distro defined, using '%s' as default", distro));
            break;
        default:
            String m = "No default configuration given for distro '" + targetString
                    + "', and more than one distro is supported. Please provide one.";
            l.error(m);
            throw new MojoExecutionException(m);
        }
    return distro;
}

From source file:de.thetaphi.forbiddenapis.AbstractCheckMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    final Log log = getLog();

    if (skip) {/*  ww  w .  j av a  2s.c om*/
        log.info("Skipping forbidden-apis checks.");
        return;
    }

    // In multi-module projects, one may want to configure the plugin in the parent/root POM.
    // However, it should not be executed for this type of POMs.
    if ("pom".equals(packaging)) {
        log.info("Skipping execution for packaging \"" + packaging + "\"");
        return;
    }

    // set default param:
    if (includes == null)
        includes = new String[] { "**/*.class" };

    final URL[] urls;
    try {
        final List<String> cp = getClassPathElements();
        urls = new URL[cp.size()];
        int i = 0;
        for (final String cpElement : cp) {
            urls[i++] = new File(cpElement).toURI().toURL();
        }
        assert i == urls.length;
        if (log.isDebugEnabled())
            log.debug("Compile Classpath: " + Arrays.toString(urls));
    } catch (MalformedURLException e) {
        throw new MojoExecutionException("Failed to build classpath: " + e);
    }

    URLClassLoader urlLoader = null;
    final ClassLoader loader = (urls.length > 0)
            ? (urlLoader = URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader()))
            : ClassLoader.getSystemClassLoader();

    try {
        final EnumSet<Checker.Option> options = EnumSet.noneOf(Checker.Option.class);
        if (internalRuntimeForbidden)
            options.add(INTERNAL_RUNTIME_FORBIDDEN);
        if (failOnMissingClasses)
            options.add(FAIL_ON_MISSING_CLASSES);
        if (failOnViolation)
            options.add(FAIL_ON_VIOLATION);
        if (failOnUnresolvableSignatures)
            options.add(FAIL_ON_UNRESOLVABLE_SIGNATURES);
        final Checker checker = new Checker(loader, options) {
            @Override
            protected void logError(String msg) {
                log.error(msg);
            }

            @Override
            protected void logWarn(String msg) {
                log.warn(msg);
            }

            @Override
            protected void logInfo(String msg) {
                log.info(msg);
            }
        };

        if (!checker.isSupportedJDK) {
            final String msg = String.format(Locale.ENGLISH,
                    "Your Java runtime (%s %s) is not supported by the forbiddenapis MOJO. Please run the checks with a supported JDK!",
                    System.getProperty("java.runtime.name"), System.getProperty("java.runtime.version"));
            if (failOnUnsupportedJava) {
                throw new MojoExecutionException(msg);
            } else {
                log.warn(msg);
                return;
            }
        }

        if (suppressAnnotations != null) {
            for (String a : suppressAnnotations) {
                checker.addSuppressAnnotation(a);
            }
        }

        log.info("Scanning for classes to check...");
        final File classesDirectory = getClassesDirectory();
        if (!classesDirectory.exists()) {
            log.warn("Classes directory does not exist, forbiddenapis check skipped: " + classesDirectory);
            return;
        }
        final DirectoryScanner ds = new DirectoryScanner();
        ds.setBasedir(classesDirectory);
        ds.setCaseSensitive(true);
        ds.setIncludes(includes);
        ds.setExcludes(excludes);
        ds.addDefaultExcludes();
        ds.scan();
        final String[] files = ds.getIncludedFiles();
        if (files.length == 0) {
            log.warn(String.format(Locale.ENGLISH,
                    "No classes found in '%s' (includes=%s, excludes=%s), forbiddenapis check skipped.",
                    classesDirectory.toString(), Arrays.toString(includes), Arrays.toString(excludes)));
            return;
        }

        try {
            final String sig = (signatures != null) ? signatures.trim() : null;
            if (sig != null && sig.length() != 0) {
                log.info("Reading inline API signatures...");
                checker.parseSignaturesString(sig);
            }
            if (bundledSignatures != null) {
                String targetVersion = getTargetVersion();
                if ("".equals(targetVersion))
                    targetVersion = null;
                if (targetVersion == null) {
                    log.warn("The 'targetVersion' parameter or '${maven.compiler.target}' property is missing. "
                            + "Trying to read bundled JDK signatures without compiler target. "
                            + "You have to explicitely specify the version in the resource name.");
                }
                for (String bs : bundledSignatures) {
                    log.info("Reading bundled API signatures: " + bs);
                    checker.parseBundledSignatures(bs, targetVersion);
                }
            }
            if (signaturesFiles != null)
                for (final File f : signaturesFiles) {
                    log.info("Reading API signatures: " + f);
                    checker.parseSignaturesFile(new FileInputStream(f));
                }
        } catch (IOException ioe) {
            throw new MojoExecutionException("IO problem while reading files with API signatures: " + ioe);
        } catch (ParseException pe) {
            throw new MojoExecutionException("Parsing signatures failed: " + pe.getMessage());
        }

        if (checker.hasNoSignatures()) {
            if (failOnUnresolvableSignatures) {
                throw new MojoExecutionException(
                        "No API signatures found; use parameters 'signatures', 'bundledSignatures', and/or 'signaturesFiles' to define those!");
            } else {
                log.info("Skipping execution because no API signatures are available.");
                return;
            }
        }

        log.info("Loading classes to check...");
        try {
            for (String f : files) {
                checker.addClassToCheck(new FileInputStream(new File(classesDirectory, f)));
            }
        } catch (IOException ioe) {
            throw new MojoExecutionException("Failed to load one of the given class files: " + ioe);
        }

        log.info("Scanning for API signatures and dependencies...");
        try {
            checker.run();
        } catch (ForbiddenApiException fae) {
            throw new MojoFailureException(fae.getMessage());
        }
    } finally {
        // Java 7 supports closing URLClassLoader, so check for Closeable interface:
        if (urlLoader instanceof Closeable)
            try {
                ((Closeable) urlLoader).close();
            } catch (IOException ioe) {
                // ignore
            }
    }
}

From source file:fr.husta.maven.plugin.ReleaseProjectVersionMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException {
    issueManagement = project.getIssueManagement();
    Log tempLog = getLog();
    if (issueManagement != null) {
        tempLog.debug("IssueManagement -> system = " + issueManagement.getSystem());
        tempLog.debug("IssueManagement -> url = " + issueManagement.getUrl());

        final String ISSUE_MNGT_MANTIS = "Mantis";
        if (issueManagement.getSystem() != null
                && ISSUE_MNGT_MANTIS.equals(issueManagement.getSystem()) == false) {
            tempLog.warn("IssueManagement -> system should be set to '" + ISSUE_MNGT_MANTIS + "'.");
        }//from   w  w  w  .j a  v a 2 s .co m
    }

    try {
        // connection to Mantis SOAP API
        MantisConnectPortType portType = MantisUtils.createConnector(getMantisSoapApiUrl());
        MantisConnector mantisConnector = new MantisConnector(portType);

        tempLog.debug("projectName = '" + projectName + "'");

        // find ProjectId from Name
        BigInteger projectId = mantisConnector.getProjectIdByName(login, password, projectName);

        tempLog.info("Project " + projectName + " has ID=" + projectId);

        String tempCurrentSnapshot = currentSnapshot;
        if (versionPrefix != null) {
            tempCurrentSnapshot = versionPrefix + "-" + tempCurrentSnapshot;
        }
        String tempReleaseVersion = releaseVersion;
        if (versionPrefix != null) {
            tempReleaseVersion = versionPrefix + "-" + tempReleaseVersion;
        }
        tempLog.info("Rename Version '" + tempCurrentSnapshot + "' to " + tempReleaseVersion);
        mantisConnector.renameVersion(tempLog, login, password, projectId, tempCurrentSnapshot,
                tempReleaseVersion);
        tempLog.info("Renamed Version '" + tempCurrentSnapshot + "' to " + tempReleaseVersion);
        // call to web service method
        String tempDevelopmentVersion = developmentVersion;
        if (versionPrefix != null) {
            tempDevelopmentVersion = versionPrefix + "-" + tempDevelopmentVersion;
        }
        tempLog.info("Create Version '" + tempDevelopmentVersion + "' in Mantis, releaseFlag=" + false);
        mantisConnector.addProjectVersion(login, password, projectId, tempDevelopmentVersion, false);
        tempLog.info("Version '" + tempDevelopmentVersion + "' created in Mantis, releaseFlag=" + false);

    } catch (ServiceException e) {
        tempLog.error(e.getMessage());
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (RuntimeException e) {
        tempLog.error(e.getMessage());
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (RemoteException e) {
        tempLog.error(e.getMessage());
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

From source file:fr.jetoile.hadoopunit.HadoopBootstrapRemoteUtils.java

License:Apache License

public String getHadoopUnitPath(String hadoopUnitPath, Log log) {
    String hadoopUnitHome = System.getenv("HADOOP_UNIT_HOME");
    String res = "";
    if (hadoopUnitHome != null) {
        res = hadoopUnitHome;//w w  w .  ja v a 2s . c  o m
        log.info("overriding property hadoopUnitPath with system environment variable" + hadoopUnitHome);
    } else {
        res = hadoopUnitPath;
    }
    log.info("is going to use:" + res);

    if (hadoopUnitPath == null) {
        log.error("hadoopUnitPath or HADOOP_UNIT_HOME should be set");
    }
    return res;
}

From source file:info.naiv.lab.java.jmt.enumgen.maven.plugin.EnumGeneratorMojo.java

License:Open Source License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    final Log log = getLog();
    try {//  w  ww  . j a  v  a  2s.  c o m
        final Path path = buildOutputDirectory();
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }

        final Charset charset = Charset.forName(encoding);
        final CompiledTemplate clsTempl = getClassTemplate();
        final EnumGenerator builder = new EnumGenerator(packageName, clsTempl);
        final Properties props = getProperties();
        if (!props.stringPropertyNames().isEmpty()) {
            log.info("properties found. ");
            CodeData code = builder.propertiesToCode(propertiesSourceEnumName, propertiesSourceFieldPrefix,
                    props);
            log.info("generate " + code.getName());
            writeCode(path, code, charset);
        }
        if (isNotBlank(enumSourceCsv)) {
            log.info("enumSourceCsv found. ");
            Multimap<String, EnumEntry> entries = EnumSource.createEnumEntries(Paths.get(enumSourceCsv),
                    charset, delimiter);
            for (String key : entries.keySet()) {
                CodeData code = builder.entriesToCode(key, entries.get(key));
                log.info("generate " + code.getName());
                writeCode(path, code, charset);
            }
        }
    } catch (IOException ex) {
        log.error(ex);
        throw new MojoFailureException("bean creation failed. ", ex);
    }
}

From source file:info.naiv.lab.java.jmt.pojogen.maven.plugin.PojoGeneratorMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    final Log log = getLog();
    try {//  w ww.ja va2  s  . c  o  m
        loadExternalDrivers(log);

        final Path path = buildOutputDirectory();
        if (Files.exists(path)) {
            // ???????.
            log.info(path + " is exists.");
            return;
        }

        final DataSource dataSource = new DriverManagerDataSource(url, username, password);
        final Charset charset = Charset.forName(encoding);
        final CompiledTemplate clsTempl = getClassTemplate();
        final PojoGenerator builder = new PojoGenerator(schema, packageName, classNameSuffix, clsTempl);
        final AntPathMatcher matcher = new AntPathMatcher();

        Files.createDirectories(path);
        JdbcUtils.extractDatabaseMetaData(dataSource, new DatabaseMetaDataCallback() {
            @Override
            public Object processMetaData(DatabaseMetaData dbmd) throws SQLException, MetaDataAccessException {
                List<String> tableNames = getTableNames(dbmd);
                for (String tableName : tableNames) {
                    if (isExcludeTarget(tableName)) {
                        log.info(tableName + " is exclude.");
                        continue;
                    }
                    CodeData code = builder.tableToBean(dbmd, tableName);
                    writeCode(path, code);
                }
                return null;
            }

            protected boolean isExcludeTarget(final String tableName) {
                if (isEmpty(excludeTables)) {
                    return false;
                }
                return Misc.contains(excludeTables, new Predicate1<String>() {
                    @Override
                    public boolean test(String obj) {
                        return matcher.match(obj, tableName);
                    }
                });
            }

            protected void writeCode(Path dir, CodeData code) {
                try {
                    Path file = dir.resolve(code.getClassName() + ".java");
                    try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
                        writer.append(code.getCode());
                    }
                } catch (IOException ex) {
                    log.error(ex);
                }
            }

            protected List<String> getTableNames(DatabaseMetaData dbmd) throws SQLException {
                List<String> tableNames = new ArrayList<>();
                String sch = schema;
                if ("@null".equals(sch)) {
                    sch = null;
                }
                try (ResultSet rs = dbmd.getTables(null, sch, "%", new String[] { "TABLE", "VIEW" })) {
                    while (rs.next()) {
                        tableNames.add(rs.getString("TABLE_NAME"));
                    }
                }
                return tableNames;
            }
        });
    } catch (MetaDataAccessException | IOException | SQLException ex) {
        log.error(ex);
        throw new MojoFailureException("bean creation failed. ", ex);
    }

}

From source file:io.cloudslang.lang.enforcer.SpringCleansingRule.java

License:Open Source License

private void applyForJavaSourcesInRoot(final String path, final Log log) throws EnforcerRuleException {
    Iterator<File> fileIterator = iterateFiles(new File(path), new String[] { JAVA }, true);
    while (fileIterator.hasNext()) {
        File source = fileIterator.next();

        if (isRegularFile(source.toPath(), NOFOLLOW_LINKS)) {
            if (log.isDebugEnabled()) {
                log.debug(format(STARTED_SCANNING_ORG_SPRINGFRAMEWORK, source.getAbsolutePath()));
            }//from   ww w  .  j  av  a 2  s.com
            try {
                String contents = readFileToString(source, UTF_8.displayName());
                if (isSpringConfigurationAnnotatedClass(contents)) {
                    log.info(format("Skipping verification for Spring configuration class in file '%s'",
                            source.getAbsolutePath()));
                    continue;
                }
                // At this point it is clear this is a regular Java class that is not a Spring Configuration class
                // and just validate we don't have org.springframework in it

                findMatchesUsingPattern(source, log, contents, patternImport,
                        FOUND_USAGE_OF_ORG_SPRINGFRAMEWORK_IN_IMPORT_AT_LINE);
                findMatchesUsingPattern(source, log, contents, patternCodeLine,
                        FOUND_USAGE_OF_ORG_SPRINGFRAMEWORK_IN_CODE_FRAGMENT_AT_LINE);
            } catch (IOException ignore) {
                log.error(format("Could not process file '%s'", source));
            }
            if (log.isDebugEnabled()) {
                log.debug(format(FINISHED_SCANNING_ORG_SPRINGFRAMEWORK, source.getAbsolutePath()));
            }
        }
    }
}

From source file:net.roboconf.maven.MavenPluginUtils.java

License:Apache License

/**
 * Formats a Roboconf errors and outputs it in the logs.
 * @param error an error/*from  w w w .j a  va 2  s.  co  m*/
 * @param log the Maven logger
 * @return a string builder with the output
 */
public static StringBuilder formatErrors(Collection<? extends RoboconfError> errors, Log log) {

    StringBuilder result = new StringBuilder();
    for (Map.Entry<RoboconfError, String> entry : RoboconfErrorHelpers.formatErrors(errors, null, true)
            .entrySet()) {
        if (entry.getKey().getErrorCode().getLevel() == ErrorLevel.WARNING)
            log.warn(entry.getValue());
        else
            log.error(entry.getValue());

        result.append(entry.getValue());
        result.append("\n");
    }

    return result;
}

From source file:net.roboconf.maven.MavenUtils.java

License:Apache License

/**
 * Formats a Roboconf errors and outputs it in the logs.
 * @param error an error/*from  w ww  . j  ava  2 s  .co m*/
 * @param log the Maven logger
 * @return a string builder with the output
 */
public static StringBuilder formatError(RoboconfError error, Log log) {

    StringBuilder sb = new StringBuilder();
    sb.append("[ ");
    sb.append(error.getErrorCode().getCategory().toString().toLowerCase());
    sb.append(" ] ");
    sb.append(error.getErrorCode().getMsg());
    if (!Utils.isEmptyOrWhitespaces(error.getDetails()))
        sb.append(" " + error.getDetails());

    if (!sb.toString().endsWith("."))
        sb.append(".");

    if (error instanceof ParsingError) {
        sb.append(" See ");
        sb.append(((ParsingError) error).getFile().getName());
        sb.append(", line ");
        sb.append(((ParsingError) error).getLine());
        sb.append(".");
    }

    if (error.getErrorCode().getLevel() == ErrorLevel.WARNING)
        log.warn(sb.toString());
    else
        log.error(sb.toString());

    return sb;
}