Search in sources :

Example 46 with Resource

use of org.apache.maven.model.Resource in project generator by mybatis.

the class MyBatisGeneratorMojo method execute.

public void execute() throws MojoExecutionException {
    if (skip) {
        getLog().info("MyBatis generator is skipped.");
        return;
    }
    LogFactory.setLogFactory(new MavenLogFactory(this));
    // add resource directories to the classpath.  This is required to support
    // use of a properties file in the build.  Typically, the properties file
    // is in the project's source tree, but the plugin classpath does not
    // include the project classpath.
    List<Resource> resources = project.getResources();
    List<String> resourceDirectories = new ArrayList<String>();
    for (Resource resource : resources) {
        resourceDirectories.add(resource.getDirectory());
    }
    ClassLoader cl = ClassloaderUtility.getCustomClassloader(resourceDirectories);
    ObjectFactory.addResourceClassLoader(cl);
    if (configurationFile == null) {
        throw new MojoExecutionException(//$NON-NLS-1$
        Messages.getString("RuntimeError.0"));
    }
    List<String> warnings = new ArrayList<String>();
    if (!configurationFile.exists()) {
        throw new MojoExecutionException(Messages.getString("RuntimeError.1", //$NON-NLS-1$
        configurationFile.toString()));
    }
    runScriptIfNecessary();
    Set<String> fullyqualifiedTables = new HashSet<String>();
    if (StringUtility.stringHasValue(tableNames)) {
        //$NON-NLS-1$
        StringTokenizer st = new StringTokenizer(tableNames, ",");
        while (st.hasMoreTokens()) {
            String s = st.nextToken().trim();
            if (s.length() > 0) {
                fullyqualifiedTables.add(s);
            }
        }
    }
    Set<String> contextsToRun = new HashSet<String>();
    if (StringUtility.stringHasValue(contexts)) {
        //$NON-NLS-1$
        StringTokenizer st = new StringTokenizer(contexts, ",");
        while (st.hasMoreTokens()) {
            String s = st.nextToken().trim();
            if (s.length() > 0) {
                contextsToRun.add(s);
            }
        }
    }
    try {
        ConfigurationParser cp = new ConfigurationParser(project.getProperties(), warnings);
        Configuration config = cp.parseConfiguration(configurationFile);
        ShellCallback callback = new MavenShellCallback(this, overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(new MavenProgressCallback(getLog(), verbose), contextsToRun, fullyqualifiedTables);
    } catch (XMLParserException e) {
        for (String error : e.getErrors()) {
            getLog().error(error);
        }
        throw new MojoExecutionException(e.getMessage());
    } catch (SQLException e) {
        throw new MojoExecutionException(e.getMessage());
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage());
    } catch (InvalidConfigurationException e) {
        for (String error : e.getErrors()) {
            getLog().error(error);
        }
        throw new MojoExecutionException(e.getMessage());
    } catch (InterruptedException e) {
    // ignore (will never happen with the DefaultShellCallback)
    }
    for (String error : warnings) {
        getLog().warn(error);
    }
    if (project != null && outputDirectory != null && outputDirectory.exists()) {
        project.addCompileSourceRoot(outputDirectory.getAbsolutePath());
        Resource resource = new Resource();
        resource.setDirectory(outputDirectory.getAbsolutePath());
        resource.addInclude("**/*.xml");
        project.addResource(resource);
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) Configuration(org.mybatis.generator.config.Configuration) ShellCallback(org.mybatis.generator.api.ShellCallback) XMLParserException(org.mybatis.generator.exception.XMLParserException) SQLException(java.sql.SQLException) Resource(org.apache.maven.model.Resource) ArrayList(java.util.ArrayList) IOException(java.io.IOException) InvalidConfigurationException(org.mybatis.generator.exception.InvalidConfigurationException) StringTokenizer(java.util.StringTokenizer) ConfigurationParser(org.mybatis.generator.config.xml.ConfigurationParser) HashSet(java.util.HashSet) MyBatisGenerator(org.mybatis.generator.api.MyBatisGenerator)

Example 47 with Resource

use of org.apache.maven.model.Resource in project maven-plugins by apache.

the class AntBuildWriter method writeProperties.

/**
     * Write properties in the writer only for a non-POM project.
     *
     * @param writer
     */
private void writeProperties(XMLWriter writer) {
    if (AntBuildWriterUtil.isPomPackaging(project)) {
        return;
    }
    // TODO: optional in m1
    // TODO: USD properties
    XmlWriterUtil.writeCommentText(writer, "Build environment properties", 1);
    // ----------------------------------------------------------------------
    // File properties to override local properties
    // ----------------------------------------------------------------------
    writer.startElement("property");
    writer.addAttribute("file", "${user.home}/.m2/maven.properties");
    // property
    writer.endElement();
    writer.startElement("property");
    writer.addAttribute("file", DEFAULT_MAVEN_PROPERTIES_FILENAME);
    // property
    writer.endElement();
    // ----------------------------------------------------------------------
    // Build properties
    // ----------------------------------------------------------------------
    XmlWriterUtil.writeLineBreak(writer, 2, 1);
    writer.startElement("property");
    writer.addAttribute("name", "maven.build.finalName");
    writer.addAttribute("value", project.getBuild().getFinalName());
    // property
    writer.endElement();
    writer.startElement("property");
    writer.addAttribute("name", "maven.build.dir");
    writer.addAttribute("value", AntBuildWriterUtil.toRelative(project.getBasedir(), project.getBuild().getDirectory()));
    // property
    writer.endElement();
    writer.startElement("property");
    writer.addAttribute("name", "maven.build.outputDir");
    writer.addAttribute("value", "${maven.build.dir}/" + AntBuildWriterUtil.toRelative(new File(project.getBuild().getDirectory()), project.getBuild().getOutputDirectory()));
    // property
    writer.endElement();
    if (!project.getCompileSourceRoots().isEmpty()) {
        List var = project.getCompileSourceRoots();
        String[] compileSourceRoots = (String[]) var.toArray(new String[var.size()]);
        for (int i = 0; i < compileSourceRoots.length; i++) {
            writer.startElement("property");
            writer.addAttribute("name", "maven.build.srcDir." + i);
            writer.addAttribute("value", AntBuildWriterUtil.toRelative(project.getBasedir(), compileSourceRoots[i]));
            // property
            writer.endElement();
        }
    }
    if (project.getBuild().getResources() != null) {
        List<Resource> var = project.getBuild().getResources();
        Resource[] array = var.toArray(new Resource[var.size()]);
        for (int i = 0; i < array.length; i++) {
            writer.startElement("property");
            writer.addAttribute("name", "maven.build.resourceDir." + i);
            writer.addAttribute("value", AntBuildWriterUtil.toRelative(project.getBasedir(), array[i].getDirectory()));
            // property
            writer.endElement();
        }
    }
    writer.startElement("property");
    writer.addAttribute("name", "maven.build.testOutputDir");
    writer.addAttribute("value", "${maven.build.dir}/" + AntBuildWriterUtil.toRelative(new File(project.getBuild().getDirectory()), project.getBuild().getTestOutputDirectory()));
    // property
    writer.endElement();
    if (!project.getTestCompileSourceRoots().isEmpty()) {
        List var = project.getTestCompileSourceRoots();
        String[] compileSourceRoots = (String[]) var.toArray(new String[var.size()]);
        for (int i = 0; i < compileSourceRoots.length; i++) {
            writer.startElement("property");
            writer.addAttribute("name", "maven.build.testDir." + i);
            writer.addAttribute("value", AntBuildWriterUtil.toRelative(project.getBasedir(), compileSourceRoots[i]));
            // property
            writer.endElement();
        }
    }
    if (project.getBuild().getTestResources() != null) {
        List<Resource> var = project.getBuild().getTestResources();
        Resource[] array = var.toArray(new Resource[var.size()]);
        for (int i = 0; i < array.length; i++) {
            writer.startElement("property");
            writer.addAttribute("name", "maven.build.testResourceDir." + i);
            writer.addAttribute("value", AntBuildWriterUtil.toRelative(project.getBasedir(), array[i].getDirectory()));
            // property
            writer.endElement();
        }
    }
    writer.startElement("property");
    writer.addAttribute("name", "maven.test.reports");
    writer.addAttribute("value", "${maven.build.dir}/test-reports");
    // property
    writer.endElement();
    String reportingOutputDir = project.getReporting().getOutputDirectory();
    // workaround for MNG-3475
    if (!new File(reportingOutputDir).isAbsolute()) {
        reportingOutputDir = new File(project.getBasedir(), reportingOutputDir).getAbsolutePath();
    }
    writer.startElement("property");
    writer.addAttribute("name", "maven.reporting.outputDirectory");
    writer.addAttribute("value", "${maven.build.dir}/" + AntBuildWriterUtil.toRelative(new File(project.getBuild().getDirectory()), reportingOutputDir));
    // property
    writer.endElement();
    // ----------------------------------------------------------------------
    // Setting properties
    // ----------------------------------------------------------------------
    XmlWriterUtil.writeLineBreak(writer, 2, 1);
    writer.startElement("property");
    writer.addAttribute("name", "maven.repo.local");
    writer.addAttribute("value", "${user.home}/.m2/repository");
    // property
    writer.endElement();
    writer.startElement("property");
    writer.addAttribute("name", "maven.settings.offline");
    writer.addAttribute("value", String.valueOf(settings.isOffline()));
    // property
    writer.endElement();
    writer.startElement("property");
    writer.addAttribute("name", "maven.settings.interactiveMode");
    writer.addAttribute("value", String.valueOf(settings.isInteractiveMode()));
    // property
    writer.endElement();
    XmlWriterUtil.writeLineBreak(writer);
}
Also used : Resource(org.apache.maven.model.Resource) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File)

