/** Scans the source directories looking for source files to be decompiled. */ protected void scanSrc() throws BuildException { for (@SuppressWarnings("unchecked") Iterator<Resource> it = src.iterator(); it.hasNext(); ) { Resource resource = it.next(); FileResource fileResource = resource instanceof FileResource ? (FileResource) resource : null; if (fileResource != null) { File file = fileResource.getFile(); if (file.isDirectory()) { DirectoryScanner ds = getDirectoryScanner(file); String[] files = ds.getIncludedFiles(); scanDir(file, destdir != null ? destdir : file, files); } else { String[] files = new String[] {fileResource.getName()}; scanDir( fileResource.getBaseDir(), destdir != null ? destdir : fileResource.getBaseDir(), files); } } // else // { // //FIXME what to do? // } } }
/** * Calculates SHA1 and MD5 checksums for the files in the directory which match the specified * pattern. * * @param dir * @param pattern */ protected void calculateChecksums(File dir, String pattern) { if (calculateChecksums) { getConsole().debug("calculating checksums for artifacts in {0}", dir); FileSet repoSet = new FileSet(); repoSet.setProject(getProject()); repoSet.setDir(dir); repoSet.setIncludes(pattern); repoSet.setExcludes("*.sha1, *.md5, *.sig, *.asc"); Iterator<?> itr = repoSet.iterator(); while (itr.hasNext()) { FileResource file = (FileResource) itr.next(); byte[] bytes = FileUtils.readContent(file.getFile()); // calculate the SHA1 hash of the content and save result String sha1 = StringUtils.getSHA1(bytes); File sha1File = new File(dir, file.getFile().getName() + ".sha1"); FileUtils.writeContent(sha1File, sha1); getConsole().debug(1, "wrote {0}", sha1File); // add sha1 file to installed artifacts path reference(sha1File); // calculate the MD5 hash of the content and save result String md5 = StringUtils.getMD5(bytes); File md5File = new File(dir, file.getFile().getName() + ".md5"); FileUtils.writeContent(md5File, md5); getConsole().debug(1, "wrote {0}", md5File); // add md5 file to installed artifacts path reference(md5File); } } }
/** * Returns list of mapped files, that should be transformed. Files can by specified via attributes * (srcFile, srcDir) or resources (FileSet, FileList, DirSet, etc). Mapped file represents input * and output file for transformation. * * @return list of mapped files */ public List<MappedFile> getMappedFiles() { mappedFiles.clear(); // one src file if (getSrcFile() != null) { addMappedFile(getSrcFile()); } if (getSrcDir() != null) { addMappedFile(getSrcDir()); } Iterator element = resources.iterator(); while (element.hasNext()) { ResourceCollection rc = (ResourceCollection) element.next(); if (rc instanceof FileSet && rc.isFilesystemOnly()) { FileSet fs = (FileSet) rc; File fromDir = fs.getDir(getProject()); DirectoryScanner ds; try { ds = fs.getDirectoryScanner(getProject()); } catch (BuildException ex) { log("Could not scan directory " + fromDir, ex, Project.MSG_ERR); continue; } for (String f : ds.getIncludedFiles()) { addMappedFile(new File(fromDir + System.getProperty("file.separator") + f), fromDir); } } else { if (!rc.isFilesystemOnly()) { log("Only filesystem resources are supported", Project.MSG_WARN); continue; } Iterator rcIt = rc.iterator(); while (rcIt.hasNext()) { Resource r = (Resource) rcIt.next(); if (!r.isExists()) { log("Could not find resource " + r.toLongString(), Project.MSG_VERBOSE); continue; } if (r instanceof FileResource) { FileResource fr = (FileResource) r; addMappedFile(fr.getFile(), fr.getBaseDir()); } else { log( "Only file resources are supported (" + r.getClass().getSimpleName() + " found)", Project.MSG_WARN); continue; } } } } return mappedFiles; }
/** * @param artifactKey * @return * @throws ArtifactNotFoundException */ private FileResource resolveFile(String artifactKey) throws ArtifactNotFoundException { ArtifactDescriptor ad = new ArtifactDescriptor(artifactKey); if (classifier != null) { ad.classifier = classifier; } Artifact artifact = ad.getArtifact(); MavenClientFactory.getInstance().resolve(artifact); FileResource fr = new FileResource(artifact.getFile()); fr.setBaseDir(artifact.getFile().getParentFile()); return fr; }
/** * Get the list of all Ant files we want to process. These can be project and antlib files. * * @return antFiles a list of ant files to be processed */ public ArrayList getAntFiles(Project project, boolean homeOnly) { ArrayList antFiles = new ArrayList(); Map targets = project.getTargets(); Iterator targetsIter = targets.values().iterator(); String projectHome = null; try { projectHome = new File(project.getProperty("helium.dir")).getCanonicalPath(); while (targetsIter.hasNext()) { Target target = (Target) targetsIter.next(); String projectPath = new File(target.getLocation().getFileName()).getCanonicalPath(); if (!antFiles.contains(projectPath)) { if (homeOnly) { if (!projectPath.contains(projectHome)) { antFiles.add(projectPath); } } else antFiles.add(projectPath); } } if (rc != null) { Iterator extraFilesIter = rc.iterator(); while (extraFilesIter.hasNext()) { FileResource f = (FileResource) extraFilesIter.next(); String extrafile = f.getFile().getCanonicalPath(); if (!antFiles.contains(f.toString()) && !f.getFile().getName().startsWith("test_")) { if (homeOnly) { if (!extrafile.contains(projectHome)) { antFiles.add(extrafile); } } else antFiles.add(extrafile); } } } } catch (Exception e) { log(e.getMessage(), Project.MSG_ERR); e.printStackTrace(); } return antFiles; }
/** * Implementation of ResourceSelector.isSelected(). * * @param resource The resource to check * @return whether the resource is selected * @see ResourceSelector#isSelected(Resource) */ public boolean isSelected(Resource resource) { if (resource.isFilesystemOnly()) { // We have a 'resourced' file, so reconvert it and use // the 'old' implementation. FileResource fileResource = (FileResource) resource; File file = fileResource.getFile(); String filename = fileResource.getName(); File basedir = fileResource.getBaseDir(); return isSelected(basedir, filename, file); } else { try { // How to handle non-file-Resources? I copy temporarily the // resource to a file and use the file-implementation. FileUtils fu = FileUtils.getFileUtils(); File tmpFile = fu.createTempFile("modified-", ".tmp", null, true, false); Resource tmpResource = new FileResource(tmpFile); ResourceUtils.copyResource(resource, tmpResource); boolean isSelected = isSelected(tmpFile.getParentFile(), tmpFile.getName(), resource.toLongString()); tmpFile.delete(); return isSelected; } catch (UnsupportedOperationException uoe) { log( "The resource '" + resource.getName() + "' does not provide an InputStream, so it is not checked. " + "Akkording to 'selres' attribute value it is " + ((selectResourcesWithoutInputStream) ? "" : " not") + "selected.", Project.MSG_INFO); return selectResourcesWithoutInputStream; } catch (Exception e) { throw new BuildException(e); } } }
/** * Optional. Set a custom stylesheet to be used * * @param stylesheet The custom stylesheet */ public void setStylesheet(FileResource stylesheet) { this.log("Setting custom stylesheet " + stylesheet.toString(), LogLevel.DEBUG.getLevel()); this.stylesheet = stylesheet; }
/** * Required. Sets the destination directory of the generated files. * * @param destDir The destination directory. */ public void setDestDir(FileResource destDir) { if (!destDir.isDirectory()) { throw new BuildException("Destination path " + destDir + " is not a directory."); } this.destDir = destDir; }
@Override public void execute() throws BuildException { build = (Build) getProject().getReference(Key.build.referenceId()); console = build.getConsole(); if (!configured) { // called from moxie.package configure(build); } if (fatjar && excludeClasspathJars) { throw new BuildException("Can not specify fatjar and excludeClasspathJars!"); } // automatic manifest entries from Moxie metadata configureManifest(mft); if (mainclass == null) { String mc = build.getConfig().getProjectConfig().getMainclass(); if (!StringUtils.isEmpty(mc)) { ClassSpec cs = new ClassSpec(getProject()); mainclass = cs; mainclass.setName(mc); jarSpecs.add(cs); } } if (mainclass != null) { String mc = mainclass.getName().replace('/', '.'); if (mc.endsWith(".class")) { mc = mc.substring(0, mc.length() - ".class".length()); } if (launcher == null) { // use specified mainclass setManifest(mft, "Main-Class", mc); } else { // inject Moxie Launcher class String mx = launcher.getName().replace('/', '.'); if (mx.endsWith(".class")) { mx = mx.substring(0, mx.length() - ".class".length()); } setManifest(mft, "Main-Class", mx); setManifest(mft, "mxMain-Class", mc); String paths = launcher.getPaths(); if (!StringUtils.isEmpty(paths)) { setManifest(mft, "mxMain-Paths", paths); } } } // automatic classpath resolution, if not manually specified if (classpath == null) { Path cp = buildClasspath(build, Scope.compile, tag); if (fatjar) { // FatJar generation classpath = createClasspath(); for (String path : cp.list()) { if (path.toLowerCase().endsWith(".jar")) { LibrarySpec lib = createLibrary(); lib.setJar(path); } else { PathElement element = classpath.createPathElement(); element.setPath(path); } } } else { // standard GenJar class dependency resolution classpath = cp; } } if (destFile == null) { setDestfile(build.getBuildArtifact(classifier)); } if (destFile.getParentFile() != null) { destFile.getParentFile().mkdirs(); } version = build.getPom().version; File outputFolder = build.getConfig().getOutputDirectory(Scope.compile); if (excludes == null) { excludes = Toolkit.DEFAULT_RESOURCE_EXCLUDES; } // include resources from the project source folders Resource resources = createResource(); if (!StringUtils.isEmpty(resourceFolderPrefix)) { resources.setPrefix(resourceFolderPrefix); } for (File dir : build.getConfig().getSourceDirectories(Scope.compile, tag)) { FileSet res = resources.createFileset(); res.setDir(dir); res.setExcludes(excludes); } if (includeResources) { // include resources from the project resource folders for (File dir : build.getConfig().getResourceDirectories(Scope.compile, tag)) { FileSet res = resources.createFileset(); res.setExcludes(excludes); res.setDir(dir); } for (Build module : build.getSolver().getLinkedModules()) { // include resources from module source folders File dir = module.getConfig().getOutputDirectory(Scope.compile); FileSet res = resources.createFileset(); res.setDir(dir); res.setExcludes(excludes); // include resources from the module resource folders for (File resDir : module.getConfig().getResourceDirectories(Scope.compile)) { FileSet resSet = resources.createFileset(); res.setExcludes(Toolkit.DEFAULT_RESOURCE_EXCLUDES); resSet.setDir(resDir); } } } if (isShowTitle()) { console.title(getClass(), destFile.getName()); } console.debug(getTaskName() + " configuration"); // display specified mxgenjar attributes MaxmlMap attributes = build.getConfig().getTaskAttributes(getTaskName()); AttributeReflector.logAttributes(this, attributes, console); // optionally inject MxLauncher utility if (launcher != null) { if (launcher.getName().equals(MxLauncher.class.getName().replace('.', '/') + ".class")) { // inject MxLauncher into the output folder of the project for (String cn : Arrays.asList(MxLauncher.class.getName(), MxLauncher.class.getName() + "$1")) { try { String fn = cn.replace('.', '/') + ".class"; InputStream is = MxLauncher.class.getResourceAsStream("/" + fn); if (is == null) { continue; } build.getConsole().log("Injecting {0} into output folder", cn); File file = new File(outputFolder, fn.replace('/', File.separatorChar)); if (file.exists()) { file.delete(); } file.getParentFile().mkdirs(); FileOutputStream os = new FileOutputStream(file, false); byte[] buffer = new byte[4096]; int len = 0; while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } is.close(); os.flush(); os.close(); // add these files to the jarSpecs ClassSpec cs = new ClassSpec(getProject()); cs.setName(cn); jarSpecs.add(cs); } catch (Exception e) { build .getConsole() .error(e, "Failed to inject {0} into {1}", launcher.getName(), outputFolder); } } } } long start = System.currentTimeMillis(); try { super.execute(); } catch (ResolutionFailedException e) { String msg; if (tag == null) { String template = "Unable to resolve: {0}\n\n{1} could not be located on the classpath.\n"; msg = MessageFormat.format( template, e.resolvingclass, e.missingclass, tag == null ? "classpath" : ("\"" + tag + "\" classpath"), tag); } else { String template = "Unable to resolve: {0}\n\n{1} could not be located on the \"{2}\" classpath.\nPlease add the \":{2}\" tag to the appropriate dependency in your Moxie descriptor file.\n"; msg = MessageFormat.format(template, e.resolvingclass, e.missingclass, tag); } throw new MoxieException(msg); } if (fatjar) { // try to merge duplicate META-INF/services files JarUtils.mergeMetaInfServices(console, destFile); } console.log(1, destFile.getAbsolutePath()); console.log( 1, "{0} KB, generated in {1} ms", (destFile.length() / 1024), System.currentTimeMillis() - start); /* * Build sources jar */ if (packageSources) { String name = destFile.getName(); if (!StringUtils.isEmpty(classifier)) { // replace the classifier with "sources" name = name.replace(classifier, "sources"); } else { // append -sources to the filename before the extension name = name.substring(0, name.lastIndexOf('.')) + "-sources" + name.substring(name.lastIndexOf('.')); } File sourcesFile = new File(destFile.getParentFile(), name); if (sourcesFile.exists()) { sourcesFile.delete(); } Jar jar = new Jar(); jar.setTaskName(getTaskName()); jar.setProject(getProject()); // set the destination file jar.setDestFile(sourcesFile); // use the resolved classes to determine included source files List<FileResource> sourceFiles = new ArrayList<FileResource>(); Map<File, Set<String>> packageResources = new HashMap<File, Set<String>>(); if (resolvedLocal.size() == 0) { console.warn( getTaskName() + " has not resolved any class files local to {0}", build.getPom().getManagementId()); } List<File> folders = build.getConfig().getSourceDirectories(Scope.compile, tag); for (String className : resolvedLocal) { String sourceName = className.substring(0, className.length() - ".class".length()).replace('.', '/') + ".java"; console.debug(sourceName); for (File folder : folders) { File file = new File(folder, sourceName); if (file.exists()) { FileResource resource = new FileResource(getProject(), file); resource.setBaseDir(folder); sourceFiles.add(resource); if (!packageResources.containsKey(folder)) { // always include default package resources packageResources.put(folder, new TreeSet<String>(Arrays.asList("/*"))); } String packagePath = FileUtils.getRelativePath(folder, file.getParentFile()); packageResources.get(folder).add(packagePath + "/*"); console.debug(1, file.getAbsolutePath()); break; } } } // add the discovered source files for the resolved classes jar.add(new FileResourceSet(sourceFiles)); // add the resolved package folders for resource files for (Map.Entry<File, Set<String>> entry : packageResources.entrySet()) { FileSet res = new FileSet(); res.setDir(entry.getKey()); res.setExcludes(excludes); StringBuilder includes = new StringBuilder(); for (String packageName : entry.getValue()) { includes.append(packageName + ","); } includes.setLength(includes.length() - 1); res.setIncludes(includes.toString()); console.debug("adding resource fileset {0}", entry.getKey()); console.debug(1, "includes={0}", includes.toString()); jar.add(res); } if (includeResources) { for (File dir : build.getConfig().getResourceDirectories(Scope.compile, tag)) { FileSet res = resources.createFileset(); res.setDir(dir); res.setExcludes(Toolkit.DEFAULT_RESOURCE_EXCLUDES); jar.add(res); } } // set the source jar manifest try { Manifest mft = new Manifest(); configureManifest(mft); jar.addConfiguredManifest(mft); } catch (ManifestException e) { console.error(e); } start = System.currentTimeMillis(); jar.execute(); console.log(1, sourcesFile.getAbsolutePath()); console.log( 1, "{0} KB, generated in {1} ms", (sourcesFile.length() / 1024), System.currentTimeMillis() - start); } }