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:org.phpmaven.phpdoc.impl.PhpdocBatchSupport.java

License:Apache License

/**
 * {@inheritDoc}/*from   w  w  w .ja va  2  s.com*/
 */
@Override
public void generateReport(Log log, IPhpdocRequest request) throws PhpException {
    try {
        final IPhpExecutable exec = this.factory
                .lookup(IPhpExecutableConfiguration.class, this.executableConfig, this.session)
                .getPhpExecutable();

        if (this.phpdocVersion.startsWith("1.")) {
            writeIni(log, request, phpDocConfigFile, generatedPhpDocConfigFile);
        } else {
            writeXml(log, request, phpDocConfigFile, generatedPhpDocConfigFile);
        }
        final String path = System.getProperty("java.library.path") + File.pathSeparator
                + System.getenv("PATH");
        log.debug("PATH: " + path);
        final String[] paths = path.split(File.pathSeparator);
        File phpDocFile = null;
        if ("phpdoc".equals(phpDocFilePath)) {
            for (int i = 0; i < paths.length; i++) {
                final File file = new File(paths[i], "phpdoc");
                if (file.isFile()) {
                    phpDocFile = file;
                    break;
                }
            }
        } else {
            phpDocFile = new File(phpDocFilePath);
        }
        if (phpDocFile == null || !phpDocFile.isFile()) {
            throw new PhpCoreException("phpdoc not found in path");
        }
        String command = "\"" + phpDocFile + "\" -c \"" + generatedPhpDocConfigFile.getAbsolutePath() + "\"";
        if (arguments != null && arguments.length() > 0) {
            command += " " + arguments;
        }
        log.debug("Executing PHPDocumentor: " + command);
        // XXX: commandLine.setWorkingDirectory(phpDocFile.getParent());
        String result;
        try {
            result = exec.execute(command, phpDocFile);
        } catch (PhpWarningException ex) {
            result = ex.getAppendedOutput();
            // silently ignore; only errors are important
        }
        for (final String line : result.split("\n")) {
            if (line.startsWith("ERROR:")) {
                // this is a error of phpdocumentor.
                log.error("Got error from php-documentor. " + "Enable debug (-X) to fetch the php output.\n"
                        + line);
                throw new PhpErrorException(phpDocFile, line);
            }
        }
    } catch (PlexusConfigurationException ex) {
        throw new PhpCoreException("Errors invoking phpdoc", ex);
    } catch (IOException ex) {
        throw new PhpCoreException("Errors invoking phpdoc", ex);
    } catch (ComponentLookupException ex) {
        throw new PhpCoreException("Errors invoking phpdoc", ex);
    }
}

From source file:org.phpmaven.phpdoc.impl.PhpdocPearSupport.java

License:Apache License

/**
 * {@inheritDoc}/*from   w ww .j av  a 2 s .c  o  m*/
 */
