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

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

Introduction

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

Prototype

void warn(Throwable error);

Source Link

Document

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

Usage

From source file:com.redhat.victims.VictimsRule.java

License:Open Source License

/**
 * This is a helper method that processes a single result that 
 * has been executed. /* w  ww .j a  v a  2  s  .c  om*/
 * 
 * If any exceptions were thrown during execution they are inspected
 * to see if they indicate a vulnerable artifact. The result is also 
 * added to the cache for the current execution context.  
 * 
 * 
 * @param ctx - The execution context the result was generated under
 * @param result - The result to examine
 * @throws VictimsException
 * @throws VulnerableArtifactException
 * @throws EnforcerRuleException
 */
private void processResult(ExecutionContext ctx, Future<ArtifactStub> result)
        throws VictimsException, VulnerableArtifactException, EnforcerRuleException {

    VictimsResultCache cache = ctx.getCache();
    Log log = ctx.getLog();

    try {

        ArtifactStub checked = result.get();
        if (checked != null) {
            log.debug("[victims-enforcer] done: " + checked.getId());
            cache.add(checked.getId(), null);
        }

    } catch (InterruptedException e) {
        log.info(e.getMessage());

    } catch (ExecutionException e) {

        log.debug(e);
        Throwable cause = e.getCause();

        if (cause instanceof VulnerableArtifactException) {

            VulnerableArtifactException ve = (VulnerableArtifactException) cause;
            // cache vulnerable artifact
            cache.add(ve.getId(), ve.getVulnerabilites());

            // Log the error and rethrow in case a fatal error
            log.warn(ve.getLogMessage());
            throw ve;

        } else {
            throw new EnforcerRuleException(e.getCause().getMessage());
        }
    }
}

From source file:com.redhat.victims.VictimsRule.java

License:Open Source License

/**
 * Scan the supplied artifacts given the provided execution context. An
 * exception will be raised if a vulnerable artifact has been detected.
 * @param ctx//w  ww.ja va  2  s.c  om
 * @param artifacts
 * @throws EnforcerRuleException
 */
public void execute(ExecutionContext ctx, Set<Artifact> artifacts) throws EnforcerRuleException {

    VictimsResultCache cache = ctx.getCache();
    Log log = ctx.getLog();
    int cores = Runtime.getRuntime().availableProcessors();
    ExecutorService executor = null;
    ExecutorCompletionService<ArtifactStub> completionService = null;
    List<Future<ArtifactStub>> results = null;

    try {

        // Synchronize database with victims service
        try {
            updateDatabase(ctx);
        } catch (VictimsException e) {
            log.warn("Unable to update victims database! Your CVE records might be out of date.");
            log.debug(e.toString());
        }
        // Concurrently process each dependency 
        executor = Executors.newFixedThreadPool(cores);
        completionService = new ExecutorCompletionService<ArtifactStub>(executor);

        results = new ArrayList<Future<ArtifactStub>>();

        for (Artifact a : artifacts) {

            // Check if we've already inspected this dependency
            if (cache.exists(a.getId())) {

                HashSet<String> cves = cache.get(a.getId());
                log.debug("[victims-enforcer] cached: " + a.getId());
                if (!cves.isEmpty()) {

                    VulnerableArtifactException err = new VulnerableArtifactException(a, Settings.FINGERPRINT,
                            cves);
                    log.warn(err.getLogMessage());

                    if (err.isFatal(ctx)) {
                        throw new EnforcerRuleException(err.getErrorMessage());
                    }
                }
                continue;
            }

            // Not in cache process artifact
            results.add(completionService.submit(new VictimsCommand(ctx, a)));

            // Poll completion service for completed tasks to short circuit
            // on failure conditions.
            Future<ArtifactStub> result = completionService.poll();
            if (result != null) {
                try {
                    results.remove(result);
                    processResult(ctx, result);

                } catch (VulnerableArtifactException e) {

                    if (e.isFatal(ctx)) {
                        // Cancel other jobs
                        for (Future<ArtifactStub> f : results) {
                            f.cancel(true);
                        }
                        throw new EnforcerRuleException(e.getErrorMessage(), e);
                    }
                }
            }

        }
        executor.shutdown();

        // Process any remaining results. 
        for (Future<ArtifactStub> future : results) {
            processResult(ctx, future);
        }

    } catch (VulnerableArtifactException e) {
        // fatal exception
        if (e.isFatal(ctx)) {
            throw new EnforcerRuleException(e.getErrorMessage());
        }

    } catch (VictimsException e) {
        log.debug(e);
        throw new EnforcerRuleException(e.getMessage());

    } finally {

        if (executor != null) {
            executor.shutdownNow();

        }
    }
}

