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);
}
}
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);
}
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;
}
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);
}
}
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;
}
Aggregations