Example 48 with Resource

use of org.apache.maven.model.Resource in project maven-plugins by apache.

the class AbstractJavadocMojo method getResource.

/**
     * @param outputFile        not nul
     * @param inputResourceName a not null resource in <code>src/main/java</code>, <code>src/main/resources</code> or
     *                          <code>src/main/javadoc</code> or in the Javadoc plugin dependencies.
     * @return the resource file absolute path as String
     * @since 2.6
     */
private String getResource(File outputFile, String inputResourceName) {
    if (inputResourceName.startsWith("/")) {
        inputResourceName = inputResourceName.replaceFirst("//*", "");
    }
    List<String> classPath = new ArrayList<String>();
    classPath.add(project.getBuild().getSourceDirectory());
    URL resourceURL = getResource(classPath, inputResourceName);
    if (resourceURL != null) {
        getLog().debug(inputResourceName + " found in the main src directory of the project.");
        return FileUtils.toFile(resourceURL).getAbsolutePath();
    }
    classPath.clear();
    List<Resource> resources = project.getBuild().getResources();
    for (Resource resource : resources) {
        classPath.add(resource.getDirectory());
    }
    resourceURL = getResource(classPath, inputResourceName);
    if (resourceURL != null) {
        getLog().debug(inputResourceName + " found in the main resources directories of the project.");
        return FileUtils.toFile(resourceURL).getAbsolutePath();
    }
    if (javadocDirectory.exists()) {
        classPath.clear();
        classPath.add(javadocDirectory.getAbsolutePath());
        resourceURL = getResource(classPath, inputResourceName);
        if (resourceURL != null) {
            getLog().debug(inputResourceName + " found in the main javadoc directory of the project.");
            return FileUtils.toFile(resourceURL).getAbsolutePath();
        }
    }
    classPath.clear();
    final String pluginId = "org.apache.maven.plugins:maven-javadoc-plugin";
    Plugin javadocPlugin = getPlugin(project, pluginId);
    if (javadocPlugin != null && javadocPlugin.getDependencies() != null) {
        List<Dependency> dependencies = javadocPlugin.getDependencies();
        for (Dependency dependency : dependencies) {
            JavadocPathArtifact javadocPathArtifact = new JavadocPathArtifact();
            javadocPathArtifact.setGroupId(dependency.getGroupId());
            javadocPathArtifact.setArtifactId(dependency.getArtifactId());
            javadocPathArtifact.setVersion(dependency.getVersion());
            Artifact artifact = null;
            try {
                artifact = createAndResolveArtifact(javadocPathArtifact);
            } catch (Exception e) {
                logError("Unable to retrieve the dependency: " + dependency + ". Ignored.", e);
            }
            if (artifact != null && artifact.getFile().exists()) {
                classPath.add(artifact.getFile().getAbsolutePath());
            }
        }
        resourceURL = getResource(classPath, inputResourceName);
        if (resourceURL != null) {
            getLog().debug(inputResourceName + " found in javadoc plugin dependencies.");
            try {
                JavadocUtil.copyResource(resourceURL, outputFile);
                return outputFile.getAbsolutePath();
            } catch (IOException e) {
                logError("IOException: " + e.getMessage(), e);
            }
        }
    }
    getLog().warn("Unable to find the resource '" + inputResourceName + "'. Using default Javadoc resources.");
    return null;
}
Also used : ArrayList(java.util.ArrayList) Resource(org.apache.maven.model.Resource) Dependency(org.apache.maven.model.Dependency) IOException(java.io.IOException) URL(java.net.URL) JavadocPathArtifact(org.apache.maven.plugin.javadoc.options.JavadocPathArtifact) Artifact(org.apache.maven.artifact.Artifact) DocletArtifact(org.apache.maven.plugin.javadoc.options.DocletArtifact) BootclasspathArtifact(org.apache.maven.plugin.javadoc.options.BootclasspathArtifact) ResourcesArtifact(org.apache.maven.plugin.javadoc.options.ResourcesArtifact) TagletArtifact(org.apache.maven.plugin.javadoc.options.TagletArtifact) CommandLineException(org.codehaus.plexus.util.cli.CommandLineException) ArtifactResolverException(org.apache.maven.shared.artifact.resolve.ArtifactResolverException) MavenInvocationException(org.apache.maven.shared.invoker.MavenInvocationException) InvalidDependencyVersionException(org.apache.maven.project.artifact.InvalidDependencyVersionException) ArtifactResolutionException(org.apache.maven.artifact.resolver.ArtifactResolutionException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) DependencyResolverException(org.apache.maven.shared.dependencies.resolve.DependencyResolverException) ProjectBuildingException(org.apache.maven.project.ProjectBuildingException) ArchiverException(org.codehaus.plexus.archiver.ArchiverException) ArtifactNotFoundException(org.apache.maven.artifact.resolver.ArtifactNotFoundException) FileNotFoundException(java.io.FileNotFoundException) NoSuchArchiverException(org.codehaus.plexus.archiver.manager.NoSuchArchiverException) MalformedURLException(java.net.MalformedURLException) MavenReportException(org.apache.maven.reporting.MavenReportException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) JavadocPathArtifact(org.apache.maven.plugin.javadoc.options.JavadocPathArtifact) Plugin(org.apache.maven.model.Plugin)

