/** * make room for a Manifest file. use a generated resource for JARS and for WARS use the manifest * in the webapp/meta-inf directory. * * @throws MojoExecutionException */ private void addManifestResource(EclipseWriterConfig config) throws MojoExecutionException { if (isJavaProject()) { // special case must be done first because it can add stuff to the classpath that will be // written by the superclass new RadManifestWriter().init(getLog(), config).write(); } if (isJavaProject() && !Constants.PROJECT_PACKAGING_EAR.equals(packaging) && !Constants.PROJECT_PACKAGING_WAR.equals(packaging) && !Constants.PROJECT_PACKAGING_EJB.equals(packaging) && !NO_GENERATED_RESOURCE_DIRNAME.equals(this.generatedResourceDirName)) { String generatedResourceDir = this.project.getBasedir().getAbsolutePath() + File.separatorChar + this.generatedResourceDirName; String metainfDir = generatedResourceDir + File.separatorChar + "META-INF"; new File(metainfDir).mkdirs(); final Resource resource = new Resource(); getLog().debug("Adding " + this.generatedResourceDirName + " to resources"); resource.setDirectory(generatedResourceDir); this.executedProject.addResource(resource); } if (Constants.PROJECT_PACKAGING_WAR.equals(packaging)) { new File(getWebContentBaseDirectory(config) + File.separatorChar + "META-INF").mkdirs(); } }
private List<Resource> getResources() { Resource appFolderResource = new Resource(); appFolderResource.setDirectory(this.appDirectory.getAbsolutePath()); appFolderResource.setFiltering(true); return Arrays.asList(appFolderResource); }
/** * Copies all found resource files, including test resources to the <code>targetFolder</code>. * * <p>Resource files to be copied are filtered or included according to the configurations inside * <code>project</code>'s pom.xml file. * * @param project project whose resource files to be copied * @param targetFolder matching resource files are stored in this directory */ public static void copyResourcesTo(MavenProject project, String targetFolder) { File targetFolderFile = new File(targetFolder); String includes; String excludes; List allResources = project.getResources(); allResources.addAll(project.getTestResources()); LOG.info("Copying resource files to runner.jar"); for (Object res : allResources) { if (!(res instanceof Resource)) { continue; } try { Resource resource = (Resource) res; File baseDir = new File(resource.getDirectory()); includes = resource.getIncludes().toString().replace("[", "").replace("]", "").replace(" ", ""); excludes = resource.getExcludes().toString().replace("[", "").replace("]", "").replace(" ", ""); List<String> resFiles = FileUtils.getFileNames(baseDir, includes, excludes, true, true); for (String resFile : resFiles) { File resourceFile = new File(resFile); LOG.info("Copying {} to {}", resourceFile.getName(), targetFolder); FileUtils.copyFileToDirectory(resourceFile, targetFolderFile); } } catch (IOException e) { LOG.warn("Error while trying to copy resource files", e); } } }
public void execute() throws MojoExecutionException { AetherUtil.setRepositorySystemSession(repoSession); AetherUtil.setRepositorySystem(repoSystem); mergerComponent = new KevoreeMergerComponent(); ContainerRoot model = KevoreeFactory.createContainerRoot(); if (sourceMarShellDirectory != null) { ContainerRoot model2 = executeOnDirectory(sourceMarShellDirectory); mergerComponent.merge(model, model2); } if (sourceMarShellDirectory2 != null) { ContainerRoot model2 = executeOnDirectory(sourceMarShellDirectory2); mergerComponent.merge(model, model2); } if (!sourceOutputDirectory.exists() && !sourceOutputDirectory.mkdirs()) { throw new MojoExecutionException( "Unable to build target packages " + sourceOutputDirectory.getAbsolutePath()); } KevoreeXmiHelper.save( sourceOutputDirectory.getAbsolutePath() + File.separator + "lib.kev", model); Resource resource = new Resource(); resource.setTargetPath("KEV-INF"); resource.setDirectory(sourceOutputDirectory.getAbsolutePath()); project.addResource(resource); }
private void addResources(List<URL> urls) throws IOException { if (this.addResources) { for (Resource resource : this.project.getResources()) { File directory = new File(resource.getDirectory()); urls.add(directory.toURI().toURL()); FileUtils.removeDuplicatesFromOutputDirectory(this.classesDirectory, directory); } } }
private void copyResourceFilesToTargetDir() throws IOException { for (Resource res : (List<Resource>) project.getResources()) { File resDir = new File(res.getDirectory()); FileUtils.copyDirectory(resDir, new File(target, resDir.getName())); } File manifest = new File(project.getBasedir(), "AndroidManifest.xml"); FileUtils.copyFileToDirectory(manifest, target); }
/** * todo: javadocs * * @param testResources */ private void includeConfigurationFile(final List<Resource> testResources) { for (final Resource rawResource : testResources) { if (rawResource.getDirectory() != null) { rawResource.addInclude(configurationFileName); } } }
private void addOutputToSourcesIfNeeded() { final Boolean add = addOutputDirectoryToCompilationSources; if (add == null || add.booleanValue()) { getLog().info("Source directory: " + outputDirectory + " added"); addCompileSourceRoot(project, outputDirectory.getAbsolutePath()); getLog().info("Resource directory: " + outputDirectory + " added"); Resource resourceDirectory = new Resource(); resourceDirectory.setDirectory(outputDirectory.getAbsolutePath()); project.addResource(resourceDirectory); } }
@Override protected void executeWithGems() throws MojoExecutionException, ScriptException, IOException, GemException { if (includeRubyResources != null) { // add it to the classpath so java classes can find the ruby files Resource resource = new Resource(); resource.setDirectory(project.getBasedir().getAbsolutePath()); for (String include : includeRubyResources) { resource.addInclude(include); } if (excludeRubyResources != null) { for (String exclude : excludeRubyResources) { resource.addExclude(exclude); } } addResource(project.getBuild().getResources(), resource); } if (includeBinStubs) { Resource resource = new Resource(); resource.setDirectory(gemsConfig.getBinDirectory().getAbsolutePath()); resource.addInclude("*"); resource.setTargetPath("META-INF/jruby.home/bin"); addResource(project.getBuild().getResources(), resource); } }
@Override protected List<File> getSources() { if (sources != null) { return sources; } List<File> sources = Lists.newArrayList(); for (String source : mavenProject.getCompileSourceRoots()) { sources.add(new File(source)); } for (Resource res : mavenProject.getResources()) { sources.add(new File(res.getDirectory())); } return sources; }
protected void includeDescriptorResource() { final Resource resource = new Resource(); final String sourcePath = outputDirectorySCR().getPath(); final String targetPath = targetDirectorySCR; resource.setDirectory(sourcePath); resource.setTargetPath(targetPath); getLog().info(""); getLog().info("including descriptor resource = " + resource); project.addResource(resource); }
/** * Find the file with given {@link #configurationFileName} in the testResources. * * @param testResources List<Resource> * @param log maven log to log with * @return File which may exist * @throws FileNotFoundException */ private File findConfigurationFile(final List<Resource> testResources, final Log log) throws FileNotFoundException { for (final Resource resource : testResources) { final String directory = resource.getDirectory(); // @todo I'm not sure if a resource's directory may be null assert (directory != null); if (log.isDebugEnabled()) { log.debug("try to find configuration in " + directory); } final boolean resourceContainsConfigFile = resource.getIncludes().contains(configurationFileName); final String fileName = directory + File.separator + configurationFileName; final File configFile = new File(fileName); final StringBuffer message = new StringBuffer(); message.append(configurationFileName).append(" "); if (resourceContainsConfigFile && configFile.exists() && configFile.isFile() && configFile.canRead()) { if (log.isDebugEnabled()) { message.append("found in the directory "); message.append(configFile.getParent()); log.debug(message.toString()); } return configFile; } else if (log.isDebugEnabled()) { message.append("not found"); log.debug(message.toString()); } } throw new FileNotFoundException(configurationFileName + " not found in " + testResources); }
public void execute() throws MojoExecutionException, MojoFailureException { String pkg = project.getPackaging(); if (pkg != null && pkg.equals("pom")) return; // skip POM modules Generator g = new Generator( outputDirectory, new Reporter() { public void debug(String msg) { getLog().debug(msg); } }); for (Resource res : (List<Resource>) project.getResources()) { File baseDir = new File(res.getDirectory()); if (!baseDir.exists()) continue; // this happens for example when POM inherits the default resource folder but no // such folder exists. FileSet fs = new FileSet(); fs.setDir(baseDir); for (String name : (List<String>) res.getIncludes()) fs.createInclude().setName(name); for (String name : (List<String>) res.getExcludes()) fs.createExclude().setName(name); for (String relPath : fs.getDirectoryScanner(new Project()).getIncludedFiles()) { File f = new File(baseDir, relPath); if (!f.getName().endsWith(".properties") || f.getName().contains("_")) continue; if (fileMask != null && !f.getName().equals(fileMask)) continue; try { g.generate(f, relPath); } catch (IOException e) { throw new MojoExecutionException("Failed to generate a class from " + f, e); } } } try { g.build(); } catch (IOException e) { throw new MojoExecutionException("Failed to generate source files", e); } project.addCompileSourceRoot(outputDirectory.getAbsolutePath()); }
private MavenProject createMavenProject(String projectRootPath) throws IOException { File projectFile = new File(projectRootPath + "/pom.xml").getAbsoluteFile(); MavenProject project = new MavenProject(); project.setFile(projectFile); project .getBuild() .setOutputDirectory( projectFile .getParentFile() .toPath() .resolve("target/classes") .toFile() .getCanonicalPath()); Resource resource = new Resource(); resource.setDirectory(new File(projectRootPath + "/src/main/resources").getAbsolutePath()); project.getResources().add(resource); return project; }
protected boolean checkResource(String sourceRoot) { // TODO: cache a processed list of Resources in a ThreadLocal as an optimization? sourceRoot = ensureTrailingSlash(sourceRoot); for (Resource resource : getProjectResources()) { String dir = ensureTrailingSlash(resource.getDirectory()); if (dir.equals(sourceRoot)) { getLog().info(sourceRoot + " already added as a resource folder; skipping."); continue; } if (dir.startsWith(sourceRoot) || sourceRoot.startsWith(dir)) { getLog() .warn( String.format( "Conflicting path between source folder (%s, to be added as resource) and resource (%s); skipping.", sourceRoot, dir)); return false; } } return true; }
/** * Copies webapp webResources from the specified directory. * * <p>Note that the <tt>webXml</tt> parameter could be null and may specify a file which is not * named <tt>web.xml<tt>. If the file exists, it will be copied to the <tt>META-INF</tt> directory * and renamed accordingly. * * @param resource the resource to copy * @param webappDirectory the target directory * @param filterProperties * @throws java.io.IOException if an error occurred while copying webResources */ public void copyResources(Resource resource, File webappDirectory, Properties filterProperties) throws IOException { if (!resource.getDirectory().equals(webappDirectory.getPath())) { getLog().info("Copy webapp webResources to " + webappDirectory.getAbsolutePath()); if (webappDirectory.exists()) { String[] fileNames = getWarFiles(resource); for (String fileName : fileNames) { if (resource.isFiltering()) { copyFilteredFile( new File(resource.getDirectory(), fileName), new File(webappDirectory, fileName), null, getFilterWrappers(), filterProperties); } else { copyFileIfModified( new File(resource.getDirectory(), fileName), new File(webappDirectory, fileName)); } } } } }
/** * Returns a list of filenames that should be copied over to the destination directory. * * @param resource the resource to be scanned * @return the array of filenames, relative to the sourceDir */ private String[] getWarFiles(Resource resource) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(resource.getDirectory()); if (resource.getIncludes() != null && !resource.getIncludes().isEmpty()) { scanner.setIncludes((String[]) resource.getIncludes().toArray(EMPTY_STRING_ARRAY)); } else { scanner.setIncludes(DEFAULT_INCLUDES); } if (resource.getExcludes() != null && !resource.getExcludes().isEmpty()) { scanner.setExcludes((String[]) resource.getExcludes().toArray(EMPTY_STRING_ARRAY)); } scanner.addDefaultExcludes(); scanner.scan(); return scanner.getIncludedFiles(); }
@SuppressWarnings("unchecked") public void execute() throws MojoExecutionException, MojoFailureException { try { if (failOnWarning) { jswarn = true; } jsErrorReporter_ = new ErrorReporter4Mojo(getLog(), jswarn); beforeProcess(); processDir(sourceDirectory, outputDirectory, null, null, true); for (Resource resource : resources) { File destRoot = outputDirectory; if (resource.getTargetPath() != null) { destRoot = new File(outputDirectory, resource.getTargetPath()); } processDir( new File(resource.getDirectory()), destRoot, resource.getIncludes(), resource.getExcludes(), true); } processDir(warSourceDirectory, webappDirectory, null, null, false); afterProcess(); getLog() .info( String.format( "nb warnings: %d, nb errors: %d", jsErrorReporter_.getWarningCnt(), jsErrorReporter_.getErrorCnt())); if (failOnWarning && (jsErrorReporter_.getWarningCnt() > 0)) { throw new MojoFailureException( "warnings on " + this.getClass().getSimpleName() + "=> failure ! (see log)"); } } catch (RuntimeException exc) { throw exc; } catch (MojoFailureException exc) { throw exc; } catch (MojoExecutionException exc) { throw exc; } catch (Exception exc) { throw new MojoExecutionException("wrap: " + exc.getMessage(), exc); } }
@Override public void execute() throws MojoExecutionException, MojoFailureException { try { URL url = new URL(war); String targetFile = url.getFile().substring(url.getFile().lastIndexOf('/') + 1); File tempWarFile = new File(tempWar.getAbsolutePath() + File.separator + targetFile); if (!tempWarFile.exists()) { getLog().info("Dowloading = " + war + " -> " + tempWarFile.getAbsolutePath()); UrlHelper.getFile(war, tempWarFile); } File previous = new File(tempWar.getAbsolutePath() + File.separator + "extracted"); if (previous.exists()) { previous.delete(); } previous = new File(tempWar.getAbsolutePath() + File.separator + "extracted"); Resource res = new Resource(); res.setDirectory(filteredWar.getAbsolutePath()); project.getResources().add(res); String[] names = new String[0]; if (filtered != null) { names = filtered.split(","); for (String name : Arrays.asList(names)) { System.out.println("Filter=" + name); } } ZipHelper.unzipToTempDir(tempWarFile, previous, Arrays.asList(names)); if (!filteredWar.exists()) { filteredWar.mkdirs(); } ZipHelper.zipFolder( previous.getAbsolutePath(), filteredWar.getAbsolutePath() + File.separator + targetFile); /* ZipHelper.unzipToTempDir(tempWarFile, outputClasses) BundlerHelper.copyWebInf(outputClasses); String sjars = singletonJars; if(sjars == null){ sjars = ""; } String[] lsjars = sjars.split(","); BundlerHelper.generateManifest(project, outputClasses,lsjars); Resource resource = new Resource(); resource.setDirectory(outputClasses.getPath()); project.getResources().add(resource); Resource resource2 = new Resource(); resource2.setDirectory(sourceOutputDirectory.getPath()+File.separator+"KEV-INF"); resource2.setTargetPath("KEV-INF"); project.getResources().add(resource2); */ // GENERATE KEVOREE COMPONENT WRAPPER /* Dependency dep = new Dependency(); dep.setArtifactId("org.kevoree.library.javase.webserver.servlet"); dep.setGroupId("org.kevoree.library.javase"); dep.setVersion(KevoreeFactory.getVersion()); dep.setType("bundle"); dep.setScope("compile"); project.getCompileDependencies().add(dep); Dependency dep2 = new Dependency(); dep2.setArtifactId("org.kevoree.library.javase.webserver"); dep2.setGroupId("org.kevoree.library.javase"); dep2.setVersion(KevoreeFactory.getVersion()); dep2.setType("bundle"); dep2.setScope("compile"); project.getCompileDependencies().add(dep2); */ /* Dependency dep3 = new Dependency(); dep3.setArtifactId("org.kevoree.extra.jetty"); dep3.setGroupId("org.kevoree.extra"); dep3.setVersion("8.1.0.RC2"); dep3.setType("bundle"); dep3.setScope("compile"); project.getCompileDependencies().add(dep3);*/ // WrapperGenerator.generate(sourceOutputDirectory,project,BundlerHelper.getWebInfParams(outputClasses),lsjars); // project.getBuild().setSourceDirectory(sourceOutputDirectory.getAbsolutePath()); } catch (Exception e) { e.printStackTrace(); getLog().error(e); } }
protected Resource createResource(String resourceDirectory) { Resource resource = new Resource(); resource.setDirectory(resourceDirectory); return resource; }
public MojoProjectStub(File projectDir) { this.basedir = projectDir; props.setProperty("basedir", this.basedir.getAbsolutePath()); File pom = new File(getBasedir(), "plugin-config.xml"); MavenXpp3Reader pomReader = new MavenXpp3Reader(); Model model = null; FileReader fileReader = null; try { fileReader = new FileReader(pom); model = pomReader.read(fileReader); setModel(model); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(fileReader); } setGroupId(model.getGroupId()); setArtifactId(model.getArtifactId()); setVersion(model.getVersion()); setName(model.getName()); setUrl(model.getUrl()); setPackaging(model.getPackaging()); setFile(pom); build = model.getBuild(); if (build == null) { build = new Build(); } File srcDir = getStandardDir(getBuild().getSourceDirectory(), "src/main/java"); getBuild().setSourceDirectory(srcDir.getAbsolutePath()); File targetDir = getStandardDir(getBuild().getDirectory(), "target"); getBuild().setDirectory(targetDir.getAbsolutePath()); File outputDir = getStandardDir(getBuild().getOutputDirectory(), "target/classes"); getBuild().setOutputDirectory(outputDir.getAbsolutePath()); List<Resource> resources = new ArrayList<Resource>(); resources.addAll(getBuild().getResources()); if (resources.isEmpty()) { resources = new ArrayList<Resource>(); Resource resource = new Resource(); File resourceDir = normalize("src/main/resources"); resource.setDirectory(resourceDir.getAbsolutePath()); makeDirs(resourceDir); resources.add(resource); } else { // Make this project work on windows ;-) for (Resource resource : resources) { File dir = normalize(resource.getDirectory()); resource.setDirectory(dir.getAbsolutePath()); } } getBuild().setResources(resources); }
/** @see org.apache.maven.plugin.eclipse.writers.EclipseWriter#write() */ public void write() throws MojoExecutionException { // check if it's necessary to create project specific settings Properties coreSettings = new Properties(); String source = IdeUtils.getCompilerSourceVersion(config.getProject()); String encoding = IdeUtils.getCompilerSourceEncoding(config.getProject()); String target = IdeUtils.getCompilerTargetVersion(config.getProject()); if (source != null) { coreSettings.put(PROP_JDT_CORE_COMPILER_SOURCE, source); coreSettings.put(PROP_JDT_CORE_COMPILER_COMPLIANCE, source); } if (encoding != null) { File basedir = config.getProject().getBasedir(); List compileSourceRoots = config.getProject().getCompileSourceRoots(); if (compileSourceRoots != null) { for (Object compileSourceRoot : compileSourceRoots) { String sourcePath = (String) compileSourceRoot; String relativePath = IdeUtils.toRelativeAndFixSeparator(basedir, new File(sourcePath), false); coreSettings.put(PROP_JDT_CORE_COMPILER_ENCODING + relativePath, encoding); } } List testCompileSourceRoots = config.getProject().getTestCompileSourceRoots(); if (testCompileSourceRoots != null) { for (Object testCompileSourceRoot : testCompileSourceRoots) { String sourcePath = (String) testCompileSourceRoot; String relativePath = IdeUtils.toRelativeAndFixSeparator(basedir, new File(sourcePath), false); coreSettings.put(PROP_JDT_CORE_COMPILER_ENCODING + relativePath, encoding); } } List resources = config.getProject().getResources(); if (resources != null) { for (Object resource1 : resources) { Resource resource = (Resource) resource1; String relativePath = IdeUtils.toRelativeAndFixSeparator(basedir, new File(resource.getDirectory()), false); coreSettings.put(PROP_JDT_CORE_COMPILER_ENCODING + relativePath, encoding); } } List testResources = config.getProject().getTestResources(); if (testResources != null) { for (Object testResource : testResources) { Resource resource = (Resource) testResource; String relativePath = IdeUtils.toRelativeAndFixSeparator(basedir, new File(resource.getDirectory()), false); coreSettings.put(PROP_JDT_CORE_COMPILER_ENCODING + relativePath, encoding); } } } if (target != null && !JDK_1_2_SOURCES.equals(target)) { coreSettings.put( "org.eclipse.jdt.core.compiler.codegen.targetPlatform", target); // $NON-NLS-1$ } // write the settings, if needed if (!coreSettings.isEmpty()) { File settingsDir = new File( config.getEclipseProjectDirectory(), EclipseWorkspaceWriter.DIR_DOT_SETTINGS); // $NON-NLS-1$ settingsDir.mkdirs(); coreSettings.put(PROP_ECLIPSE_PREFERENCES_VERSION, "1"); // $NON-NLS-1$ try { File oldCoreSettingsFile; File coreSettingsFile = new File(settingsDir, EclipseWorkspaceWriter.ECLIPSE_JDT_CORE_PREFS_FILE); if (coreSettingsFile.exists()) { oldCoreSettingsFile = coreSettingsFile; Properties oldsettings = new Properties(); oldsettings.load(new FileInputStream(oldCoreSettingsFile)); Properties newsettings = (Properties) oldsettings.clone(); newsettings.putAll(coreSettings); if (!oldsettings.equals(newsettings)) { newsettings.store(new FileOutputStream(coreSettingsFile), null); } } else { coreSettings.store(new FileOutputStream(coreSettingsFile), null); log.info( Messages.getString( "EclipseSettingsWriter.wrotesettings", //$NON-NLS-1$ coreSettingsFile.getCanonicalPath())); } } catch (FileNotFoundException e) { throw new MojoExecutionException( Messages.getString("EclipseSettingsWriter.cannotcreatesettings"), e); // $NON-NLS-1$ } catch (IOException e) { throw new MojoExecutionException( Messages.getString("EclipseSettingsWriter.errorwritingsettings"), e); // $NON-NLS-1$ } } else { log.info(Messages.getString("EclipseSettingsWriter.usingdefaults")); // $NON-NLS-1$ } }
public void doExecute() throws MojoExecutionException, MojoFailureException { setup(); // java -cp gwt-dev.jar:gwt-user.jar // com.google.gwt.resources.css.InterfaceGenerator -standalone -typeName // some.package.MyCssResource -css // input.css if (cssFiles != null) { for (String file : cssFiles) { final String typeName = FilenameUtils.separatorsToSystem(file) .substring(0, file.lastIndexOf('.')) .replace(File.separatorChar, '.'); final File javaOutput = new File(getGenerateDirectory(), typeName.replace('.', File.separatorChar) + ".java"); for (Resource resource : getProject().getResources()) { final File candidate = new File(resource.getDirectory(), file); if (candidate.exists()) { if (buildContext.isUptodate(javaOutput, candidate)) { getLog().debug(javaOutput.getAbsolutePath() + " is up to date. Generation skipped"); break; } getLog().info("Generating " + javaOutput + " with typeName " + typeName); ensureTargetPackageExists(getGenerateDirectory(), typeName); try { final StringBuilder content = new StringBuilder(); createJavaCommand() .setMainClass("com.google.gwt.resources.css.InterfaceGenerator") .addToClasspath(getClasspath(Artifact.SCOPE_COMPILE)) .arg("-standalone") .arg("-typeName") .arg(typeName) .arg("-css") .arg(candidate.getAbsolutePath()) .addToClasspath(getJarFiles(GWT_DEV, false)) .addToClasspath(getJarFiles(GWT_USER, false)) .setOut( new StreamConsumer() { public void consumeLine(String line) { content.append(line).append(SystemUtils.LINE_SEPARATOR); } }) .execute(); if (content.length() == 0) { throw new MojoExecutionException( "cannot generate java source from file " + file + "."); } final OutputStreamWriter outputWriter = new OutputStreamWriter(buildContext.newFileOutputStream(javaOutput), encoding); try { outputWriter.write(content.toString()); } finally { IOUtil.close(outputWriter); } } catch (IOException e) { throw new MojoExecutionException("Failed to write to file: " + javaOutput, e); } catch (JavaCommandException e) { throw new MojoExecutionException(e.getMessage(), e); } break; } } } } }
/** * Scan the given resource to receive a full files list to work on. It should consist only of the * files explicitly (or implicitly) included and excluded via plugin configuration. See {@link * Resource} for details. Additionally, this method will filters resulted target file names via * provided RegExp filter. * * @param resource a {@link Resource} entry to scan * @return list of files with source and target info */ public final Map<File, File> getFileList( final Resource resource, final boolean excludeDefaults, final FileRenameRegexp fRenameRegxp) { final Map<File, File> workingFiles = new HashMap<File, File>(); final DirectoryScanner dirScanner = new DirectoryScanner(); dirScanner.setBasedir(resource.getDirectory()); if (resource.getIncludes().size() > 0) { dirScanner.setIncludes( resource.getIncludes().toArray(new String[resource.getIncludes().size()])); } if (resource.getExcludes().size() > 0) { if (excludeDefaults) { final String[] resourceExcludes = resource.getExcludes().toArray(new String[resource.getExcludes().size()]); final String[] excludes = ArrayUtils.addAll(resourceExcludes, getDefaultExcludes()); dirScanner.setExcludes(excludes); } else { dirScanner.setExcludes( resource.getExcludes().toArray(new String[resource.getExcludes().size()])); } } else { if (excludeDefaults) { dirScanner.setExcludes(getDefaultExcludes()); } } dirScanner.addDefaultExcludes(); dirScanner.scan(); final String[] includedFiles = dirScanner.getIncludedFiles(); for (final String file : includedFiles) { if (logger.isDebugEnabled()) { logger.debug("-- adding file: " + file); } String outputFileName; if (fRenameRegxp != null) { outputFileName = file.replaceAll( fRenameRegxp.getPattern(), fRenameRegxp.getReplace() != null ? fRenameRegxp.getReplace() : ""); } else { outputFileName = file; } if (resource.getTargetPath() != null || resource.getTargetPath().length() == 0) { // NOPMD workingFiles.put( new File(resource.getDirectory() + "/" + file), new File(resource.getTargetPath() + "/" + outputFileName)); // NOPMD } else { workingFiles.put( new File(resource.getDirectory() + "/" + file), new File(resource.getDirectory() + "/" + outputFileName)); // NOPMD } } return workingFiles; }
@Override public void execute() throws MojoExecutionException { Path warExecFile = Paths.get(buildDirectory, finalName); try { Files.deleteIfExists(warExecFile); Files.createDirectories(warExecFile.getParent()); try (OutputStream os = Files.newOutputStream(warExecFile); ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR, os)) { // If project is a war project add the war to the project if ("war".equalsIgnoreCase(project.getPackaging())) { File projectArtifact = project.getArtifact().getFile(); if (projectArtifact != null && Files.exists(projectArtifact.toPath())) { aos.putArchiveEntry(new JarArchiveEntry(projectArtifact.getName())); try (InputStream is = Files.newInputStream(projectArtifact.toPath())) { IOUtils.copy(is, aos); } aos.closeArchiveEntry(); } } // Add extraWars into the jar if (extraWars != null) { for (Dependency extraWarDependency : extraWars) { ArtifactRequest request = new ArtifactRequest(); request.setArtifact( new DefaultArtifact( extraWarDependency.getGroupId(), extraWarDependency.getArtifactId(), extraWarDependency.getType(), extraWarDependency.getVersion())); request.setRepositories(projectRepos); ArtifactResult result; try { result = repoSystem.resolveArtifact(repoSession, request); } catch (ArtifactResolutionException e) { throw new MojoExecutionException(e.getMessage(), e); } File extraWarFile = result.getArtifact().getFile(); aos.putArchiveEntry(new JarArchiveEntry(extraWarFile.getName())); try (InputStream is = Files.newInputStream(extraWarFile.toPath())) { IOUtils.copy(is, aos); } aos.closeArchiveEntry(); } } // Add extraResources into the jar. Folder /extra if (extraResources != null) { for (Resource extraResource : extraResources) { DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(extraResource.getDirectory()); directoryScanner.setExcludes( extraResource .getExcludes() .toArray(new String[extraResource.getExcludes().size()])); if (!extraResource.getIncludes().isEmpty()) { directoryScanner.setIncludes( extraResource .getIncludes() .toArray(new String[extraResource.getIncludes().size()])); } else { // include everything by default directoryScanner.setIncludes(new String[] {"**"}); } directoryScanner.scan(); for (String includeFile : directoryScanner.getIncludedFiles()) { aos.putArchiveEntry( new JarArchiveEntry(Runner.EXTRA_RESOURCES_DIR + "/" + includeFile)); Path extraFile = Paths.get(extraResource.getDirectory(), includeFile); try (InputStream is = Files.newInputStream(extraFile)) { IOUtils.copy(is, aos); } aos.closeArchiveEntry(); } } } Set<String> includeArtifacts = new HashSet<>(); includeArtifacts.add("org.apache.tomcat:tomcat-jdbc"); includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-core"); includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-logging-juli"); includeArtifacts.add("org.yaml:snakeyaml"); includeArtifacts.add("com.beust:jcommander"); if (includeJSPSupport) { includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-jasper"); includeArtifacts.add("org.eclipse.jdt.core.compiler:ecj"); } for (Artifact pluginArtifact : pluginArtifacts) { String artifactName = pluginArtifact.getGroupId() + ":" + pluginArtifact.getArtifactId(); if (includeArtifacts.contains(artifactName)) { try (JarFile jarFile = new JarFile(pluginArtifact.getFile())) { extractJarToArchive(jarFile, aos); } } } if (extraDependencies != null) { for (Dependency dependency : extraDependencies) { ArtifactRequest request = new ArtifactRequest(); request.setArtifact( new DefaultArtifact( dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(), dependency.getVersion())); request.setRepositories(projectRepos); ArtifactResult result; try { result = repoSystem.resolveArtifact(repoSession, request); } catch (ArtifactResolutionException e) { throw new MojoExecutionException(e.getMessage(), e); } try (JarFile jarFile = new JarFile(result.getArtifact().getFile())) { extractJarToArchive(jarFile, aos); } } } if (includeJSPSupport) { addFile(aos, "/conf/web.xml", "conf/web.xml"); } else { addFile(aos, "/conf/web_wo_jsp.xml", "conf/web.xml"); } addFile(aos, "/conf/logging.properties", "conf/logging.properties"); if (includeTcNativeWin32 != null) { aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.32")); Files.copy(Paths.get(includeTcNativeWin32), aos); aos.closeArchiveEntry(); } if (includeTcNativeWin64 != null) { aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.64")); Files.copy(Paths.get(includeTcNativeWin64), aos); aos.closeArchiveEntry(); } String[] runnerClasses = { "ch.rasc.embeddedtc.runner.CheckConfig$CheckConfigOptions", "ch.rasc.embeddedtc.runner.CheckConfig", "ch.rasc.embeddedtc.runner.Config", "ch.rasc.embeddedtc.runner.Shutdown", "ch.rasc.embeddedtc.runner.Context", "ch.rasc.embeddedtc.runner.DeleteDirectory", "ch.rasc.embeddedtc.runner.ObfuscateUtil$ObfuscateOptions", "ch.rasc.embeddedtc.runner.ObfuscateUtil", "ch.rasc.embeddedtc.runner.Runner$1", "ch.rasc.embeddedtc.runner.Runner$2", "ch.rasc.embeddedtc.runner.Runner$StartOptions", "ch.rasc.embeddedtc.runner.Runner$StopOptions", "ch.rasc.embeddedtc.runner.Runner$RunnerShutdownHook", "ch.rasc.embeddedtc.runner.Runner" }; for (String rc : runnerClasses) { String classAsPath = rc.replace('.', '/') + ".class"; try (InputStream is = getClass().getResourceAsStream("/" + classAsPath)) { aos.putArchiveEntry(new JarArchiveEntry(classAsPath)); IOUtils.copy(is, aos); aos.closeArchiveEntry(); } } Manifest manifest = new Manifest(); Manifest.Attribute mainClassAtt = new Manifest.Attribute(); mainClassAtt.setName("Main-Class"); mainClassAtt.setValue(Runner.class.getName()); manifest.addConfiguredAttribute(mainClassAtt); aos.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF")); manifest.write(aos); aos.closeArchiveEntry(); aos.putArchiveEntry(new JarArchiveEntry(Runner.TIMESTAMP_FILENAME)); aos.write(String.valueOf(System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8)); aos.closeArchiveEntry(); } } catch (IOException | ArchiveException | ManifestException e) { throw new MojoExecutionException(e.getMessage(), e); } }
public static void prepareLanguage( Log log, MavenProject project, MavenProjectHelper projectHelper, File languageOutDir, File schemaOutDir, BuildContext buildContext) throws MojoExecutionException { File camelMetaDir = new File(languageOutDir, "META-INF/services/org/apache/camel/"); // first we need to setup the output directory because the next check // can stop the build before the end and eclipse always needs to know about that directory if (projectHelper != null) { projectHelper.addResource( project, languageOutDir.getPath(), Collections.singletonList("**/dataformat.properties"), Collections.emptyList()); } if (!PackageHelper.haveResourcesChanged( log, project, buildContext, "META-INF/services/org/apache/camel/language")) { return; } Map<String, String> javaTypes = new HashMap<String, String>(); StringBuilder buffer = new StringBuilder(); int count = 0; for (Resource r : project.getBuild().getResources()) { File f = new File(r.getDirectory()); if (!f.exists()) { f = new File(project.getBasedir(), r.getDirectory()); } f = new File(f, "META-INF/services/org/apache/camel/language"); if (f.exists() && f.isDirectory()) { File[] files = f.listFiles(); if (files != null) { for (File file : files) { String javaType = readClassFromCamelResource(file, buffer, buildContext); if (!file.isDirectory() && file.getName().charAt(0) != '.') { count++; } if (javaType != null) { javaTypes.put(file.getName(), javaType); } } } } } // find camel-core and grab the data format model from there, and enrich this model with // information from this artifact // and create json schema model file for this data format try { if (count > 0) { Artifact camelCore = findCamelCoreArtifact(project); if (camelCore != null) { File core = camelCore.getFile(); if (core != null) { URL url = new URL("file", null, core.getAbsolutePath()); URLClassLoader loader = new URLClassLoader(new URL[] {url}); for (Map.Entry<String, String> entry : javaTypes.entrySet()) { String name = entry.getKey(); String javaType = entry.getValue(); String modelName = asModelName(name); InputStream is = loader.getResourceAsStream( "org/apache/camel/model/language/" + modelName + ".json"); if (is == null) { // use file input stream if we build camel-core itself, and thus do not have a JAR // which can be loaded by URLClassLoader is = new FileInputStream( new File(core, "org/apache/camel/model/language/" + modelName + ".json")); } String json = loadText(is); if (json != null) { LanguageModel languageModel = new LanguageModel(); languageModel.setName(name); languageModel.setTitle(""); languageModel.setModelName(modelName); languageModel.setLabel(""); languageModel.setDescription(""); languageModel.setJavaType(javaType); languageModel.setGroupId(project.getGroupId()); languageModel.setArtifactId(project.getArtifactId()); languageModel.setVersion(project.getVersion()); List<Map<String, String>> rows = JSonSchemaHelper.parseJsonSchema("model", json, false); for (Map<String, String> row : rows) { if (row.containsKey("title")) { languageModel.setTitle(row.get("title")); } if (row.containsKey("description")) { languageModel.setDescription(row.get("description")); } if (row.containsKey("label")) { languageModel.setLabel(row.get("label")); } if (row.containsKey("javaType")) { languageModel.setModelJavaType(row.get("javaType")); } } log.debug("Model " + languageModel); // build json schema for the data format String properties = after(json, " \"properties\": {"); String schema = createParameterJsonSchema(languageModel, properties); log.debug("JSon schema\n" + schema); // write this to the directory File dir = new File(schemaOutDir, schemaSubDirectory(languageModel.getJavaType())); dir.mkdirs(); File out = new File(dir, name + ".json"); OutputStream fos = buildContext.newFileOutputStream(out); fos.write(schema.getBytes()); fos.close(); buildContext.refresh(out); log.debug("Generated " + out + " containing JSon schema for " + name + " language"); } } } } } } catch (Exception e) { throw new MojoExecutionException( "Error loading language model from camel-core. Reason: " + e, e); } if (count > 0) { Properties properties = new Properties(); String names = buffer.toString(); properties.put("languages", names); properties.put("groupId", project.getGroupId()); properties.put("artifactId", project.getArtifactId()); properties.put("version", project.getVersion()); properties.put("projectName", project.getName()); if (project.getDescription() != null) { properties.put("projectDescription", project.getDescription()); } camelMetaDir.mkdirs(); File outFile = new File(camelMetaDir, "language.properties"); // check if the existing file has the same content, and if so then leave it as is so we do not // write any changes // which can cause a re-compile of all the source code if (outFile.exists()) { try { Properties existing = new Properties(); InputStream is = new FileInputStream(outFile); existing.load(is); is.close(); // are the content the same? if (existing.equals(properties)) { log.debug("No language changes detected"); return; } } catch (IOException e) { // ignore } } try { OutputStream os = buildContext.newFileOutputStream(outFile); properties.store(os, "Generated by camel-package-maven-plugin"); os.close(); log.info( "Generated " + outFile + " containing " + count + " Camel " + (count > 1 ? "languages: " : "language: ") + names); if (projectHelper != null) { projectHelper.attachArtifact(project, "properties", "camelLanguage", outFile); } } catch (IOException e) { throw new MojoExecutionException( "Failed to write properties to " + outFile + ". Reason: " + e, e); } } else { log.debug( "No META-INF/services/org/apache/camel/language directory found. Are you sure you have created a Camel language?"); } }