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.bytedeco.javacpp.tools.BuildMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException {
    final Log log = getLog();
    try {//from ww w  .  j  a  v  a  2s .c  o m
        if (log.isDebugEnabled()) {
            log.debug("classPath: " + classPath);
            log.debug("classPaths: " + Arrays.deepToString(classPaths));
            log.debug("includePath: " + includePath);
            log.debug("includePaths: " + Arrays.deepToString(includePaths));
            log.debug("linkPath: " + linkPath);
            log.debug("linkPaths: " + Arrays.deepToString(linkPaths));
            log.debug("preloadPath: " + preloadPath);
            log.debug("preloadPaths: " + Arrays.deepToString(preloadPaths));
            log.debug("outputDirectory: " + outputDirectory);
            log.debug("outputName: " + outputName);
            log.debug("compile: " + compile);
            log.debug("deleteJniFiles: " + deleteJniFiles);
            log.debug("header: " + header);
            log.debug("copyLibs: " + copyLibs);
            log.debug("jarPrefix: " + jarPrefix);
            log.debug("properties: " + properties);
            log.debug("propertyFile: " + propertyFile);
            log.debug("propertyKeysAndValues: " + propertyKeysAndValues);
            log.debug("classOrPackageName: " + classOrPackageName);
            log.debug("classOrPackageNames: " + Arrays.deepToString(classOrPackageNames));
            log.debug("environmentVariables: " + environmentVariables);
            log.debug("compilerOptions: " + Arrays.deepToString(compilerOptions));
            log.debug("skip: " + skip);
        }

        if (skip) {
            log.info("Skipping execution of JavaCPP Builder");
            return;
        }

        classPaths = merge(classPaths, classPath);
        classOrPackageNames = merge(classOrPackageNames, classOrPackageName);

        Logger logger = new Logger() {
            @Override
            public void debug(String s) {
                log.debug(s);
            }

            @Override
            public void info(String s) {
                log.info(s);
            }

            @Override
            public void warn(String s) {
                log.warn(s);
            }

            @Override
            public void error(String s) {
                log.error(s);
            }
        };
        Builder builder = new Builder(logger).classPaths(classPaths).outputDirectory(outputDirectory)
                .outputName(outputName).compile(compile).deleteJniFiles(deleteJniFiles).header(header)
                .copyLibs(copyLibs).jarPrefix(jarPrefix).properties(properties).propertyFile(propertyFile)
                .properties(propertyKeysAndValues).classesOrPackages(classOrPackageNames)
                .environmentVariables(environmentVariables).compilerOptions(compilerOptions);
        Properties properties = builder.properties;
        log.info("Detected platform \"" + Loader.getPlatform() + "\"");
        log.info("Building for platform \"" + properties.get("platform") + "\"");
        String separator = properties.getProperty("platform.path.separator");
        for (String s : merge(includePaths, includePath)) {
            String v = properties.getProperty("platform.includepath", "");
            properties.setProperty("platform.includepath",
                    v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s);
        }
        for (String s : merge(linkPaths, linkPath)) {
            String v = properties.getProperty("platform.linkpath", "");
            properties.setProperty("platform.linkpath",
                    v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s);
        }
        for (String s : merge(preloadPaths, preloadPath)) {
            String v = properties.getProperty("platform.preloadpath", "");
            properties.setProperty("platform.preloadpath",
                    v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s);
        }
        Properties projectProperties = project.getProperties();
        for (String key : properties.stringPropertyNames()) {
            projectProperties.setProperty("javacpp." + key, properties.getProperty(key));
        }
        File[] outputFiles = builder.build();
        if (log.isDebugEnabled()) {
            log.debug("outputFiles: " + Arrays.deepToString(outputFiles));
        }
    } catch (IOException | ClassNotFoundException | NoClassDefFoundError | InterruptedException
            | ParserException e) {
        log.error("Failed to execute JavaCPP Builder: " + e.getMessage());
        throw new MojoExecutionException("Failed to execute JavaCPP Builder", e);
    }
}

From source file:org.codehaus.mojo.apt.LogUtils.java