From source file:com.sixsq.slipstream.SlipStreamMojo.java

License:Apache License

public void execute() throws MojoExecutionException {

    Log log = getLog();

    fillInAndValidateParameters();/*from  w  w w.  java 2  s . com*/

    DeploymentController controller = new DeploymentController(slipstreamServerUri, server.getUsername(),
            server.getPassword());

    // Ensure that the output directory exists.
    File outputDirectory = new File(targetDirectory);
    if (!outputDirectory.mkdirs()) {
        log.error(String.format("unable to create output directory: %s", outputDirectory.getAbsolutePath()));
    }

    try {

        controller.checkServerResponds();
        controller.login();
        controller.checkLogin();

        for (String module : deploymentModuleNames) {
            try {

                controller.verifyModuleExists(module);
                log.info(String.format("Module: %s", module));

                URI runUri = controller.runModule(module);
                log.info(String.format("Run URI: %s", runUri.toString()));

                pollServerUntilDone(log, runUri, controller);

                List<URI> reportUris = controller.getReports(runUri);

                List<File> localFiles = new ArrayList<File>();

                for (URI uri : reportUris) {
                    File localFile = controller.downloadFile(uri, outputDirectory);
                    localFiles.add(localFile);
                }

                attachArtifacts(log, localFiles);

            } catch (MojoExecutionException e) {
                log.warn(String.format("Error while running module %s: %s", module, e.getMessage()));
            }
        }

    } finally {
        closeReliably(controller, log);
    }

}

From source file:com.slim.service.ValidateService.java

License:Apache License

/**
 * /* w  ww  .j a  v  a2  s . c  om*/
 * @param project
 * @param designerBinDir
 * @param outputDirectory
 * @param validationIgnoresFile
 * @param logger
 * @throws MojoExecutionException
 * @throws MojoFailureException
 */
public void validate(MavenProject project, String designerHome, String outputDirectory,
        String validationIgnoresFile, boolean checkUnusedGlobalVariables, Log logger)
        throws MojoExecutionException, MojoFailureException {
    String validateOutputFile = project.getBasedir().toString() + "\\" + outputDirectory + "\\"
            + "outValidate.txt";

    logger.info(" - DESIGNER_HOME : " + designerHome);
    logger.info(" - BASE_DIR : " + project.getBasedir().toString());
    logger.info(" - VALIDATE_OUTPUT_LOG : " + validateOutputFile);
    logger.info(" - IGNORE_FILE : " + validationIgnoresFile);

    boolean validated = true;

    Pattern pattern = preparePattern(project, designerHome, outputDirectory, validationIgnoresFile, logger);
    Pattern patternResult = Pattern.compile(".*Found.*errors.*and.*warnings.*");

    try {
        CommandUtils.createDirectoryIfNeeded(project.getBasedir().toString() + "\\" + outputDirectory, logger);

        Map<String, String> options = new HashMap<String, String>();
        if (checkUnusedGlobalVariables) {
            options.put(CommandUtils.U_OPTION,
                    project.getBasedir().toString() + "\\" + project.getArtifact().getArtifactId());
        } else {
            options.put(CommandUtils.STRING_VIDE,
                    project.getBasedir().toString() + "\\" + project.getArtifact().getArtifactId());
        }

        BufferedReader validateOutput = CommandUtils.executeCommand(logger, designerHome,
                CommandUtils.getValidateProjectBin(), options);

        BufferedWriter outLogStream = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(validateOutputFile)));
        outLogStream.append("#Log generated at " + new Date() + ".\n");

        String line = null;
        while ((line = validateOutput.readLine()) != null) {
            boolean ignored = false;
            String trimmedLine = line.trim();
            if (trimmedLine.length() == 0 || pattern.matcher(trimmedLine).matches()) {
                ignored = true;
            }
            if (!ignored) {
                validated = false;
                logger.warn(trimmedLine);
            }
            if (patternResult.matcher(line).matches()) {
                logger.info(line + "\n");
            }
            outLogStream.append(line + "\n");
        }

        outLogStream.close();

        logger.info("*******************************************************************");
        logger.info("Complete validation log is written to " + validateOutputFile);
        logger.info("*******************************************************************");
        logger.info("");
    } catch (IOException e) {
        e.printStackTrace();
        throw new MojoExecutionException("Error", e);
    } catch (Throwable e) {
        e.printStackTrace();
        throw new MojoExecutionException("Error", e);
    }

    if (!validated) {
        throw new MojoFailureException(
                "Project Validation failed ! Please check and verify Project or configure "
                        + validationIgnoresFile);
    }
}