Example 49 with Resource

use of org.apache.maven.model.Resource in project maven-plugins by apache.

the class ProcessRemoteResourcesMojo method execute.

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException {
    if (skip) {
        getLog().info("Skipping remote resources execution.");
        return;
    }
    if (StringUtils.isEmpty(encoding)) {
        getLog().warn("File encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING + ", i.e. build is platform dependent!");
    }
    if (runOnlyAtExecutionRoot && !project.isExecutionRoot()) {
        getLog().info("Skipping remote-resource generation in this project because it's not the Execution Root");
        return;
    }
    if (resolveScopes == null) {
        if (excludeScope == null || "".equals(excludeScope)) {
            resolveScopes = new String[] { this.includeScope };
        } else {
            resolveScopes = new String[] { Artifact.SCOPE_TEST };
        }
    }
    velocity = new VelocityEngine();
    velocity.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);
    velocity.setProperty("resource.loader", "classpath");
    velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    velocity.init();
    if (supplementalModels == null) {
        File sups = new File(appendedResourcesDirectory, "supplemental-models.xml");
        if (sups.exists()) {
            try {
                supplementalModels = new String[] { sups.toURI().toURL().toString() };
            } catch (MalformedURLException e) {
                // ignore
                getLog().debug("URL issue with supplemental-models.xml: " + e.toString());
            }
        }
    }
    addSupplementalModelArtifacts();
    locator.addSearchPath(FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath());
    if (appendedResourcesDirectory != null) {
        locator.addSearchPath(FileResourceLoader.ID, appendedResourcesDirectory.getAbsolutePath());
    }
    locator.addSearchPath("url", "");
    locator.setOutputDirectory(new File(project.getBuild().getDirectory()));
    if (includeProjectProperties) {
        final Properties projectProperties = project.getProperties();
        for (Object key : projectProperties.keySet()) {
            properties.put(key.toString(), projectProperties.get(key).toString());
        }
    }
    ClassLoader origLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        validate();
        List<File> resourceBundleArtifacts = downloadBundles(resourceBundles);
        supplementModels = loadSupplements(supplementalModels);
        VelocityContext context = new VelocityContext(properties);
        configureVelocityContext(context);
        RemoteResourcesClassLoader classLoader = new RemoteResourcesClassLoader(null);
        initalizeClassloader(classLoader, resourceBundleArtifacts);
        Thread.currentThread().setContextClassLoader(classLoader);
        processResourceBundles(classLoader, context);
        try {
            if (outputDirectory.exists()) {
                // ----------------------------------------------------------------------------
                // Push our newly generated resources directory into the MavenProject so that
                // these resources can be picked up by the process-resources phase.
                // ----------------------------------------------------------------------------
                Resource resource = new Resource();
                resource.setDirectory(outputDirectory.getAbsolutePath());
                // MRRESOURCES-61 handle main and test resources separately
                if (attachToMain) {
                    project.getResources().add(resource);
                }
                if (attachToTest) {
                    project.getTestResources().add(resource);
                }
                // ----------------------------------------------------------------------------
                // Write out archiver dot file
                // ----------------------------------------------------------------------------
                File dotFile = new File(project.getBuild().getDirectory(), ".plxarc");
                FileUtils.mkdir(dotFile.getParentFile().getAbsolutePath());
                FileUtils.fileWrite(dotFile.getAbsolutePath(), outputDirectory.getName());
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Error creating dot file for archiving instructions.", e);
        }
    } finally {
        Thread.currentThread().setContextClassLoader(origLoader);
    }
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) MalformedURLException(java.net.MalformedURLException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) VelocityContext(org.apache.velocity.VelocityContext) Resource(org.apache.maven.model.Resource) IOException(java.io.IOException) Properties(java.util.Properties) ClasspathResourceLoader(org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader) File(java.io.File)