License:Open Source License

public static void log(Log log, int level, CharSequence message) {
    if (level == LEVEL_DEBUG) {
        log.debug(message);//  ww  w. j  av  a 2 s.c o m
    } else if (level == LEVEL_INFO) {
        log.info(message);
    } else if (level == LEVEL_WARN) {
        log.warn(message);
    } else if (level == LEVEL_ERROR) {
        log.error(message);
    } else {
        throw new IllegalArgumentException("Unknown log level: " + level);
    }
}

From source file:org.codehaus.mojo.cassandra.Utils.java

License:Apache License

/**
 * Stops the Cassandra service./* w w w. j a v a 2 s .  co m*/
 *
 * @param rpcAddress The rpcAddress to connect to in order to see if Cassandra has stopped.
 * @param rpcPort    The rpcPort to connect on to check if Cassandra has stopped.
 * @param stopPort   The port to stop on.
 * @param stopKey    The key to stop with,
 * @param log        The log to write to.
 */
static void stopCassandraServer(String rpcAddress, int rpcPort, String stopAddress, int stopPort,
        String stopKey, Log log) {
    try {
        Socket s = new Socket(InetAddress.getByName(stopAddress), stopPort);
        s.setSoLinger(false, 0);

        OutputStream out = s.getOutputStream();
        out.write((stopKey + "\r\nstop\r\n").getBytes());
        out.flush();
        s.close();
    } catch (ConnectException e) {
        log.info("Cassandra not running!");
        return;
    } catch (Exception e) {
        log.error(e);
        return;
    }
    log.info("Waiting for Cassandra to stop...");
    long maxWaiting = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(30);
    boolean stopped = false;
    while (!stopped && System.currentTimeMillis() < maxWaiting) {
        TTransport tr = new TFramedTransport(new TSocket(rpcAddress, rpcPort));
        try {
            TProtocol proto = new TBinaryProtocol(tr);
            Cassandra.Client client = new Cassandra.Client(proto);
            try {
                tr.open();
            } catch (TTransportException e) {
                if (e.getCause() instanceof ConnectException) {
                    stopped = true;
                    continue;
                }
                log.debug(e.getLocalizedMessage(), e);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    // ignore
                }
            }
        } finally {
            if (tr.isOpen()) {
                tr.close();
            }
        }
    }
    if (stopped) {
        log.info("Cassandra has stopped.");
    } else {
        log.warn("Gave up waiting for Cassandra to stop.");
    }
}

From source file:org.codehaus.mojo.jalopy.JalopyMojo.java

License:Apache License

private void logMessage(Jalopy jalopy, File currentFile) throws MojoExecutionException {
    Log log = getLog();

    if (jalopy.getState() == Jalopy.State.OK) {
        log.info(currentFile + " formatted correctly.");
    } else if (jalopy.getState() == Jalopy.State.WARN) {
        log.warn(currentFile + " formatted with warnings.");
    } else if (jalopy.getState() == Jalopy.State.ERROR) {
        log.error(currentFile + " could not be formatted.");

        if (isFailOnError()) {
            throw new MojoExecutionException(currentFile + " could not be formatted.");
        }/*from   w w w  .j  a va 2s.co m*/
    } else {
        log.info(currentFile + " formatted with unknown state.");
    }
}

From source file:org.codehaus.mojo.javascript.titanium.TitaniumBuilder.java

License:Open Source License

/**
 * Parse a line and output to the specified logger using the appropriate level.
 * @param line The line to parse./*from ww w .j a v a2  s .  c  o  m*/
 * @param log The logger.
 * @param defaultLogLevel The log level to use if the parsed line doesn't contain
 * the log level info.
 * @return the log level used to log the line.
 */