From source file:com.slim.service.ValidateService.java

License:Apache License

/**
 * Prepare pattern of expressions to ignore
 * /*w  w w.ja  va  2s . c o m*/
 * @return
 */
private Pattern preparePattern(MavenProject project, String designerBinDir, String outputDirectory,
        String validationIgnoresFile, Log logger) {
    String lineIgnore;
    Pattern p = Pattern.compile("");
    try {
        BufferedReader ignoredStream = new BufferedReader(
                new InputStreamReader(new FileInputStream(validationIgnoresFile)));
        lineIgnore = null;
        StringBuilder sb = new StringBuilder();
        while ((lineIgnore = ignoredStream.readLine()) != null) {
            if (!lineIgnore.startsWith("#")) {
                sb.append("(?:" + lineIgnore + ")|");
            }
        }
        sb.deleteCharAt(sb.length() - 1);// remove the last "|" (OR)
        logger.debug("Pattern to match is : " + sb.toString());
        p = Pattern.compile(sb.toString());
    } catch (Exception ex) {
        logger.warn("********************************************************************************");
        logger.warn(validationIgnoresFile
                + " file is empty or could not be loaded. Run in debug mode to have Exception info");
        logger.warn("********************************************************************************");
        logger.debug(ex);
    }
    return p;
}

From source file:com.spoledge.audao.maven.GeneratorMojo.java

License:Apache License