Example 50 with Resource

use of org.apache.maven.model.Resource in project maven-plugins by apache.

the class ProcessRemoteResourcesMojo method copyResourceIfExists.

protected boolean copyResourceIfExists(File file, String relFileName, VelocityContext context) throws IOException, MojoExecutionException {
    for (Resource resource : resources) {
        File resourceDirectory = new File(resource.getDirectory());
        if (!resourceDirectory.exists()) {
            continue;
        }
        // TODO - really should use the resource includes/excludes and name mapping
        File source = new File(resourceDirectory, relFileName);
        File templateSource = new File(resourceDirectory, relFileName + TEMPLATE_SUFFIX);
        if (!source.exists() && templateSource.exists()) {
            source = templateSource;
        }
        if (source.exists() && !source.equals(file)) {
            if (source == templateSource) {
                Reader reader = null;
                Writer writer = null;
                DeferredFileOutputStream os = new DeferredFileOutputStream(velocityFilterInMemoryThreshold, file);
                try {
                    if (encoding != null) {
                        reader = new InputStreamReader(new FileInputStream(source), encoding);
                        writer = new OutputStreamWriter(os, encoding);
                    } else {
                        reader = ReaderFactory.newPlatformReader(source);
                        writer = WriterFactory.newPlatformWriter(os);
                    }
                    velocity.evaluate(context, writer, "", reader);
                    writer.close();
                    writer = null;
                    reader.close();
                    reader = null;
                } catch (ParseErrorException e) {
                    throw new MojoExecutionException("Error rendering velocity resource: " + source, e);
                } catch (MethodInvocationException e) {
                    throw new MojoExecutionException("Error rendering velocity resource: " + source, e);
                } catch (ResourceNotFoundException e) {
                    throw new MojoExecutionException("Error rendering velocity resource: " + source, e);
                } finally {
                    IOUtil.close(writer);
                    IOUtil.close(reader);
                }
                fileWriteIfDiffers(os);
            } else if (resource.isFiltering()) {
                MavenFileFilterRequest req = setupRequest(resource, source, file);
                try {
                    fileFilter.copyFile(req);
                } catch (MavenFilteringException e) {
                    throw new MojoExecutionException("Error filtering resource: " + source, e);
                }
            } else {
                FileUtils.copyFile(source, file);
            }
            // exclude the original (so eclipse doesn't complain about duplicate resources)
            resource.addExclude(relFileName);
            return true;
        }
    }
    return false;
}
Also used : InputStreamReader(java.io.InputStreamReader) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MavenFilteringException(org.apache.maven.shared.filtering.MavenFilteringException) ParseErrorException(org.apache.velocity.exception.ParseErrorException) Resource(org.apache.maven.model.Resource) RemoteResourcesBundleXpp3Reader(org.apache.maven.plugin.resources.remote.io.xpp3.RemoteResourcesBundleXpp3Reader) Reader(java.io.Reader) MavenXpp3Reader(org.apache.maven.model.io.xpp3.MavenXpp3Reader) SupplementalDataModelXpp3Reader(org.apache.maven.plugin.resources.remote.io.xpp3.SupplementalDataModelXpp3Reader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) FileReader(java.io.FileReader) FileInputStream(java.io.FileInputStream) MavenFileFilterRequest(org.apache.maven.shared.filtering.MavenFileFilterRequest) OutputStreamWriter(java.io.OutputStreamWriter) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException) DeferredFileOutputStream(org.apache.commons.io.output.DeferredFileOutputStream) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) File(java.io.File) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter) FileWriter(java.io.FileWriter)

Aggregations

Resource (org.apache.maven.model.Resource)65 File (java.io.File)49 MavenProjectResourcesStub (org.apache.maven.plugins.resources.stub.MavenProjectResourcesStub)17 ArrayList (java.util.ArrayList)16 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)15 IOException (java.io.IOException)11 Properties (java.util.Properties)8 MojoFailureException (org.apache.maven.plugin.MojoFailureException)8 FileInputStream (java.io.FileInputStream)7 List (java.util.List)6 InputStream (java.io.InputStream)5 OutputStream (java.io.OutputStream)5 URL (java.net.URL)5 LinkedList (java.util.LinkedList)4 Map (java.util.Map)4 URLClassLoader (java.net.URLClassLoader)3 Iterator (java.util.Iterator)3 FileOutputStream (java.io.FileOutputStream)2 MalformedURLException (java.net.MalformedURLException)2 HashMap (java.util.HashMap)2