private static String parseTitaniumBuilderLine(String line, Log log, String defaultLogLevel) {
    final Pattern pattern = Pattern.compile("\\[(TRACE|INFO|DEBUG|WARN|ERROR)\\] (.+)");
    final Matcher matcher = pattern.matcher(line);
    if (matcher.find()) {
        String type = matcher.group(1);
        String msg = matcher.group(2);
        if (type.equals("TRACE") || type.equals("DEBUG")) {
            log.debug(msg);
            return "DEBUG";
        } else if (type.equals("INFO")) {
            log.info(msg);
            return "INFO";
        } else if (type.equals("ERROR")) {
            log.error(msg);
            return "ERROR";
        } else if (type.equals("WARN")) {
            log.warn(msg);
            return "WARN";
        } else {
            log.debug(msg);
            return "DEBUG";
        }
    } else {
        if (defaultLogLevel != null) {
            defaultLogLevel = defaultLogLevel.toUpperCase();
            if (defaultLogLevel.equals("DEBUG") || defaultLogLevel.equals("TRACE")) {
                log.debug(line);
            } else if (defaultLogLevel.equals("INFO")) {
                log.info(line);
            } else if (defaultLogLevel.equals("ERROR")) {
                log.error(line);
            } else if (defaultLogLevel.equals("WARN")) {
                log.warn(line);
            } else {
                log.debug(line);
                defaultLogLevel = "DEBUG";
            }
            return defaultLogLevel;
        } else {
            log.debug(line);
            return "DEBUG";
        }
    }
}

From source file:org.codehaus.mojo.smc.Util.java

License:Apache License

/**
 * execute the net.sf.smc.Smc#main method given the specified arguments.
 * Standard Output and Err messages are redirected to <code>log.info()</code> and <code>log.error</code>.
 * @param arguments//from  ww  w .j  a  v  a2  s  . c  o  m
 * @param log
 * @throws Exception thrown if log.error() is not empty
 */
static void executeSmc(List arguments, Log log) throws Exception {
    final StringOutputStream out = new StringOutputStream();
    final StringOutputStream err = new StringOutputStream();
    executeSmc(arguments, out, err);
    if (out.toString().length() > 0) {
        log.info(out.toString());
    }
    if (err.toString().length() > 0) {
        log.error(".sm file contains errors: \n" + err.toString());
        throw new Exception("Error while converting files.");
    }
}

From source file:org.codehaus.mojo.webstart.generator.AbstractGenerator.java

License:Apache License

protected AbstractGenerator(Log log, GeneratorTechnicalConfig config, C extraConfig) {

    this.log = log;
    this.config = config;
    this.extraConfig = extraConfig;

    Properties props = new Properties();

    String inputFileTemplatePath = config.getInputFileTemplatePath();

    if (inputFileTemplatePath != null) {
        props.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS,
                "org.apache.velocity.runtime.log.NullLogSystem");
        props.setProperty("file.resource.loader.path", config.getResourceLoaderPath().getAbsolutePath());

        initVelocity(props);//from  www  .  ja va 2  s  . c o  m

        if (!engine.templateExists(inputFileTemplatePath)) {
            log.warn("Warning, template not found. Will probably fail.");
        }
    } else {
        log.info("No template specified Using default one.");

        inputFileTemplatePath = config.getDefaultTemplateResourceName();

        String webstartJarURL = config.getWebstartJarURL();
        log.debug("***** Webstart JAR URL: " + webstartJarURL);

        props = new Properties();
        props.setProperty("resource.loader", "jar");
        props.setProperty("jar.resource.loader.description",
                "Jar resource loader for default webstart templates");
        props.setProperty("jar.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.JarResourceLoader");
        props.setProperty("jar.resource.loader.path", webstartJarURL);

        initVelocity(props);

        if (!engine.templateExists(inputFileTemplatePath)) {
            log.error("Inbuilt template not found!! " + config.getDefaultTemplateResourceName()
                    + " Will probably fail.");
        }
    }

    try {
        this.velocityTemplate = engine.getTemplate(inputFileTemplatePath, config.getEncoding());
    } catch (Exception e) {
        IllegalArgumentException iae = new IllegalArgumentException(
                "Could not load the template file from '" + inputFileTemplatePath + "'");
        iae.initCause(e);
        throw iae;
    }
}

From source file:org.eclipse.acceleo.maven.AcceleoParserMojo.java

License:Open Source License

