List of usage examples for java.util.jar Manifest getMainAttributes
public Attributes getMainAttributes()
From source file:org.apache.openejb.config.DeploymentLoader.java
@SuppressWarnings("unchecked") public Class<? extends DeploymentModule> discoverModuleType(final URL baseUrl, final ClassLoader classLoader, final Set<RequireDescriptors> requireDescriptor) throws IOException, UnknownModuleTypeException { final boolean scanPotentialEjbModules = !requireDescriptor.contains(RequireDescriptors.EJB); final boolean scanPotentialClientModules = !requireDescriptor.contains(RequireDescriptors.CLIENT); URL pathToScanDescriptors = baseUrl; String path;// ww w. j a v a 2 s . co m if (baseUrl != null) { path = URLs.toFile(baseUrl).getAbsolutePath(); if (baseUrl.getProtocol().equals("file") && path.endsWith("WEB-INF/classes/")) { //EJB found in WAR/WEB-INF/classes, scan WAR for ejb-jar.xml pathToScanDescriptors = new URL(path.substring(0, path.lastIndexOf("WEB-INF/classes/"))); } } else { path = ""; } final Map<String, URL> descriptors = getDescriptors(classLoader, pathToScanDescriptors); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } if (path.endsWith(".xml") || path.endsWith(".json")) { // let say it is a resource module return ResourcesModule.class; } if (descriptors.containsKey("application.xml") || path.endsWith(".ear")) { return AppModule.class; } if (descriptors.containsKey("ra.xml") || path.endsWith(".rar")) { return ConnectorModule.class; } if (baseUrl != null) { final Map<String, URL> webDescriptors = getWebDescriptors(getFile(baseUrl)); if (webDescriptors.containsKey("web.xml") || webDescriptors.containsKey(WEB_FRAGMENT_XML) // descriptor || path.endsWith(".war") || new File(path, "WEB-INF").exists()) { // webapp specific files return WebModule.class; } } if (descriptors.containsKey("ejb-jar.xml") || descriptors.containsKey("beans.xml")) { return EjbModule.class; } if (descriptors.containsKey("application-client.xml")) { return ClientModule.class; } final URL manifestUrl = descriptors.get("MANIFEST.MF"); if (scanPotentialClientModules && manifestUrl != null) { // In this case scanPotentialClientModules really means "require application-client.xml" final InputStream is = new BufferedInputStream(manifestUrl.openStream()); final Manifest manifest = new Manifest(is); final String mainClass = manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS); if (mainClass != null) { return ClientModule.class; } } final Class<? extends DeploymentModule> cls = checkAnnotations(baseUrl, classLoader, scanPotentialEjbModules, scanPotentialClientModules); if (cls != null) { return cls; } if (descriptors.containsKey("persistence.xml") || descriptors.containsKey("persistence-fragment.xml")) { return PersistenceModule.class; } //#TOMEE-613 final File file = URLs.toFile(baseUrl); if (DeploymentsResolver.isValidDirectory(file)) { final File[] files = file.listFiles(); if (containsEarAssets(files)) { return AppModule.class; } if (containsWebAssets(files)) { return WebModule.class; } } final Class<? extends DeploymentModule> defaultType = (Class<? extends DeploymentModule>) SystemInstance .get().getOptions().get("openejb.default.deployment-module", (Class<?>) null); if (defaultType != null) { // should we do a better filtering? it seems enough for common cases. if (WebModule.class.equals(defaultType) && (path.endsWith(".jar!") || path.endsWith(".jar"))) { throw new UnknownModuleTypeException("Unknown module type: url=" + path + " which can't be a war."); } logger.debug("type for '" + path + "' was not found, defaulting to " + defaultType.getSimpleName()); return defaultType; } throw new UnknownModuleTypeException("Unknown module type: url=" + path); // baseUrl can be null }
From source file:org.apache.catalina.loader.WebappClassLoader.java
/** * Returns true if the specified package name is sealed according to the * given manifest.//from ww w.j a va 2 s . co m */ protected boolean isPackageSealed(String name, Manifest man) { String path = name + "/"; Attributes attr = man.getAttributes(path); String sealed = null; if (attr != null) { sealed = attr.getValue(Name.SEALED); } if (sealed == null) { if ((attr = man.getMainAttributes()) != null) { sealed = attr.getValue(Name.SEALED); } } return "true".equalsIgnoreCase(sealed); }
From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java
/** * <p>//from w w w . j a v a2s.c o m * Reads the manifest from the JAR file and collects the entries. Some * vendorKey entries are:</p> * <ul><li>Implementation Title</li> * <li>Implementation Version</li> <li>Implementation Vendor</li> * <li>Implementation VendorId</li> <li>Bundle Name</li> <li>Bundle * Version</li> <li>Bundle Vendor</li> <li>Bundle Description</li> <li>Main * Class</li> </ul> * However, all but a handful of specific entries are read in. * * @param dependency A reference to the dependency * @param classInformation a collection of class information * @return whether evidence was identified parsing the manifest * @throws IOException if there is an issue reading the JAR file */ protected boolean parseManifest(Dependency dependency, List<ClassNameInformation> classInformation) throws IOException { boolean foundSomething = false; JarFile jar = null; try { jar = new JarFile(dependency.getActualFilePath()); final Manifest manifest = jar.getManifest(); if (manifest == null) { if (!dependency.getFileName().toLowerCase().endsWith("-sources.jar") && !dependency.getFileName().toLowerCase().endsWith("-javadoc.jar") && !dependency.getFileName().toLowerCase().endsWith("-src.jar") && !dependency.getFileName().toLowerCase().endsWith("-doc.jar")) { LOGGER.debug("Jar file '{}' does not contain a manifest.", dependency.getFileName()); } return false; } final EvidenceCollection vendorEvidence = dependency.getVendorEvidence(); final EvidenceCollection productEvidence = dependency.getProductEvidence(); final EvidenceCollection versionEvidence = dependency.getVersionEvidence(); String source = "Manifest"; String specificationVersion = null; boolean hasImplementationVersion = false; Attributes atts = manifest.getMainAttributes(); for (Entry<Object, Object> entry : atts.entrySet()) { String key = entry.getKey().toString(); String value = atts.getValue(key); if (HTML_DETECTION_PATTERN.matcher(value).find()) { value = Jsoup.parse(value).text(); } if (IGNORE_VALUES.contains(value)) { continue; } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) { foundSomething = true; productEvidence.addEvidence(source, key, value, Confidence.HIGH); addMatchingValues(classInformation, value, productEvidence); } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) { hasImplementationVersion = true; foundSomething = true; versionEvidence.addEvidence(source, key, value, Confidence.HIGH); } else if ("specification-version".equalsIgnoreCase(key)) { specificationVersion = key; } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) { foundSomething = true; vendorEvidence.addEvidence(source, key, value, Confidence.HIGH); addMatchingValues(classInformation, value, vendorEvidence); } else if (key.equalsIgnoreCase(IMPLEMENTATION_VENDOR_ID)) { foundSomething = true; vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, vendorEvidence); } else if (key.equalsIgnoreCase(BUNDLE_DESCRIPTION)) { foundSomething = true; addDescription(dependency, value, "manifest", key); addMatchingValues(classInformation, value, productEvidence); } else if (key.equalsIgnoreCase(BUNDLE_NAME)) { foundSomething = true; productEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, productEvidence); // //the following caused false positives. // } else if (key.equalsIgnoreCase(BUNDLE_VENDOR)) { // foundSomething = true; // vendorEvidence.addEvidence(source, key, value, Confidence.HIGH); // addMatchingValues(classInformation, value, vendorEvidence); } else if (key.equalsIgnoreCase(BUNDLE_VERSION)) { foundSomething = true; versionEvidence.addEvidence(source, key, value, Confidence.HIGH); } else if (key.equalsIgnoreCase(Attributes.Name.MAIN_CLASS.toString())) { continue; //skipping main class as if this has important information to add // it will be added during class name analysis... if other fields // have the information from the class name then they will get added... } else { key = key.toLowerCase(); if (!IGNORE_KEYS.contains(key) && !key.endsWith("jdk") && !key.contains("lastmodified") && !key.endsWith("package") && !key.endsWith("classpath") && !key.endsWith("class-path") && !key.endsWith("-scm") //todo change this to a regex? && !key.startsWith("scm-") && !value.trim().startsWith("scm:") && !isImportPackage(key, value) && !isPackage(key, value)) { foundSomething = true; if (key.contains("version")) { if (!key.contains("specification")) { versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM); } } else if ("build-id".equals(key)) { int pos = value.indexOf('('); if (pos >= 0) { value = value.substring(0, pos - 1); } pos = value.indexOf('['); if (pos >= 0) { value = value.substring(0, pos - 1); } versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM); } else if (key.contains("title")) { productEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, productEvidence); } else if (key.contains("vendor")) { if (key.contains("specification")) { vendorEvidence.addEvidence(source, key, value, Confidence.LOW); } else { vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, vendorEvidence); } } else if (key.contains("name")) { productEvidence.addEvidence(source, key, value, Confidence.MEDIUM); vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, vendorEvidence); addMatchingValues(classInformation, value, productEvidence); } else if (key.contains("license")) { addLicense(dependency, value); } else if (key.contains("description")) { addDescription(dependency, value, "manifest", key); } else { productEvidence.addEvidence(source, key, value, Confidence.LOW); vendorEvidence.addEvidence(source, key, value, Confidence.LOW); addMatchingValues(classInformation, value, vendorEvidence); addMatchingValues(classInformation, value, productEvidence); if (value.matches(".*\\d.*")) { final StringTokenizer tokenizer = new StringTokenizer(value, " "); while (tokenizer.hasMoreElements()) { final String s = tokenizer.nextToken(); if (s.matches("^[0-9.]+$")) { versionEvidence.addEvidence(source, key, s, Confidence.LOW); } } } } } } } for (Map.Entry<String, Attributes> item : manifest.getEntries().entrySet()) { final String name = item.getKey(); source = "manifest: " + name; atts = item.getValue(); for (Entry<Object, Object> entry : atts.entrySet()) { final String key = entry.getKey().toString(); final String value = atts.getValue(key); if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) { foundSomething = true; productEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, productEvidence); } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) { foundSomething = true; versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM); } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) { foundSomething = true; vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, vendorEvidence); } else if (key.equalsIgnoreCase(Attributes.Name.SPECIFICATION_TITLE.toString())) { foundSomething = true; productEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, productEvidence); } } } if (specificationVersion != null && !hasImplementationVersion) { foundSomething = true; versionEvidence.addEvidence(source, "specification-version", specificationVersion, Confidence.HIGH); } } finally { if (jar != null) { jar.close(); } } return foundSomething; }
From source file:dalma.container.ClassLoaderImpl.java
/** * Define the package information when the class comes from a * jar with a manifest//w w w . j ava 2s .co m * * @param container the jar file containing the manifest * @param packageName the name of the package being defined. * @param manifest the jar's manifest */ protected void definePackage(File container, String packageName, Manifest manifest) { String sectionName = packageName.replace('.', '/') + "/"; String specificationTitle = null; String specificationVendor = null; String specificationVersion = null; String implementationTitle = null; String implementationVendor = null; String implementationVersion = null; String sealedString = null; URL sealBase = null; Attributes sectionAttributes = manifest.getAttributes(sectionName); if (sectionAttributes != null) { specificationTitle = sectionAttributes.getValue(Attributes.Name.SPECIFICATION_TITLE); specificationVendor = sectionAttributes.getValue(Attributes.Name.SPECIFICATION_VENDOR); specificationVersion = sectionAttributes.getValue(Attributes.Name.SPECIFICATION_VERSION); implementationTitle = sectionAttributes.getValue(Attributes.Name.IMPLEMENTATION_TITLE); implementationVendor = sectionAttributes.getValue(Attributes.Name.IMPLEMENTATION_VENDOR); implementationVersion = sectionAttributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION); sealedString = sectionAttributes.getValue(Attributes.Name.SEALED); } Attributes mainAttributes = manifest.getMainAttributes(); if (mainAttributes != null) { if (specificationTitle == null) { specificationTitle = mainAttributes.getValue(Attributes.Name.SPECIFICATION_TITLE); } if (specificationVendor == null) { specificationVendor = mainAttributes.getValue(Attributes.Name.SPECIFICATION_VENDOR); } if (specificationVersion == null) { specificationVersion = mainAttributes.getValue(Attributes.Name.SPECIFICATION_VERSION); } if (implementationTitle == null) { implementationTitle = mainAttributes.getValue(Attributes.Name.IMPLEMENTATION_TITLE); } if (implementationVendor == null) { implementationVendor = mainAttributes.getValue(Attributes.Name.IMPLEMENTATION_VENDOR); } if (implementationVersion == null) { implementationVersion = mainAttributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION); } if (sealedString == null) { sealedString = mainAttributes.getValue(Attributes.Name.SEALED); } } if (sealedString != null && sealedString.equalsIgnoreCase("true")) { try { sealBase = new URL("file:" + container.getPath()); } catch (MalformedURLException e) { // ignore } } definePackage(packageName, specificationTitle, specificationVersion, specificationVendor, implementationTitle, implementationVersion, implementationVendor, sealBase); }
From source file:me.azenet.UHPlugin.UHPluginCommand.java
/** * This command prints some informations about the plugin and the translation. * //from w w w . j a v a2s. co m * Usage: /uh about * * @param sender * @param command * @param label * @param args */ @SuppressWarnings("unused") private void doAbout(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player) sender.sendMessage(""); sender.sendMessage( i.t("cmd.titleHelp", p.getDescription().getDescription(), p.getDescription().getVersion())); // Authors String authors = ""; List<String> listAuthors = p.getDescription().getAuthors(); for (String author : listAuthors) { if (author == listAuthors.get(0)) { // Nothing } else if (author == listAuthors.get(listAuthors.size() - 1)) { authors += " " + i.t("about.and") + " "; } else { authors += ", "; } authors += author; } sender.sendMessage(i.t("about.authors", authors)); // Build number String build = null; try { Class<? extends UHPlugin> clazz = p.getClass(); String className = clazz.getSimpleName() + ".class"; String classPath = clazz.getResource(className).toString(); if (classPath.startsWith("jar")) { // Class from JAR String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF"; Manifest manifest = new Manifest(new URL(manifestPath).openStream()); Attributes attr = manifest.getMainAttributes(); build = attr.getValue("Git-Commit"); } } catch (IOException e) { // Build not available. } if (build != null) { sender.sendMessage(i.t("about.build.number", build)); } else { sender.sendMessage(i.t("about.build.notAvailable")); } // Translation sender.sendMessage(i.t("about.i18n.title")); sender.sendMessage( i.t("about.i18n.selected", i.getSelectedLanguage(), i.getTranslator(i.getSelectedLanguage()))); sender.sendMessage( i.t("about.i18n.fallback", i.getDefaultLanguage(), i.getTranslator(i.getDefaultLanguage()))); sender.sendMessage(i.t("about.license.title")); sender.sendMessage(i.t("about.license.license")); }
From source file:org.codehaus.mojo.cassandra.AbstractCassandraMojo.java
/** * Create a jar with just a manifest containing a Main-Class entry for SurefireBooter and a Class-Path entry for * all classpath elements. Copied from surefire (ForkConfiguration#createJar()) * * @param jarFile The jar file to create/update * @param mainClass The main class to run. * @throws java.io.IOException if something went wrong. *//*from w w w . j av a 2 s . c om*/ protected void createCassandraJar(File jarFile, String mainClass, File cassandraDir) throws IOException { File conf = new File(cassandraDir, "conf"); FileOutputStream fos = null; JarOutputStream jos = null; try { fos = new FileOutputStream(jarFile); jos = new JarOutputStream(fos); jos.setLevel(JarOutputStream.STORED); jos.putNextEntry(new JarEntry("META-INF/MANIFEST.MF")); Manifest man = new Manifest(); // we can't use StringUtils.join here since we need to add a '/' to // the end of directory entries - otherwise the jvm will ignore them. StringBuilder cp = new StringBuilder(); cp.append(new URL(conf.toURI().toASCIIString()).toExternalForm()); cp.append(' '); getLog().debug("Adding plugin artifact: " + ArtifactUtils.versionlessKey(pluginArtifact) + " to the classpath"); cp.append(new URL(pluginArtifact.getFile().toURI().toASCIIString()).toExternalForm()); cp.append(' '); for (Artifact artifact : this.pluginDependencies) { getLog().debug("Adding plugin dependency artifact: " + ArtifactUtils.versionlessKey(artifact) + " to the classpath"); // NOTE: if File points to a directory, this entry MUST end in '/'. cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm()); cp.append(' '); } if (addMainClasspath || addTestClasspath) { if (addTestClasspath) { getLog().debug("Adding: " + testClassesDirectory + " to the classpath"); cp.append(new URL(testClassesDirectory.toURI().toASCIIString()).toExternalForm()); cp.append(' '); } if (addMainClasspath) { getLog().debug("Adding: " + classesDirectory + " to the classpath"); cp.append(new URL(classesDirectory.toURI().toASCIIString()).toExternalForm()); cp.append(' '); } for (Artifact artifact : (Set<Artifact>) this.project.getArtifacts()) { if ("jar".equals(artifact.getType()) && !Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) && (!Artifact.SCOPE_TEST.equals(artifact.getScope()) || addTestClasspath)) { getLog().debug("Adding dependency: " + ArtifactUtils.versionlessKey(artifact) + " to the classpath"); // NOTE: if File points to a directory, this entry MUST end in '/'. cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm()); cp.append(' '); } } } man.getMainAttributes().putValue("Manifest-Version", "1.0"); man.getMainAttributes().putValue("Class-Path", cp.toString().trim()); man.getMainAttributes().putValue("Main-Class", mainClass); man.write(jos); } finally { IOUtil.close(jos); IOUtil.close(fos); } }
From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.FeatureCatalogue.java
public void xsltWrite(File transformationSource, String xsltfileName, File transformationTarget) { try {//from w w w . j ava2 s . c o m // ============================== // 1. perform additional checks // ============================== URI xsltMainFileUri = null; if (xsltPath.toLowerCase().startsWith("http")) { URL url = new URL(xsltPath + "/" + xsltfileName); xsltMainFileUri = url.toURI(); } else { File xsl = new File(xsltPath + "/" + xsltfileName); if (xsl.exists()) { xsltMainFileUri = xsl.toURI(); } else { result.addError(this, 18, xsl.getAbsolutePath()); return; } } // ============================== // 2. perform the transformation // ============================== // determine if we need to run with a specific JRE if (pathToJavaExe == null) { // continue using current runtime environment XsltWriter writer = new XsltWriter(xslTransformerFactory, hrefMappings, transformationParameters, result); writer.xsltWrite(transformationSource, xsltMainFileUri, transformationTarget); } else { // execute with JRE from configuration List<String> cmds = new ArrayList<String>(); cmds.add(pathToJavaExe); if (javaOptions != null) { cmds.add(javaOptions); } cmds.add("-cp"); List<String> cpEntries = new ArrayList<String>(); // determine if execution from jar or from class file URL writerResource = XsltWriter.class.getResource("XsltWriter.class"); String writerResourceAsString = writerResource.toString(); if (writerResourceAsString.startsWith("jar:")) { // execution from jar // get path to main ShapeChange jar file String jarPath = writerResourceAsString.substring(4, writerResourceAsString.indexOf("!")); URI jarUri = new URI(jarPath); // add path to man jar file to class path entries File jarF = new File(jarUri); cpEntries.add(jarF.getPath()); /* * Get parent directory in which ShapeChange JAR file * exists, because class path entries in manifest are * defined relative to it. */ File jarDir = jarF.getParentFile(); // get manifest and the classpath entries defined by it Manifest mf = new JarFile(jarF).getManifest(); String classPath = mf.getMainAttributes().getValue("Class-Path"); if (classPath != null) { for (String dependency : classPath.split(" ")) { // add path to dependency to class path entries File dependencyF = new File(jarDir, dependency); cpEntries.add(dependencyF.getPath()); } } } else { // execution with class files // get classpath entries from system class loader ClassLoader cl = ClassLoader.getSystemClassLoader(); URL[] urls = ((URLClassLoader) cl).getURLs(); for (URL url : urls) { File dependencyF = new File(url.getPath()); cpEntries.add(dependencyF.getPath()); } } String cpValue = StringUtils.join(cpEntries, System.getProperty("path.separator")); cmds.add("\"" + cpValue + "\""); /* add fully qualified name of XsltWriter class to command */ cmds.add(XsltWriter.class.getName()); // add parameter for hrefMappings (if defined) if (!hrefMappings.isEmpty()) { List<NameValuePair> hrefMappingsList = new ArrayList<NameValuePair>(); for (Entry<String, URI> hrefM : hrefMappings.entrySet()) { hrefMappingsList.add(new BasicNameValuePair(hrefM.getKey(), hrefM.getValue().toString())); } String hrefMappingsString = URLEncodedUtils.format(hrefMappingsList, XsltWriter.ENCODING_CHARSET); /* * NOTE: surrounding href mapping string with double quotes * to avoid issues with using '=' inside the string when * passed as parameter in invocation of java executable. */ cmds.add(XsltWriter.PARAM_hrefMappings); cmds.add("\"" + hrefMappingsString + "\""); } if (!transformationParameters.isEmpty()) { List<NameValuePair> transformationParametersList = new ArrayList<NameValuePair>(); for (Entry<String, String> transParam : transformationParameters.entrySet()) { transformationParametersList .add(new BasicNameValuePair(transParam.getKey(), transParam.getValue())); } String transformationParametersString = URLEncodedUtils.format(transformationParametersList, XsltWriter.ENCODING_CHARSET); /* * NOTE: surrounding transformation parameter string with * double quotes to avoid issues with using '=' inside the * string when passed as parameter in invocation of java * executable. */ cmds.add(XsltWriter.PARAM_transformationParameters); cmds.add("\"" + transformationParametersString + "\""); } if (xslTransformerFactory != null) { cmds.add(XsltWriter.PARAM_xslTransformerFactory); cmds.add(xslTransformerFactory); } String transformationSourcePath = transformationSource.getPath(); String xsltMainFileUriString = xsltMainFileUri.toString(); String transformationTargetPath = transformationTarget.getPath(); cmds.add(XsltWriter.PARAM_transformationSourcePath); cmds.add("\"" + transformationSourcePath + "\""); cmds.add(XsltWriter.PARAM_transformationTargetPath); cmds.add("\"" + transformationTargetPath + "\""); cmds.add(XsltWriter.PARAM_xsltMainFileUri); cmds.add("\"" + xsltMainFileUriString + "\""); result.addInfo(this, 26, StringUtils.join(cmds, " ")); ProcessBuilder pb = new ProcessBuilder(cmds); try { Process proc = pb.start(); StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream()); StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream()); errorGobbler.start(); outputGobbler.start(); errorGobbler.join(); outputGobbler.join(); int exitVal = proc.waitFor(); if (outputGobbler.hasResult()) { result.addInfo(this, 25, outputGobbler.getResult()); } if (exitVal != 0) { // log error if (errorGobbler.hasResult()) { result.addError(this, 23, errorGobbler.getResult(), "" + exitVal); } else { result.addError(this, 24, "" + exitVal); } } } catch (InterruptedException e) { result.addFatalError(this, 22); throw new ShapeChangeAbortException(); } } // ============== // 2. log result // ============== if (OutputFormat.toLowerCase().contains("docx")) { // nothing to do here, the writeDOCX method adds the proper // result } else if (OutputFormat.toLowerCase().contains("framehtml")) { String outputDir = outputDirectory + "/" + outputFilename; result.addResult(getTargetID(), outputDir, "index.html", null); } else { result.addResult(getTargetID(), outputDirectory, transformationTarget.getName(), null); } } catch (Exception e) { String m = e.getMessage(); if (m != null) { result.addError(m); } e.printStackTrace(System.err); } }
From source file:org.netbeans.nbbuild.MakeJnlp2.java
private Map<String, List<File>> verifyExtensions(File f, Manifest mf, String dashcnb, String codebasename, boolean verify, Set<String> indirectFilePaths) throws IOException, BuildException { Map<String, List<File>> localizedFiles = new HashMap<String, List<File>>(); File clusterRoot = f.getParentFile(); String moduleDirPrefix = ""; File updateTracking;//from w w w. j av a 2 s .c om log("Verifying extensions for: " + codebasename + ", cluster root: " + clusterRoot + ", verify: " + verify, Project.MSG_DEBUG); for (;;) { updateTracking = new File(clusterRoot, "update_tracking"); if (updateTracking.isDirectory()) { break; } moduleDirPrefix = clusterRoot.getName() + "/" + moduleDirPrefix; clusterRoot = clusterRoot.getParentFile(); if (clusterRoot == null || !clusterRoot.exists()) { if (!verify) { return localizedFiles; } throw new BuildException("Cannot find update_tracking directory for module " + f); } } File ut = new File(updateTracking, dashcnb + ".xml"); if (!ut.exists()) { throw new BuildException("The file " + ut + " for module " + codebasename + " cannot be found"); } Map<String, String> fileToOwningModule = new HashMap<String, String>(); try { ModuleSelector.readUpdateTracking(getProject(), ut.toString(), fileToOwningModule); } catch (IOException ex) { throw new BuildException(ex); } catch (ParserConfigurationException ex) { throw new BuildException(ex); } catch (SAXException ex) { throw new BuildException(ex); } log("project files: " + fileToOwningModule, Project.MSG_DEBUG); String name = relative(f, clusterRoot); log(" removing: " + name, Project.MSG_DEBUG); removeWithLocales(fileToOwningModule, name, clusterRoot, localizedFiles); name = "config/Modules/" + dashcnb + ".xml"; log(" removing: " + name, Project.MSG_DEBUG); removeWithLocales(fileToOwningModule, name, clusterRoot, localizedFiles); name = "config/ModuleAutoDeps/" + dashcnb + ".xml"; log(" removing: " + name, Project.MSG_DEBUG); removeWithLocales(fileToOwningModule, name, clusterRoot, localizedFiles); name = "update_tracking/" + dashcnb + ".xml"; log(" removing: " + name, Project.MSG_DEBUG); removeWithLocales(fileToOwningModule, name, clusterRoot, localizedFiles); String path = mf.getMainAttributes().getValue("Class-Path"); if (path != null) { StringTokenizer tok = new StringTokenizer(path, ", "); while (tok.hasMoreElements()) { String s = tok.nextToken(); File e = new File(f.getParentFile(), s); String r = relative(e, clusterRoot); removeWithLocales(fileToOwningModule, r, clusterRoot, localizedFiles); } } fileToOwningModule.remove("ant/nblib/" + dashcnb + ".jar"); fileToOwningModule.remove("VERSION.txt"); // cluster release information fileToOwningModule.keySet().removeAll(indirectFilePaths); if (verifyExcludes != null) { StringTokenizer tok = new StringTokenizer(verifyExcludes, ", "); while (tok.hasMoreElements()) { removeWithLocales(fileToOwningModule, tok.nextToken(), clusterRoot, localizedFiles); } } if (verify) { if (!fileToOwningModule.isEmpty()) { throw new BuildException("Cannot build JNLP for module " + f + " as these files are in " + "module's NBM, but are not referenced from any path (see harness/README for properties you can define to fix):\n" + fileToOwningModule.keySet()); } } return localizedFiles; }
From source file:com.slamd.admin.JobPack.java
/** * Extracts the contents of the job pack and registers the included jobs with * the SLAMD server./*from www . ja v a 2s .c om*/ * * @throws SLAMDServerException If a problem occurs while processing the job * pack JAR file. */ public void processJobPack() throws SLAMDServerException { byte[] fileData = null; File tempFile = null; String fileName = null; String separator = System.getProperty("file.separator"); if (filePath == null) { // First, get the request and ensure it is multipart content. HttpServletRequest request = requestInfo.request; if (!FileUpload.isMultipartContent(request)) { throw new SLAMDServerException("Request does not contain multipart " + "content"); } // Iterate through the request fields to get to the file data. Iterator iterator = fieldList.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); String fieldName = fileItem.getFieldName(); if (fieldName.equals(Constants.SERVLET_PARAM_JOB_PACK_FILE)) { fileData = fileItem.get(); fileName = fileItem.getName(); } } // Make sure that a file was actually uploaded. if (fileData == null) { throw new SLAMDServerException("No file data was found in the " + "request."); } // Write the JAR file data to a temp file, since that's the only way we // can parse it. if (separator == null) { separator = "/"; } tempFile = new File(jobClassDirectory + separator + fileName); try { FileOutputStream outputStream = new FileOutputStream(tempFile); outputStream.write(fileData); outputStream.flush(); outputStream.close(); } catch (IOException ioe) { try { tempFile.delete(); } catch (Exception e) { } ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("I/O error writing temporary JAR " + "file: " + ioe, ioe); } } else { tempFile = new File(filePath); if ((!tempFile.exists()) || (!tempFile.isFile())) { throw new SLAMDServerException("Specified job pack file \"" + filePath + "\" does not exist"); } try { fileName = tempFile.getName(); int fileLength = (int) tempFile.length(); fileData = new byte[fileLength]; FileInputStream inputStream = new FileInputStream(tempFile); int bytesRead = 0; while (bytesRead < fileLength) { bytesRead += inputStream.read(fileData, bytesRead, fileLength - bytesRead); } inputStream.close(); } catch (Exception e) { slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e)); throw new SLAMDServerException("Error reading job pack file \"" + filePath + "\" -- " + e, e); } } StringBuilder htmlBody = requestInfo.htmlBody; // Parse the jar file JarFile jarFile = null; Manifest manifest = null; Enumeration jarEntries = null; try { jarFile = new JarFile(tempFile, true); manifest = jarFile.getManifest(); jarEntries = jarFile.entries(); } catch (IOException ioe) { try { if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("Unable to parse the JAR file: " + ioe, ioe); } ArrayList<String> dirList = new ArrayList<String>(); ArrayList<String> fileNameList = new ArrayList<String>(); ArrayList<byte[]> fileDataList = new ArrayList<byte[]>(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = (JarEntry) jarEntries.nextElement(); String entryName = jarEntry.getName(); if (jarEntry.isDirectory()) { dirList.add(entryName); } else { try { int entrySize = (int) jarEntry.getSize(); byte[] entryData = new byte[entrySize]; InputStream inputStream = jarFile.getInputStream(jarEntry); extractFileData(inputStream, entryData); fileNameList.add(entryName); fileDataList.add(entryData); } catch (IOException ioe) { try { jarFile.close(); if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("I/O error parsing JAR entry " + entryName + " -- " + ioe, ioe); } catch (SLAMDServerException sse) { try { jarFile.close(); if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } sse.printStackTrace(); throw sse; } } } // If we have gotten here, then we have read all the data from the JAR file. // Delete the temporary file to prevent possible (although unlikely) // conflicts with data contained in the JAR. try { jarFile.close(); if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } // Create the directory structure specified in the JAR file. if (!dirList.isEmpty()) { htmlBody.append("<B>Created the following directories</B>" + Constants.EOL); htmlBody.append("<BR>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < dirList.size(); i++) { File dirFile = new File(jobClassDirectory + separator + dirList.get(i)); try { dirFile.mkdirs(); htmlBody.append(" <LI>" + dirFile.getAbsolutePath() + "</LI>" + Constants.EOL); } catch (Exception e) { htmlBody.append("</UL>" + Constants.EOL); e.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e)); throw new SLAMDServerException( "Unable to create directory \"" + dirFile.getAbsolutePath() + " -- " + e, e); } } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } // Write all the files to disk. If we have gotten this far, then there // should not be any failures, but if there are, then we will have to // leave things in a "dirty" state. if (!fileNameList.isEmpty()) { htmlBody.append("<B>Created the following files</B>" + Constants.EOL); htmlBody.append("<BR>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < fileNameList.size(); i++) { File dataFile = new File(jobClassDirectory + separator + fileNameList.get(i)); try { // Make sure the parent directory exists. dataFile.getParentFile().mkdirs(); } catch (Exception e) { } try { FileOutputStream outputStream = new FileOutputStream(dataFile); outputStream.write(fileDataList.get(i)); outputStream.flush(); outputStream.close(); htmlBody.append(" <LI>" + dataFile.getAbsolutePath() + "</LI>" + Constants.EOL); } catch (IOException ioe) { htmlBody.append("</UL>" + Constants.EOL); ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("Unable to write file " + dataFile.getAbsolutePath() + ioe, ioe); } } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } // Finally, parse the manifest to get the names of the classes that should // be registered with the SLAMD server. Attributes manifestAttributes = manifest.getMainAttributes(); Attributes.Name key = new Attributes.Name(Constants.JOB_PACK_MANIFEST_REGISTER_JOBS_ATTR); String registerClassesStr = (String) manifestAttributes.get(key); if ((registerClassesStr == null) || (registerClassesStr.length() == 0)) { htmlBody.append("<B>No job classes registered</B>" + Constants.EOL); } else { ArrayList<String> successList = new ArrayList<String>(); ArrayList<String> failureList = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(registerClassesStr, ", \t\r\n"); while (tokenizer.hasMoreTokens()) { String className = tokenizer.nextToken(); try { JobClass jobClass = slamdServer.loadJobClass(className); slamdServer.addJobClass(jobClass); successList.add(className); } catch (Exception e) { failureList.add(className + ": " + e); } } if (!successList.isEmpty()) { htmlBody.append("<B>Registered Job Classes</B>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < successList.size(); i++) { htmlBody.append(" <LI>" + successList.get(i) + "</LI>" + Constants.EOL); } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } if (!failureList.isEmpty()) { htmlBody.append("<B>Unable to Register Job Classes</B>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < failureList.size(); i++) { htmlBody.append(" <LI>" + failureList.get(i) + "</LI>" + Constants.EOL); } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } } }
From source file:org.jvnet.hudson.test.JenkinsRule.java
/** * If this test harness is launched for a Jenkins plugin, locate the <tt>target/test-classes/the.jpl</tt> * and add a recipe to install that to the new Jenkins. * * <p>/*from w w w . jav a 2s.c om*/ * This file is created by <tt>maven-hpi-plugin</tt> at the testCompile phase when the current * packaging is <tt>jpi</tt>. */ public void recipeLoadCurrentPlugin() throws Exception { final Enumeration<URL> jpls = getClass().getClassLoader().getResources("the.jpl"); final Enumeration<URL> hpls = getClass().getClassLoader().getResources("the.hpl"); final List<URL> all = Collections.list(jpls); all.addAll(Collections.list(hpls)); if (all.isEmpty()) return; // nope recipes.add(new JenkinsRecipe.Runner() { private File home; private final List<Jpl> jpls = new ArrayList<Jpl>(); @Override public void decorateHome(JenkinsRule testCase, File home) throws Exception { this.home = home; this.jpls.clear(); for (URL hpl : all) { Jpl jpl = new Jpl(hpl); jpl.loadManifest(); jpls.add(jpl); } for (Jpl jpl : jpls) { jpl.resolveDependencies(); } } class Jpl { final URL jpl; Manifest m; private String shortName; Jpl(URL jpl) { this.jpl = jpl; } void loadManifest() throws IOException { m = new Manifest(jpl.openStream()); shortName = m.getMainAttributes().getValue("Short-Name"); if (shortName == null) throw new Error(jpl + " doesn't have the Short-Name attribute"); FileUtils.copyURLToFile(jpl, new File(home, "plugins/" + shortName + ".jpl")); } void resolveDependencies() throws Exception { // make dependency plugins available // TODO: probably better to read POM, but where to read from? // TODO: this doesn't handle transitive dependencies // Tom: plugins are now searched on the classpath first. They should be available on // the compile or test classpath. As a backup, we do a best-effort lookup in the Maven repository // For transitive dependencies, we could evaluate Plugin-Dependencies transitively. String dependencies = m.getMainAttributes().getValue("Plugin-Dependencies"); if (dependencies != null) { DEPENDENCY: for (String dep : dependencies.split(",")) { String suffix = ";resolution:=optional"; boolean optional = dep.endsWith(suffix); if (optional) { dep = dep.substring(0, dep.length() - suffix.length()); } String[] tokens = dep.split(":"); String artifactId = tokens[0]; String version = tokens[1]; for (Jpl other : jpls) { if (other.shortName.equals(artifactId)) continue DEPENDENCY; // resolved from another JPL file } File dependencyJar = resolveDependencyJar(artifactId, version); if (dependencyJar == null) { if (optional) { System.err.println("cannot resolve optional dependency " + dep + " of " + shortName + "; skipping"); continue; } throw new IOException("Could not resolve " + dep + " in " + System.getProperty("java.class.path")); } File dst = new File(home, "plugins/" + artifactId + ".jpi"); if (!dst.exists() || dst.lastModified() != dependencyJar.lastModified()) { try { FileUtils.copyFile(dependencyJar, dst); } catch (ClosedByInterruptException x) { throw new AssumptionViolatedException("copying dependencies was interrupted", x); } } } } } } /** * Lazily created embedder. */ private MavenEmbedder embedder; private MavenEmbedder getMavenEmbedder() throws MavenEmbedderException, IOException { if (embedder == null) embedder = MavenUtil.createEmbedder( new StreamTaskListener(System.out, Charset.defaultCharset()), (File) null, null); return embedder; } private @CheckForNull File resolveDependencyJar(String artifactId, String version) throws Exception { // try to locate it from manifest Enumeration<URL> manifests = getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (manifests.hasMoreElements()) { URL manifest = manifests.nextElement(); InputStream is = manifest.openStream(); Manifest m = new Manifest(is); is.close(); if (artifactId.equals(m.getMainAttributes().getValue("Short-Name"))) return Which.jarFile(manifest); } // For snapshot plugin dependencies, an IDE may have replaced ~/.m2/repository//${artifactId}.hpi with /${artifactId}-plugin/target/classes/ // which unfortunately lacks META-INF/MANIFEST.MF so try to find index.jelly (which every plugin should include) and thus the ${artifactId}.hpi: Enumeration<URL> jellies = getClass().getClassLoader().getResources("index.jelly"); while (jellies.hasMoreElements()) { URL jellyU = jellies.nextElement(); if (jellyU.getProtocol().equals("file")) { File jellyF = new File(jellyU.toURI()); File classes = jellyF.getParentFile(); if (classes.getName().equals("classes")) { File target = classes.getParentFile(); if (target.getName().equals("target")) { File hpi = new File(target, artifactId + ".hpi"); if (hpi.isFile()) { return hpi; } } } } } // need to search multiple group IDs // TODO: extend manifest to include groupID:artifactID:version Exception resolutionError = null; for (String groupId : PLUGIN_GROUPIDS) { // first try to find it on the classpath. // this takes advantage of Maven POM located in POM URL dependencyPomResource = getClass() .getResource("/META-INF/maven/" + groupId + "/" + artifactId + "/pom.xml"); if (dependencyPomResource != null) { // found it return Which.jarFile(dependencyPomResource); } else { try { // currently the most of the plugins are still hpi return resolvePluginFile(artifactId, version, groupId, "hpi"); } catch (AbstractArtifactResolutionException x) { try { // but also try with the new jpi return resolvePluginFile(artifactId, version, groupId, "jpi"); } catch (AbstractArtifactResolutionException x2) { // could be a wrong groupId resolutionError = x; } } } } throw new Exception("Failed to resolve plugin: " + artifactId + " version " + version, resolutionError); } private @CheckForNull File resolvePluginFile(String artifactId, String version, String groupId, String type) throws Exception { final Artifact jpi = getMavenEmbedder().createArtifact(groupId, artifactId, version, "compile"/*doesn't matter*/, type); getMavenEmbedder().resolve(jpi, Arrays.asList(getMavenEmbedder() .createRepository("http://maven.glassfish.org/content/groups/public/", "repo")), embedder.getLocalRepository()); return jpi.getFile(); } }); }