@Override
public void generateReport(Log log, IPhpdocRequest request) throws PhpException {
    try {
        final Xpp3Dom dom = new Xpp3Dom("configuration");
        if (this.executableConfig != null) {
            //                final Xpp3Dom configNode = new Xpp3Dom("executableConfig");
            //                configNode.addChild(executableConfig);
            dom.addChild(this.executableConfig);
        }
        final IMavenPearUtility util = this.factory.lookup(IPearConfiguration.class, dom, this.session)
                .getUtility(log);

        if (!util.isInstalled()) {
            util.installPear(false);
        }
        // do not try to read remote channels; so that we will work in offline mode etc.
        util.initChannels(false);

        boolean disableDeprecatedWarning = false;

        if (this.phpdocVersion.startsWith("1.")) {
            writeIni(log, request, phpDocConfigFile, generatedPhpDocConfigFile);
            util.installFromMavenRepository("net.php", "PhpDocumentor", this.phpdocVersion);
            disableDeprecatedWarning = true;
        } else {
            writeXml(log, request, phpDocConfigFile, generatedPhpDocConfigFile);
            // there is a very strange dependency mismatching in phpdoc.
            // an unknown version 0.17.0 is used as dependency for various things.
            // however it does not really work; maybe we need an empty dummy package.
            util.installFromMavenRepository("org.phpdoc", "phpDocumentor", "0.17.0");

            util.installFromMavenRepository("org.phpdoc", "phpDocumentor", this.phpdocVersion);
        }

        String phpDoc = ExecutionUtils.searchExecutable(log, "phpdoc.php", util.getBinDir().getAbsolutePath());
        if (phpDoc == null) {
            phpDoc = ExecutionUtils.searchExecutable(log, "phpdoc", util.getBinDir().getAbsolutePath(), false);
            if (phpDoc == null) {
                throw new PhpCoreException("phpdoc not found in path (" + util.getBinDir() + ")");
            }
        }
        String command = "-c \"" + generatedPhpDocConfigFile.getAbsolutePath() + "\"";
        if (arguments != null && arguments.length() > 0) {
            command += " " + arguments;
        }
        log.debug("Executing PHPDocumentor with args: " + command);
        // XXX: commandLine.setWorkingDirectory(phpDocFile.getParent());
        String result;

        try {
            if (!phpDoc.endsWith(".bat")) {
                final IPhpExecutableConfiguration config = this.factory
                        .lookup(IPhpExecutableConfiguration.class, this.executableConfig, this.session);

                // phpdoc overwrites error_reporting. we need to hack if we plan to overwrite it by ourselves.
                final String newErrorReporting = config.getNumErrorReporting() == -1
                        ? (disableDeprecatedWarning ? "E_ALL & !E_DEPRECATED" : null)
                        : String.valueOf(config.getNumErrorReporting());

                // try to find phpdoc.inc
                final File phpDocInc = new File(util.getPhpDir(), "PhpDocumentor/phpDocumentor/phpdoc.inc");

                if (newErrorReporting != null) {
                    log.debug("setting error reporting to " + newErrorReporting);
                    log.debug("using phpdoc.inc at " + phpDocInc);
                    config.setErrorReporting(newErrorReporting);
                }

                config.getIncludePath().add(util.getPhpDir().getAbsolutePath());
                if (newErrorReporting == null || !phpDocInc.exists()) {
                    // direct execution
                    final IPhpExecutable exec = config.getPhpExecutable();
                    result = exec.execute("\"" + phpDoc + "\" " + command, new File(phpDoc));
                } else {
                    // try to hack the deprecated warning
                    config.getIncludePath().add(phpDocInc.getParentFile().getParentFile().getAbsolutePath());
                    final IPhpExecutable exec = config.getPhpExecutable();
                    result = exec.executeCode("", PHPDOC_INC, command);
                }
            } else {
                final Commandline commandLine = new Commandline("\"" + phpDoc + "\" " + command);
                final StringBuilder stdout = new StringBuilder();
                final StringBuilder stderr = new StringBuilder();
                CommandLineUtils.executeCommandLine(commandLine, new StreamConsumer() {
                    @Override
                    public void consumeLine(String line) {
                        stdout.append(line);
                        stdout.append("\n");
                    }
                }, new StreamConsumer() {
                    @Override
                    public void consumeLine(String line) {
                        stderr.append(line);
                        stderr.append("\n");
                    }
                });
                result = stdout.toString();
                log.debug("phpdoc output:\n" + result);
            }
        } catch (PhpWarningException ex) {
            result = ex.getAppendedOutput();
            // silently ignore; only errors are important
        }
        for (final String line : result.split("\n")) {
            if (line.startsWith("ERROR:")) {
                // this is a error of phpdocumentor.
                log.error("Got error from php-documentor. " + "Enable debug (-X) to fetch the php output.\n"
                        + line);
                throw new PhpErrorException(new File(phpDoc), line);
            }
        }
    } catch (PlexusConfigurationException ex) {
        throw new PhpCoreException("Errors invoking phpdoc", ex);
    } catch (IOException ex) {
        throw new PhpCoreException("Errors invoking phpdoc", ex);
    } catch (ComponentLookupException ex) {
        throw new PhpCoreException("Errors invoking phpdoc", ex);
    } catch (CommandLineException ex) {
        throw new PhpCoreException("Errors invoking phpdoc", ex);
    }
}