/**
 * {@inheritDoc}/*from ww w .  j av  a2s  . c  om*/
 * 
 * @see org.apache.maven.plugin.AbstractMojo#execute()
 */
public void execute() throws MojoExecutionException, MojoFailureException {
    Log log = getLog();
    log.info("Acceleo maven stand alone build...");

    log.info("Starting packages registration...");

    URLClassLoader newLoader = null;
    try {
        List<?> runtimeClasspathElements = project.getRuntimeClasspathElements();
        List<?> compileClasspathElements = project.getCompileClasspathElements();
        URL[] runtimeUrls = new URL[runtimeClasspathElements.size() + compileClasspathElements.size()];
        int i = 0;
        for (Object object : runtimeClasspathElements) {
            if (object instanceof String) {
                String str = (String) object;
                log.debug("Adding the runtime dependency " + str
                        + " to the classloader for the package resolution");
                runtimeUrls[i] = new File(str).toURI().toURL();
                i++;
            } else {
                log.debug("Runtime classpath entry is not a string: " + object);
            }
        }
        for (Object object : compileClasspathElements) {
            if (object instanceof String) {
                String str = (String) object;
                log.debug("Adding the compilation dependency " + str
                        + " to the classloader for the package resolution");
                runtimeUrls[i] = new File(str).toURI().toURL();
                i++;
            } else {
                log.debug("Runtime classpath entry is not a string: " + object);
            }
        }
        newLoader = new URLClassLoader(runtimeUrls, Thread.currentThread().getContextClassLoader());
    } catch (DependencyResolutionRequiredException e) {
        log.error(e);
    } catch (MalformedURLException e) {
        log.error(e);
    }

    for (String packageToRegister : this.packagesToRegister) {
        try {
            if (newLoader != null) {
                Class<?> forName = Class.forName(packageToRegister, true, newLoader);
                Field nsUri = forName.getField("eNS_URI");
                Field eInstance = forName.getField("eINSTANCE");

                Object nsURIInvoked = nsUri.get(null);
                if (nsURIInvoked instanceof String) {
                    log.info("Registering package '" + packageToRegister + "'.");
                    AcceleoPackageRegistry.INSTANCE.put((String) nsURIInvoked, eInstance.get(null));
                } else {
                    log.error("The URI field is not a string.");
                }
            }
        } catch (ClassNotFoundException e) {
            log.error(e);
        } catch (IllegalAccessException e) {
            log.error(e);
        } catch (SecurityException e) {
            log.error(e);
        } catch (NoSuchFieldException e) {
            log.error(e);
        }

    }

    log.info("Starting the build sequence for the project '" + this.acceleoProject.getRoot() + "'...");
    log.info("Mapping the pom.xml to AcceleoProject...");

    Preconditions.checkNotNull(this.acceleoProject);
    Preconditions.checkNotNull(this.acceleoProject.getRoot());
    Preconditions.checkNotNull(this.acceleoProject.getEntries());
    Preconditions.checkState(this.acceleoProject.getEntries().size() >= 1);

    File root = this.acceleoProject.getRoot();

    org.eclipse.acceleo.internal.parser.compiler.AcceleoProject aProject = new org.eclipse.acceleo.internal.parser.compiler.AcceleoProject(
            root);
    List<Entry> entries = this.acceleoProject.getEntries();
    Set<AcceleoProjectClasspathEntry> classpathEntries = new LinkedHashSet<AcceleoProjectClasspathEntry>();
    for (Entry entry : entries) {
        File inputDirectory = new File(root, entry.getInput());
        File outputDirectory = new File(root, entry.getOutput());

        log.debug("Input: " + inputDirectory.getAbsolutePath());
        log.debug("Output: " + outputDirectory.getAbsolutePath());

        AcceleoProjectClasspathEntry classpathEntry = new AcceleoProjectClasspathEntry(inputDirectory,
                outputDirectory);
        classpathEntries.add(classpathEntry);
    }
    aProject.addClasspathEntries(classpathEntries);

    List<AcceleoProject> dependencies = this.acceleoProject.getDependencies();
    if (dependencies != null) {
        for (AcceleoProject dependingAcceleoProject : dependencies) {
            File dependingProjectRoot = dependingAcceleoProject.getRoot();
            Preconditions.checkNotNull(dependingProjectRoot);

            org.eclipse.acceleo.internal.parser.compiler.AcceleoProject aDependingProject = new org.eclipse.acceleo.internal.parser.compiler.AcceleoProject(
                    dependingProjectRoot);

            List<Entry> dependingProjectEntries = dependingAcceleoProject.getEntries();
            Set<AcceleoProjectClasspathEntry> dependingClasspathEntries = new LinkedHashSet<AcceleoProjectClasspathEntry>();
            for (Entry entry : dependingProjectEntries) {
                File inputDirectory = new File(root, entry.getInput());
                File outputDirectory = new File(root, entry.getOutput());
                AcceleoProjectClasspathEntry classpathEntry = new AcceleoProjectClasspathEntry(inputDirectory,
                        outputDirectory);
                dependingClasspathEntries.add(classpathEntry);
            }

            aDependingProject.addClasspathEntries(dependingClasspathEntries);
            aProject.addProjectDependencies(Sets.newHashSet(aDependingProject));
        }
    }

    log.info("Adding jar dependencies...");
    List<String> jars = this.acceleoProject.getJars();
    if (jars != null) {
        Set<URI> newDependencies = new LinkedHashSet<URI>();
        for (String jar : jars) {
            log.info("Resolving jar: '" + jar + "'...");
            File jarFile = new File(jar);
            if (jarFile.isFile()) {
                URI uri = URI.createFileURI(jar);
                newDependencies.add(uri);
                log.info("Found jar for '" + jar + "' on the filesystem: '" + jarFile.getAbsolutePath() + "'.");
            } else {
                StringTokenizer tok = new StringTokenizer(jar, ":");

                String groupdId = null;
                String artifactId = null;
                String version = null;

                int c = 0;
                while (tok.hasMoreTokens()) {
                    String nextToken = tok.nextToken();
                    if (c == 0) {
                        groupdId = nextToken;
                    } else if (c == 1) {
                        artifactId = nextToken;
                    } else if (c == 2) {
                        version = nextToken;
                    }

                    c++;
                }

                Set<?> artifacts = this.project.getArtifacts();
                for (Object object : artifacts) {
                    if (object instanceof Artifact) {
                        Artifact artifact = (Artifact) object;
                        if (groupdId != null && groupdId.equals(artifact.getGroupId()) && artifactId != null
                                && artifactId.equals(artifact.getArtifactId())) {
                            if (version != null && version.equals(artifact.getVersion())) {
                                File artifactFile = artifact.getFile();
                                if (artifactFile != null && artifactFile.exists()) {
                                    URI uri = URI.createFileURI(artifactFile.getAbsolutePath());
                                    newDependencies.add(uri);
                                    log.info("Found jar for '" + jar + "' on the filesystem: '" + uri.toString()
                                            + "'.");
                                }
                            } else if (version == null) {
                                File artifactFile = artifact.getFile();
                                if (artifactFile != null && artifactFile.exists()) {
                                    URI uri = URI.createFileURI(artifactFile.getAbsolutePath());
                                    newDependencies.add(uri);
                                    log.info("Found jar for '" + jar + "' on the filesystem: '" + uri.toString()
                                            + "'.");
                                }
                            }
                        }
                    }
                }

                List<?> mavenDependencies = this.project.getDependencies();
                for (Object object : mavenDependencies) {
                    if (object instanceof Dependency) {
                        Dependency dependency = (Dependency) object;
                        if (groupdId != null && groupdId.equals(dependency.getGroupId()) && artifactId != null
                                && artifactId.equals(dependency.getArtifactId())) {
                            if (version != null && version.equals(dependency.getVersion())) {
                                String systemPath = dependency.getSystemPath();
                                if (systemPath != null && new File(systemPath).exists()) {
                                    URI uri = URI.createFileURI(systemPath);
                                    newDependencies.add(uri);
                                    log.info("Found jar for '" + jar + "' on the filesystem: '" + uri.toString()
                                            + "'.");
                                }
                            } else if (version == null) {
                                String systemPath = dependency.getSystemPath();
                                if (systemPath != null && new File(systemPath).exists()) {
                                    URI uri = URI.createFileURI(systemPath);
                                    newDependencies.add(uri);
                                    log.info("Found jar for '" + jar + "' on the filesystem: '" + uri.toString()
                                            + "'.");
                                }
                            }
                        }
                    }
                }
            }
        }
        aProject.addDependencies(newDependencies);
    }

    log.info("Starting parsing...");
    AcceleoParser parser = new AcceleoParser(aProject, this.useBinaryResources, this.usePlatformResourcePath);
    AcceleoParserListener listener = new AcceleoParserListener();
    parser.addListeners(listener);

    // Load and plug the uri resolver
    if (this.uriHandler != null && newLoader != null) {
        try {
            Class<?> forName = Class.forName(this.uriHandler, true, newLoader);
            Object newInstance = forName.newInstance();
            if (newInstance instanceof IAcceleoParserURIHandler) {
                IAcceleoParserURIHandler resolver = (IAcceleoParserURIHandler) newInstance;
                parser.setURIHandler(resolver);
            }
        } catch (ClassNotFoundException e) {
            log.error(e);
        } catch (InstantiationException e) {
            log.error(e);
        } catch (IllegalAccessException e) {
            log.error(e);
        }
    }

    Set<File> builtFiles = parser.buildAll(new BasicMonitor());

    boolean errorFound = false;
    for (File builtFile : builtFiles) {
        Collection<AcceleoParserProblem> problems = parser.getProblems(builtFile);
        Collection<AcceleoParserWarning> warnings = parser.getWarnings(builtFile);

        if (problems.size() > 0) {
            log.info("Errors for file '" + builtFile.getName() + "': " + problems);
            errorFound = true;
        }
        if (warnings.size() > 0) {
            log.info("Warnings for file '" + builtFile.getName() + "': " + warnings);
        }
    }

    if (errorFound && failOnError) {
        throw new MojoExecutionException("Errors have been found during the build of the generator");
    }

    // Removing everything
    AcceleoPackageRegistry.INSTANCE.clear();
    log.info("Build completed.");
}