private void generate() throws MojoExecutionException {
    Log log = getLog();

    String targetName = dbType.toUpperCase();

    log.info("AuDAO Generating from '" + src + "', to '" + dest + "', target '" + targetName + "'");

    try {/*ww  w . j  ava2 s .c o m*/
        Target target = Target.valueOf(targetName);
        InputStreamReader xmlReader = new InputStreamReader(new FileInputStream(src), "UTF-8");

        Output output = dest.getName().endsWith(".zip") ? new ZipFileOutput(dest) : new FileOutput(dest);

        Generator g = new Generator(target);
        g.setIsDebugEnabled(debug);
        g.validate(xmlReader);

        xmlReader = new InputStreamReader(new FileInputStream(src), "UTF-8");

        if (enableResources != null) {
            for (ResourceType res : enableResources) {
                g.setResourceEnabled(res, true);
            }

            if (generateDtoGwtSerializer) {
                g.setResourceEnabled(ResourceType.DTO_GWT_SERIALIZER, generateDtoGwtSerializer);
            }
        } else {
            g.setAllResourcesEnabled(true);
            g.setResourceEnabled(ResourceType.DTO_GWT_SERIALIZER, generateDtoGwtSerializer);
        }

        g.generate(pkg, xmlReader, output);

        output.finish();
    } catch (GeneratorException e) {
        if (e.isWarningOnly()) {
            log.warn(e.toString());
        } else {
            List<? extends Exception> exceptions = e.getExceptions();
            List<GeneratorException.Type> types = e.getTypes();

            for (int i = 0; i < exceptions.size(); i++) {
                switch (types.get(i)) {
                case WARNING:
                    log.warn(exceptions.get(i).toString());
                    break;

                case ERROR:
                    log.error("Error: ", exceptions.get(i));
                    break;

                default:
                    log.error("Fatal error:", exceptions.get(i));
                    break;

                }
            }

            throw new MojoExecutionException("Error (" + exceptions.size() + " nested errors)", e);
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Error", e);
    }
}

From source file:com.spotify.docker.Utils.java

License:Apache License

public static void pushImage(DockerClient docker, String imageName, Log log,
        final DockerBuildInformation buildInfo, int retryPushCount, int retryPushTimeout)
        throws MojoExecutionException, DockerException, IOException, InterruptedException {
    int attempt = 0;
    do {// w  ww  .ja v  a2  s . c o m
        final AnsiProgressHandler ansiProgressHandler = new AnsiProgressHandler();
        final DigestExtractingProgressHandler handler = new DigestExtractingProgressHandler(
                ansiProgressHandler);

        try {
            log.info("Pushing " + imageName);
            docker.push(imageName, handler);
            // A concurrent push raises a generic DockerException and not
            // the more logical ImagePushFailedException. Hence the rather
            // wide catch clause.
        } catch (DockerException e) {
            if (attempt < retryPushCount) {
                log.warn(String.format(PUSH_FAIL_WARN_TEMPLATE, imageName, retryPushTimeout / 1000, attempt + 1,
                        retryPushCount));
                sleep(retryPushTimeout);
                continue;
            } else {
                throw e;
            }
        }
        if (buildInfo != null) {
            final String imageNameWithoutTag = parseImageName(imageName)[0];
            buildInfo.setDigest(imageNameWithoutTag + "@" + handler.digest());
        }
        break;
    } while (attempt++ <= retryPushCount);
}

From source file:com.spotify.plugin.dockerfile.AbstractDockerMojo.java

License:Apache License

@Nonnull
protected File buildDockerInfoJar(@Nonnull Log log) throws MojoExecutionException {
    final File jarFile = getJarFile(buildDirectory, finalName, classifier);

    final MavenArchiver archiver = new MavenArchiver();
    archiver.setArchiver(jarArchiver);/*from w  ww. java2  s.c  om*/
    archiver.setOutputFile(jarFile);

    archive.setForced(forceCreation);

    if (dockerInfoDirectory.exists()) {
        final String prefix = getMetaSubdir();
        archiver.getArchiver().addDirectory(dockerInfoDirectory, prefix);
    } else {
        log.warn("Docker info directory not created - Docker info JAR will be empty");
    }

    try {
        archiver.createArchive(session, project, archive);
    } catch (Exception e) {
        throw new MojoExecutionException("Could not build Docker info JAR", e);
    }

    return jarFile;
}

From source file:com.spotify.plugin.dockerfile.BuildMojo.java

License:Apache License

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

    if (skipBuild) {
        log.info("Skipping execution because 'dockerfile.build.skip' is set");
        return;/*from www .j a  v  a  2s .  c o m*/
    }

    if (!new File(contextDirectory, "Dockerfile").exists()
            && !new File(contextDirectory, "dockerfile").exists()) {
        log.info("Skipping execution because missing Dockerfile in context directory: "
                + contextDirectory.getPath());
        return;
    }

    final String imageId = buildImage(dockerClient, log, verbose, contextDirectory, repository, tag,
            pullNewerImage, noCache);

    if (imageId == null) {
        log.warn("Docker build was successful, but no image was built");
    } else {
        log.info(MessageFormat.format("Detected build of image with id {0}", imageId));
        writeMetadata(Metadata.IMAGE_ID, imageId);
    }

    // Do this after the build so that other goals don't use the tag if it doesn't exist
    if (repository != null) {
        writeImageInfo(repository, tag);
    }

    writeMetadata(log);

    if (repository == null) {
        log.info(MessageFormat.format("Successfully built {0}", imageId));
    } else {
        log.info(MessageFormat.format("Successfully built {0}", formatImageName(repository, tag)));
    }
}

From source file:com.sri.vt.majic.util.clean.Cleaner.java

License:Apache License

/**
 * Creates a new cleaner./*from w  w w .  j a  va  2 s.  co  m*/
 * 
 * @param log The logger to use, may be <code>null</code> to disable logging.
 * @param verbose Whether to perform verbose logging.
 */
public Cleaner(final Log log, boolean verbose) {
    logDebug = (log == null || !log.isDebugEnabled()) ? null : new Logger() {
        public void log(CharSequence message) {
            log.debug(message);
        }
    };

    logInfo = (log == null || !log.isInfoEnabled()) ? null : new Logger() {
        public void log(CharSequence message) {
            log.info(message);
        }
    };

    logWarn = (log == null || !log.isWarnEnabled()) ? null : new Logger() {
        public void log(CharSequence message) {
            log.warn(message);
        }
    };

    logVerbose = verbose ? logInfo : logDebug;
}