From source file:org.phpmaven.phpdoc.impl.PhpdocSupport.java

License:Apache License

/**
 * {@inheritDoc}//from w w  w.  jav a 2s .c  om
 */
@Override
public void generateReport(Log log, IPhpdocRequest request) throws PhpException {
    try {
        final IPhpExecutable exec = this.factory
                .lookup(IPhpExecutableConfiguration.class, this.executableConfig, this.session)
                .getPhpExecutable(log);

        writeIni(log, request, phpDocConfigFile, generatedPhpDocConfigFile);
        final String path = System.getProperty("java.library.path") + File.pathSeparator
                + System.getenv("PATH");
        log.debug("PATH: " + path);
        final String[] paths = path.split(File.pathSeparator);
        File phpDocFile = null;
        if ("phpdoc".equals(phpDocFilePath)) {
            for (int i = 0; i < paths.length; i++) {
                final File file = new File(paths[i], "phpdoc");
                if (file.isFile()) {
                    phpDocFile = file;
                    break;
                }
            }
        } else {
            phpDocFile = new File(phpDocFilePath);
        }
        if (phpDocFile == null || !phpDocFile.isFile()) {
            throw new PhpCoreException("phpdoc not found in path");
        }
        final String command = "\"" + phpDocFile + "\" -c \"" + generatedPhpDocConfigFile.getAbsolutePath()
                + "\"";
        log.debug("Executing PHPDocumentor: " + command);
        // XXX: commandLine.setWorkingDirectory(phpDocFile.getParent());
        final String result = exec.execute(command, phpDocFile);
        for (final String line : result.split("\n")) {
            if (line.startsWith("ERROR:")) {
                // this is a error of phpdocumentor.
                log.error("Got error from php-documentor. " + "Enable debug (-X) to fetch the php output.\n"
                        + line);
                throw new PhpErrorException(phpDocFile, line);
            }
        }
    } catch (PlexusConfigurationException ex) {
        throw new PhpCoreException("Errors invoking phpdoc", ex);
    } catch (IOException ex) {
        throw new PhpCoreException("Errors invoking phpdoc", ex);
    } catch (ComponentLookupException ex) {
        throw new PhpCoreException("Errors invoking phpdoc", ex);
    }
}

From source file:org.primefaces.extensions.optimizerplugin.ClosureCompilerOptimizer.java

License:Apache License