From source file:org.eclipse.acceleo.maven.launcher.compatibility.AcceleoLauncherMojo.java

License:Open Source License

/**
 * {@inheritDoc}//from w  ww .  j  ava  2 s .c  o  m
 * 
 * @see org.apache.maven.plugin.AbstractMojo#execute()
 */
public void execute() throws MojoExecutionException, MojoFailureException {
    Log log = getLog();
    log.info("Acceleo maven stand alone generation...");

    log.info("Starting generator class loading...");

    URLClassLoader newLoader = null;
    try {
        List<?> runtimeClasspathElements = project.getRuntimeClasspathElements();
        List<?> compileClasspathElements = project.getCompileClasspathElements();
        URL[] runtimeUrls = new URL[runtimeClasspathElements.size() + compileClasspathElements.size()];
        int i = 0;
        for (Object object : runtimeClasspathElements) {
            if (object instanceof String) {
                String str = (String) object;
                log.debug("Adding the runtime dependency " + str
                        + " to the classloader for the package resolution");
                runtimeUrls[i] = new File(str).toURI().toURL();
                i++;
            } else {
                log.debug("Runtime classpath entry is not a string: " + object);
            }
        }
        for (Object object : compileClasspathElements) {
            if (object instanceof String) {
                String str = (String) object;
                log.debug("Adding the compilation dependency " + str
                        + " to the classloader for the package resolution");
                runtimeUrls[i] = new File(str).toURI().toURL();
                i++;
            } else {
                log.debug("Runtime classpath entry is not a string: " + object);
            }
        }
        newLoader = new URLClassLoader(runtimeUrls, Thread.currentThread().getContextClassLoader());
    } catch (DependencyResolutionRequiredException e) {
        log.error(e);
    } catch (MalformedURLException e) {
        log.error(e);
    }

    try {
        if (newLoader != null) {
            final Class<?> generatorClazz = Class.forName(generatorClass, true, newLoader);

            log.info("Starting the generation sequence for the generator '" + generatorClass + "'...");
            final Method mainMethod = generatorClazz.getMethod("main", String[].class);

            List<String> arguments = new ArrayList<String>(parameters.size() + 2);
            log.info("Model: '" + model + "'");
            arguments.add(model);
            log.info("Output folder: '" + outputFolder + "'");
            arguments.add(outputFolder);
            for (String parameter : parameters) {
                log.info("Parameter: '" + parameter + "'");
                arguments.add(parameter);
            }

            log.info("Invoking generator.");
            mainMethod.invoke(null, (Object) arguments.toArray(new String[arguments.size()]));

            log.info("Generation completed.");
        }
    } catch (ClassNotFoundException e) {
        log.error(e);
    } catch (SecurityException e) {
        log.error(e);
    } catch (NoSuchMethodException e) {
        log.error(e);
    } catch (IllegalAccessException e) {
        log.error(e);
    } catch (IllegalArgumentException e) {
        log.error(e);
    } catch (InvocationTargetException e) {
        log.error(e);
    }

}