@Override
public void optimize(final ResourcesSetAdapter rsa, final Log log) throws MojoExecutionException {
    CompilationLevel compLevel = rsa.getCompilationLevel();
    CompilerOptions options = new CompilerOptions();
    compLevel.setOptionsForCompilationLevel(options);

    WarningLevel warnLevel = rsa.getWarningLevel();
    warnLevel.setOptionsForWarningLevel(options);
    com.google.javascript.jscomp.Compiler.setLoggingLevel(Level.WARNING);

    try {//  ww  w  .  j  av  a2 s  . c  o  m
        Charset cset = Charset.forName(rsa.getEncoding());

        if (rsa.getAggregation() == null) {
            // no aggregation
            for (File file : rsa.getFiles()) {
                log.info("Optimize JS file " + file.getName() + " ...");
                addToOriginalSize(file);

                JSSourceFile jsSourceFile = JSSourceFile.fromFile(file, cset);
                List<JSSourceFile> interns = new ArrayList<JSSourceFile>();
                interns.add(jsSourceFile);

                // compile
                Compiler compiler = compile(log, interns, options, rsa.isFailOnWarning());

                // generate output
                String path = file.getCanonicalPath();
                if (StringUtils.isNotBlank(rsa.getSuffix())) {
                    // write compiled content into the new file
                    File outputFile = getFileWithSuffix(path, rsa.getSuffix());
                    Files.write(compiler.toSource(), outputFile, cset);

                    // statistic
                    addToOptimizedSize(outputFile);
                } else {
                    // path of temp. file
                    String pathOptimized = FileUtils.removeExtension(path) + OPTIMIZED_FILE_EXTENSION;

                    // create a new temp. file
                    File outputFile = new File(pathOptimized);
                    Files.touch(outputFile);

                    // write compiled content into the new file and rename it (overwrite the original file)
                    Files.write(compiler.toSource(), outputFile, cset);
                    FileUtils.rename(outputFile, file);

                    // statistic
                    addToOptimizedSize(file);
                }
            }
        } else if (rsa.getAggregation().getOutputFile() != null) {
            // aggregation to one output file
            File outputFile;

            if (!rsa.getAggregation().isWithoutCompress()) {
                // with compressing before aggregation
                List<JSSourceFile> interns = new ArrayList<JSSourceFile>();
                for (File file : rsa.getFiles()) {
                    log.info("Optimize JS file " + file.getName() + " ...");
                    addToOriginalSize(file);

                    interns.add(JSSourceFile.fromFile(file, cset));
                }

                // compile
                Compiler compiler = compile(log, interns, options, rsa.isFailOnWarning());

                int filesCount = rsa.getFiles().size();
                if (rsa.getAggregation().getPrependedFile() != null) {
                    filesCount++;
                }

                if (filesCount > 1) {
                    log.info("Aggregation is running ...");
                }

                // get right output file
                outputFile = getOutputFile(rsa);

                long sizeBefore = outputFile.length();

                if (rsa.getAggregation().getPrependedFile() != null) {
                    // write / append to be prepended file into / to the output file
                    prependFile(rsa.getAggregation().getPrependedFile(), outputFile, cset, rsa.getEncoding());
                }

                // write / append compiled content into / to the output file
                Files.append(compiler.toSource(), outputFile, cset);

                // statistic
                addToOptimizedSize(outputFile.length() - sizeBefore);

                if (filesCount > 1) {
                    log.info(filesCount + " files were successfully aggregated.");
                }
            } else {
                // only aggregation without compressing
                outputFile = aggregateFiles(rsa, cset, log);
            }

            // delete single files if necessary
            deleteFilesIfNecessary(rsa, log);

            // rename aggregated file if necessary
            renameOutputFileIfNecessary(rsa, outputFile);
        } else {
            // should not happen
            log.error("Wrong plugin's internal state.");
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Resources optimization failure: " + e.getLocalizedMessage(), e);
    }
}

From source file:org.primefaces.extensions.optimizerplugin.ClosureCompilerOptimizer.java

License:Apache License

protected void evalResult(final Result result, final Log log, final boolean failOnWarning)
        throws MojoExecutionException {
    if (result.warnings != null) {
        for (JSError warning : result.warnings) {
            log.warn(warning.toString());
        }//  w w w  .  ja  va2s. c  o m
    }

    if (result.warnings != null && result.warnings.length > 0 && failOnWarning) {
        throw new MojoExecutionException("Resources optimization failure. Please fix warnings and try again.");
    }

    if (result.errors != null) {
        for (JSError error : result.errors) {
            log.error(error.toString());
        }
    }

    if (result.errors != null && result.errors.length > 0) {
        throw new MojoExecutionException("Resources optimization failure. Please fix errors and try again.");
    }

    if (!result.success) {
        throw new MojoExecutionException("Resources optimization failure. Please fix errors and try again.");
    }
}

From source file:org.primefaces.extensions.optimizerplugin.optimizer.ClosureCompilerOptimizer.java

License:Apache License

@Override
public void optimize(final ResourcesSetAdapter rsAdapter, final Log log) throws MojoExecutionException {
    ResourcesSetJsAdapter rsa = (ResourcesSetJsAdapter) rsAdapter;
    CompilationLevel compLevel = rsa.getCompilationLevel();
    CompilerOptions options = new CompilerOptions();
    compLevel.setOptionsForCompilationLevel(options);

    WarningLevel warnLevel = rsa.getWarningLevel();
    warnLevel.setOptionsForWarningLevel(options);
    Compiler.setLoggingLevel(Level.WARNING);

    try {//from  ww w.  j a v  a  2 s. co m
        Charset cset = Charset.forName(rsa.getEncoding());

        if (rsa.getAggregation() == null) {
            // no aggregation
            for (File file : rsa.getFiles()) {
                log.info("Optimize JS file " + file.getName() + " ...");

                // statistic
                addToOriginalSize(file);

                // path of the original file
                String path = file.getCanonicalPath();

                String outputFilePath = null;
                String outputSourceMapDir = null;
                File sourceMapFile = null;
                File sourceFile;

                if (rsa.getSourceMap() != null) {
                    // setup source map
                    outputFilePath = file.getCanonicalPath();
                    outputSourceMapDir = rsa.getSourceMap().getOutputDir();
                    sourceMapFile = setupSourceMapFile(options, rsa.getSourceMap(), outputFilePath);
                    // create an empty file with ...source.js from the original one
                    sourceFile = getFileWithSuffix(path, OUTPUT_FILE_SUFFIX);

                    if (StringUtils.isNotBlank(rsa.getSuffix())) {
                        // rename original file as ...source.js
                        FileUtils.rename(file, sourceFile);
                    } else {
                        // copy content of the original file to the ...source.js
                        FileUtils.copyFile(file, sourceFile);
                    }
                } else {
                    sourceFile = file;
                }

                // compile
                List<SourceFile> interns = new ArrayList<SourceFile>();
                interns.add(SourceFile.fromFile(sourceFile, cset));
                Compiler compiler = compile(log, interns, options, rsa.isFailOnWarning());

                if (StringUtils.isNotBlank(rsa.getSuffix())) {
                    // write compiled content into the new file
                    File outputFile = getFileWithSuffix(path, rsa.getSuffix());
                    Files.write(compiler.toSource(), outputFile, cset);

                    if (sourceMapFile != null) {
                        // write sourceMappingURL into the minified file
                        writeSourceMappingURL(outputFile, sourceMapFile, rsa.getSourceMap().getSourceMapRoot(),
                                cset, log);
                    }

                    // statistic
                    addToOptimizedSize(outputFile);
                } else {
                    // path of temp. file
                    String pathOptimized = FileUtils.removeExtension(path) + OPTIMIZED_FILE_EXTENSION;

                    // create a new temp. file
                    File outputFile = new File(pathOptimized);
                    Files.touch(outputFile);

                    // write compiled content into the new file and rename it (overwrite the original file)
                    Files.write(compiler.toSource(), outputFile, cset);
                    FileUtils.rename(outputFile, file);

                    if (sourceMapFile != null) {
                        // write sourceMappingURL into the minified file
                        writeSourceMappingURL(file, sourceMapFile, rsa.getSourceMap().getSourceMapRoot(), cset,
                                log);
                    }

                    // statistic
                    addToOptimizedSize(file);
                }

                if (outputFilePath != null && sourceMapFile != null) {
                    // write the source map
                    Files.touch(sourceMapFile);
                    writeSourceMap(sourceMapFile, outputFilePath, compiler.getSourceMap(), outputSourceMapDir,
                            log);

                    // move the source file to the source map dir
                    moveToSourceMapDir(sourceFile, outputSourceMapDir, log);
                }
            }
        } else if (rsa.getAggregation().getOutputFile() != null) {
            // aggregation to one output file
            File outputFile = rsa.getAggregation().getOutputFile();
            File aggrOutputFile = aggregateFiles(rsa, cset, true);

            // statistic
            long sizeBefore = addToOriginalSize(aggrOutputFile);

            if (!rsa.getAggregation().isWithoutCompress()) {
                // compressing
                for (File file : rsa.getFiles()) {
                    log.info("Optimize JS file " + file.getName() + " ...");
                }

                String outputFilePath = null;
                File sourceMapFile = null;
                if (rsa.getSourceMap() != null) {
                    // setup source map
                    outputFilePath = outputFile.getCanonicalPath();
                    sourceMapFile = setupSourceMapFile(options, rsa.getSourceMap(), outputFilePath);
                }

                // compile
                List<SourceFile> interns = new ArrayList<SourceFile>();
                interns.add(SourceFile.fromFile(aggrOutputFile, cset));
                Compiler compiler = compile(log, interns, options, rsa.isFailOnWarning());

                // delete single files if necessary
                deleteFilesIfNecessary(rsa, log);

                // write the compiled content into a new file
                Files.touch(outputFile);
                Files.write(compiler.toSource(), outputFile, cset);

                if (outputFilePath != null && sourceMapFile != null) {
                    // write sourceMappingURL into the minified file
                    writeSourceMappingURL(outputFile, sourceMapFile, rsa.getSourceMap().getSourceMapRoot(),
                            cset, log);

                    // write the source map
                    String outputSourceMapDir = rsa.getSourceMap().getOutputDir();
                    Files.touch(sourceMapFile);
                    writeSourceMap(sourceMapFile, outputFilePath, compiler.getSourceMap(), outputSourceMapDir,
                            log);

                    // move the source file
                    moveToSourceMapDir(aggrOutputFile, outputSourceMapDir, log);
                } else {
                    // delete the temp. aggregated file ...source.js
                    if (aggrOutputFile.exists() && !aggrOutputFile.delete()) {
                        log.warn("Temporary file " + aggrOutputFile.getName() + " could not be deleted.");
                    }
                }

                // statistic
                addToOptimizedSize(sizeBefore - outputFile.length());
            } else {
                // delete single files if necessary
                deleteFilesIfNecessary(rsa, log);

                // rename aggregated file if necessary
                renameOutputFileIfNecessary(rsa, aggrOutputFile);

                // statistic
                addToOptimizedSize(sizeBefore);
            }
        } else {
            // should not happen
            log.error("Wrong plugin's internal state.");
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Resources optimization failure: " + e.getLocalizedMessage(), e);
    }
}

From source file:org.primefaces.extensions.optimizerplugin.optimizer.ClosureCompilerOptimizer.java

License:Apache License

protected void evalResult(Result result, Log log, boolean failOnWarning) throws MojoExecutionException {
    if (result.warnings != null) {
        for (JSError warning : result.warnings) {
            log.warn(warning.toString());
        }/*from   w  w w  .  j  a  va  2 s. c  om*/
    }

    if (result.warnings != null && result.warnings.length > 0 && failOnWarning) {
        throw new MojoExecutionException("Resources optimization failure. Please fix warnings and try again.");
    }

    if (result.errors != null) {
        for (JSError error : result.errors) {
            log.error(error.toString());
        }
    }

    if (result.errors != null && result.errors.length > 0) {
        throw new MojoExecutionException("Resources optimization failure. Please fix errors and try again.");
    }

    if (!result.success) {
        throw new MojoExecutionException("Resources optimization failure. Please fix errors and try again.");
    }
}

From source file:org.primefaces.extensions.optimizerplugin.optimizer.YuiCompressorOptimizer.java

License:Apache License

@Override
public void optimize(final ResourcesSetAdapter rsAdapter, final Log log) throws MojoExecutionException {
    ResourcesSetCssAdapter rsa = (ResourcesSetCssAdapter) rsAdapter;
    Reader in = null;/*w w w  .j  av  a  2 s . c o  m*/
    OutputStreamWriter out = null;

    try {
        if (rsa.getAggregation() == null) {
            // no aggregation
            for (File file : rsa.getFiles()) {
                log.info("Optimize CSS file " + file.getName() + " ...");

                // statistic
                addToOriginalSize(file);

                in = getReader(rsa, file);

                // generate output
                String path = file.getCanonicalPath();
                if (StringUtils.isNotBlank(rsa.getSuffix())) {
                    // create a new output stream
                    File outputFile = getFileWithSuffix(path, rsa.getSuffix());
                    out = new OutputStreamWriter(new FileOutputStream(outputFile), rsa.getEncoding());

                    // compress and write compressed content into the new file
                    CssCompressor compressor = new CssCompressor(in);
                    compressor.compress(out, 500);
                    closeStreams(in, out);

                    // statistic
                    addToOptimizedSize(outputFile);
                } else {
                    // path of temp. file
                    String pathOptimized = FileUtils.removeExtension(path) + OPTIMIZED_FILE_EXTENSION;

                    // create a new temp. file and output stream
                    File outputFile = new File(pathOptimized);
                    Files.touch(outputFile);
                    out = new OutputStreamWriter(new FileOutputStream(outputFile), rsa.getEncoding());

                    // compress and write compressed content into the new file
                    CssCompressor compressor = new CssCompressor(in);
                    compressor.compress(out, 500);
                    closeStreams(in, out);

                    // rename the new file (overwrite the original file)
                    FileUtils.rename(outputFile, file);

                    // statistic
                    addToOptimizedSize(file);
                }
            }
        } else if (rsa.getAggregation().getOutputFile() != null) {
            // aggregation to one output file
            File outputFile;
            Charset cset = Charset.forName(rsa.getEncoding());

            if (!rsa.getAggregation().isWithoutCompress()) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(baos, rsa.getEncoding());

                // with compressing before aggregation
                for (File file : rsa.getFiles()) {
                    log.info("Optimize CSS file " + file.getName() + " ...");

                    // statistic
                    addToOriginalSize(file);

                    // create reader for the current file
                    in = getReader(rsa, file);

                    // compress and write compressed content into the output stream
                    CssCompressor compressor = new CssCompressor(in);
                    compressor.compress(osw, 500);

                    // close stream
                    IOUtil.close(in);
                }

                // close stream
                IOUtil.close(osw);

                if (rsa.getAggregation().getPrependedFile() != null) {
                    // statistic
                    addToOriginalSize(rsa.getAggregation().getPrependedFile());
                }

                // get right output file
                outputFile = getOutputFile(rsa);

                long sizeBefore = outputFile.length();

                if (rsa.getAggregation().getPrependedFile() != null) {
                    // write / append to be prepended file into / to the output file
                    prependFile(rsa.getAggregation().getPrependedFile(), outputFile, cset, rsa);
                }

                // write / append compiled content into / to the output file
                Files.append(baos.toString(rsa.getEncoding()), outputFile, cset);

                // statistic
                addToOptimizedSize(outputFile.length() - sizeBefore);
            } else {
                // only aggregation without compressing
                outputFile = aggregateFiles(rsa, cset, false);

                // statistic
                long size = addToOriginalSize(outputFile);
                addToOptimizedSize(size);
            }

            // delete single files if necessary
            deleteFilesIfNecessary(rsa, log);

            // rename aggregated file if necessary
            renameOutputFileIfNecessary(rsa, outputFile);
        } else {
            // should not happen
            log.error("Wrong plugin's internal state.");
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Resources optimization failure: " + e.getLocalizedMessage(), e);
    } finally {
        closeStreams(in, out);
    }
}

From source file:org.primefaces.extensions.optimizerplugin.YuiCompressorOptimizer.java

License:Apache License

@Override
public void optimize(final ResourcesSetAdapter rsa, final Log log) throws MojoExecutionException {
    InputStreamReader in = null;//  w w w .  j a v a 2s .c  o  m
    OutputStreamWriter out = null;

    try {
        if (rsa.getAggregation() == null) {
            // no aggregation
            for (File file : rsa.getFiles()) {
                log.info("Optimize CSS file " + file.getName() + " ...");
                addToOriginalSize(file);

                in = new InputStreamReader(new FileInputStream(file), rsa.getEncoding());

                // generate output
                String path = file.getCanonicalPath();
                if (StringUtils.isNotBlank(rsa.getSuffix())) {
                    // create a new output stream
                    File outputFile = getFileWithSuffix(path, rsa.getSuffix());
                    out = new OutputStreamWriter(new FileOutputStream(outputFile), rsa.getEncoding());

                    // compress and write compressed content into the new file
                    CssCompressor compressor = new CssCompressor(in);
                    compressor.compress(out, 500);
                    closeStreams(in, out);

                    // statistic
                    addToOptimizedSize(outputFile);
                } else {
                    // path of temp. file
                    String pathOptimized = FileUtils.removeExtension(path) + OPTIMIZED_FILE_EXTENSION;

                    // create a new temp. file and output stream
                    File outputFile = new File(pathOptimized);
                    Files.touch(outputFile);
                    out = new OutputStreamWriter(new FileOutputStream(outputFile), rsa.getEncoding());

                    // compress and write compressed content into the new file
                    CssCompressor compressor = new CssCompressor(in);
                    compressor.compress(out, 500);
                    closeStreams(in, out);

                    // rename the new file (overwrite the original file)
                    FileUtils.rename(outputFile, file);

                    // statistic
                    addToOptimizedSize(file);
                }
            }
        } else if (rsa.getAggregation().getOutputFile() != null) {
            // aggregation to one output file
            File outputFile;
            Charset cset = Charset.forName(rsa.getEncoding());

            if (!rsa.getAggregation().isWithoutCompress()) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(baos, rsa.getEncoding());

                // with compressing before aggregation
                for (File file : rsa.getFiles()) {
                    log.info("Optimize CSS file " + file.getName() + " ...");
                    addToOriginalSize(file);

                    // create input stream for the current file
                    in = new InputStreamReader(new FileInputStream(file), rsa.getEncoding());

                    // compress and write compressed content into the output stream
                    CssCompressor compressor = new CssCompressor(in);
                    compressor.compress(osw, 500);

                    // close stream
                    IOUtil.close(in);
                }

                // close stream
                IOUtil.close(osw);

                int filesCount = rsa.getFiles().size();
                if (rsa.getAggregation().getPrependedFile() != null) {
                    filesCount++;
                }

                if (filesCount > 1) {
                    log.info("Aggregation is running ...");
                }

                // get right output file
                outputFile = getOutputFile(rsa);

                long sizeBefore = outputFile.length();

                if (rsa.getAggregation().getPrependedFile() != null) {
                    // write / append to be prepended file into / to the output file
                    prependFile(rsa.getAggregation().getPrependedFile(), outputFile, cset, rsa.getEncoding());
                }

                // write / append compiled content into / to the output file
                Files.append(baos.toString(rsa.getEncoding()), outputFile, cset);

                // statistic
                addToOptimizedSize(outputFile.length() - sizeBefore);

                if (filesCount > 1) {
                    log.info(filesCount + " files were successfully aggregated.");
                }
            } else {
                // only aggregation without compressing
                outputFile = aggregateFiles(rsa, cset, log);
            }

            // delete single files if necessary
            deleteFilesIfNecessary(rsa, log);

            // rename aggregated file if necessary
            renameOutputFileIfNecessary(rsa, outputFile);
        } else {
            // should not happen
            log.error("Wrong plugin's internal state.");
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Resources optimization failure: " + e.getLocalizedMessage(), e);
    } finally {
        closeStreams(in, out);
    }
}

From source file:org.qunix.maven.structure.plugin.core.StructureBuilder.java

License:Apache License

/**
 * Collects user/env. parameters then instantiate wrapper {@link AbstractStructureNode} object and calls a recursive to put outputs together
 * //from  w  w w  .jav a  2s  . c  om
 * @param root root node
 * @param type {@link StructureType} (from maven goal)
 * @param detailed does user wants details output
 * @param logger default logger instance for mojo
 * @param ignores list of regexpatterns to ignore
 * @param outputFile does user wants to write output into file? If null then it will be printed into screen
 * @throws MojoFailureException
 */
public void build(Object root, StructureType type, boolean detailed, Log logger, String[] ignores,
        File... outputFile) throws MojoFailureException {

    //null check
    if (root == null) {
        throw new MojoFailureException("Structure plugin couldnt recognize root!");
    }

    //get wrapped node so we can process
    StructureNode<?> parent = StructureFactory.getStructure(type, root, detailed);

    //get header (project structure...)
    StringBuilder outputStr = new StringBuilder(parent.getHeader());

    //call recursive if root has childs
    buildChilds(parent, StructureOutput.LONG_TAB.getValue(), outputStr, ignores);

    //some more space
    outputStr.append(StructureOutput.LONG_NEW_LINE.getValue());

    //if outputfile not specified put into screen
    if (ArrayUtils.isEmpty(outputFile) || outputFile[0] == null) {
        logger.info(outputStr.toString());
    } else {

        //if output file specified write into file
        //TODO carry into or call from utility class
        try {
            FileWriter fw = new FileWriter(outputFile[0]);
            fw.write(outputStr.toString());
            fw.flush();
            fw.close();
        } catch (IOException e) {
            logger.error(e);
            throw new MojoFailureException("Structure plugin couldnt write output to file!");

        }

    }
}