From source file:org.genantics.maven.PegGenMojo.java

License:Open Source License

public void execute() throws MojoExecutionException {
    // NB: This could be more compactly written using PegGen,
    // but calling the parser and generator separately
    // allows better debugging.
    try {/*from   w ww  .  j  ava 2 s . co  m*/
        Log log = getLog();
        // FIXME - what is the right way to do this?
        File file = projectPath != null ? new File(projectPath) : new File(".");

        // For debugging
        String canon = file.getCanonicalPath();

        if (!grammarExtension.startsWith("."))
            grammarExtension = "." + grammarExtension;

        pegDirName = sourceDirectory;
        int slash = sourceDirectory.lastIndexOf('/');
        if (slash < 0)
            slash = sourceDirectory.lastIndexOf(File.separatorChar);
        if (slash >= 0)
            pegDirName = sourceDirectory.substring(slash + 1);

        locateGrammars(file);
        if (grammars.isEmpty()) {
            log.info("There are no grammars in " + sourceDirectory);
            return;
        }
        for (Grammar grammar : grammars) {
            char[] buf = new char[(int) grammar.file.length()];
            Reader reader = new FileReader(grammar.file);
            try {
                reader.read(buf);
            } finally {
                reader.close();
            }
            Parser parser = new Parser();
            Node[] nodes = parser.parseGrammar(buf, 0, buf.length);
            if (nodes == null || nodes.length == 0) {
                log.error("Parsing " + grammar.file.getCanonicalPath());
                List list = parser.getErrors();
                if (list != null) {
                    for (Object err : list) {
                        log.error(err.toString());
                    }
                }
                throw new MojoExecutionException("Parse errors");
            }
            File target = new File(file, outputDirectory);
            if (!target.exists()) {
                if (!target.mkdirs()) {
                    log.error("Can't create " + outputDirectory);
                    return;
                }
            }
            StringBuilder sb = new StringBuilder();
            collectRelativePath(grammar.file, sb);
            String relativePath = sb.toString();
            File outFile = new File(target, relativePath);
            File outDir = outFile.getParentFile();
            if (!outDir.exists()) {
                if (!outDir.mkdirs()) {
                    log.error("Can't create output directory " + outDir.getCanonicalPath());
                    return;
                }
            }
            int dirEnd = relativePath.lastIndexOf('/');
            String pkg = dirEnd < 0 ? "" : relativePath.substring(0, dirEnd).replace('/', '.');
            PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outFile)));
            String className = outFile.getName();
            // extension is always .java
            className = className.substring(0, className.length() - ".java".length());
            try {
                SimplePegGenerator gen = new SimplePegGenerator();
                gen.generate(nodes[0], buf, writer, pkg, className, null, "  ");
            } finally {
                writer.close();
            }
            log.info("Generated " + outFile.getCanonicalPath());
        }
    } catch (IOException e) {
        throw new MojoExecutionException("", e);
    }
}