List of usage examples for java.util.jar Manifest Manifest
public Manifest()
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 a v 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:org.apache.sqoop.integration.connectorloading.ClasspathTest.java
private Map<String, String> buildJar(String outputDir, Map<String, JarContents> sourceFileToJarMap) throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); List<File> sourceFiles = new ArrayList<>(); for (JarContents jarContents : sourceFileToJarMap.values()) { sourceFiles.addAll(jarContents.sourceFiles); }/*w ww . j av a2s.c om*/ fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(outputDir.toString()))); Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(sourceFiles); boolean compiled = compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call(); if (!compiled) { throw new RuntimeException("failed to compile"); } for (Map.Entry<String, JarContents> jarNameAndContents : sourceFileToJarMap.entrySet()) { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, "."); JarOutputStream target = new JarOutputStream( new FileOutputStream(outputDir.toString() + File.separator + jarNameAndContents.getKey()), manifest); List<String> classesForJar = new ArrayList<>(); for (File sourceFile : jarNameAndContents.getValue().getSourceFiles()) { //split the file on dot to get the filename from FILENAME.java String fileName = sourceFile.getName().split("\\.")[0]; classesForJar.add(fileName); } File dir = new File(outputDir); File[] directoryListing = dir.listFiles(); for (File compiledClass : directoryListing) { String classFileName = compiledClass.getName().split("\\$")[0].split("\\.")[0]; if (classesForJar.contains(classFileName)) { addFileToJar(compiledClass, target); } } for (File propertiesFile : jarNameAndContents.getValue().getProperitesFiles()) { addFileToJar(propertiesFile, target); } target.close(); } //delete non jar files File dir = new File(outputDir); File[] directoryListing = dir.listFiles(); for (File file : directoryListing) { String extension = file.getName().split("\\.")[1]; if (!extension.equals("jar")) { file.delete(); } } Map<String, String> jarMap = new HashMap<>(); jarMap.put(TEST_CONNECTOR_JAR_NAME, outputDir.toString() + File.separator + TEST_CONNECTOR_JAR_NAME); jarMap.put(TEST_DEPENDENCY_JAR_NAME, outputDir.toString() + File.separator + TEST_DEPENDENCY_JAR_NAME); return jarMap; }
From source file:org.eclipse.gemini.blueprint.test.AbstractOnTheFlyBundleCreatorTests.java
/** * Creates the default manifest in case none if found on the disk. By * default, the imports are synthetised based on the test class bytecode. * // w w w . j a va 2 s .c o m * @return default manifest for the jar created on the fly */ protected Manifest createDefaultManifest() { Manifest manifest = new Manifest(); Attributes attrs = manifest.getMainAttributes(); // manifest versions attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); attrs.putValue(Constants.BUNDLE_MANIFESTVERSION, "2"); String description = getName() + "-" + getClass().getName(); // name/description attrs.putValue(Constants.BUNDLE_NAME, "TestBundle-" + description); attrs.putValue(Constants.BUNDLE_SYMBOLICNAME, "TestBundle-" + description); attrs.putValue(Constants.BUNDLE_DESCRIPTION, "on-the-fly test bundle"); // activator attrs.putValue(Constants.BUNDLE_ACTIVATOR, JUnitTestActivator.class.getName()); // add Import-Package entry addImportPackage(manifest); if (logger.isDebugEnabled()) logger.debug("Created manifest:" + manifest.getMainAttributes().entrySet()); return manifest; }
From source file:org.apache.beam.runners.apex.ApexYarnLauncher.java
/** * Create a jar file from the given directory. * @param dir source directory//from ww w. ja va 2 s . com * @param jarFile jar file name * @throws IOException when file cannot be created */ public static void createJar(File dir, File jarFile) throws IOException { final Map<String, ?> env = Collections.singletonMap("create", "true"); if (jarFile.exists() && !jarFile.delete()) { throw new RuntimeException("Failed to remove " + jarFile); } URI uri = URI.create("jar:" + jarFile.toURI()); try (final FileSystem zipfs = FileSystems.newFileSystem(uri, env)) { File manifestFile = new File(dir, JarFile.MANIFEST_NAME); Files.createDirectory(zipfs.getPath("META-INF")); try (final OutputStream out = Files.newOutputStream(zipfs.getPath(JarFile.MANIFEST_NAME))) { if (!manifestFile.exists()) { new Manifest().write(out); } else { FileUtils.copyFile(manifestFile, out); } } final java.nio.file.Path root = dir.toPath(); Files.walkFileTree(root, new java.nio.file.SimpleFileVisitor<Path>() { String relativePath; @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { relativePath = root.relativize(dir).toString(); if (!relativePath.isEmpty()) { if (!relativePath.endsWith("/")) { relativePath += "/"; } if (!relativePath.equals("META-INF/")) { final Path dstDir = zipfs.getPath(relativePath); Files.createDirectory(dstDir); } } return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String name = relativePath + file.getFileName(); if (!JarFile.MANIFEST_NAME.equals(name)) { try (final OutputStream out = Files.newOutputStream(zipfs.getPath(name))) { FileUtils.copyFile(file.toFile(), out); } } return super.visitFile(file, attrs); } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { relativePath = root.relativize(dir.getParent()).toString(); if (!relativePath.isEmpty() && !relativePath.endsWith("/")) { relativePath += "/"; } return super.postVisitDirectory(dir, exc); } }); } }
From source file:com.android.builder.internal.packaging.sign.SignatureExtension.java
/** * Creates a new signature extension./*from w w w . ja v a2s. com*/ * * @param manifestExtension the extension maintaining the manifest * @param minSdkVersion minSdkVersion of the package * @param certificate sign certificate * @param privateKey the private key to sign the jar * @param apkSignedHeaderValue value of the {@code X-Android-APK-Signed} header to output into * the {@code .SF} file or {@code null} if the header should not be output. * * @throws NoSuchAlgorithmException failed to obtain the digest algorithm. */ public SignatureExtension(@NonNull ManifestGenerationExtension manifestExtension, int minSdkVersion, @NonNull X509Certificate certificate, @NonNull PrivateKey privateKey, @Nullable String apkSignedHeaderValue) throws NoSuchAlgorithmException { mManifestExtension = manifestExtension; mSignatureFile = new Manifest(); mDirty = false; mCertificate = certificate; mPrivateKey = privateKey; mApkSignedHeaderValue = apkSignedHeaderValue; mSignatureAlgorithm = SignatureAlgorithm.fromKeyAlgorithm(privateKey.getAlgorithm(), minSdkVersion); mDigestAlgorithm = DigestAlgorithm.findBest(minSdkVersion, mSignatureAlgorithm); mMessageDigest = MessageDigest.getInstance(mDigestAlgorithm.messageDigestName); }
From source file:org.eclipse.equinox.servletbridge.FrameworkLauncher.java
/** * deployExtensionBundle will generate the Servletbridge extensionbundle if it is not already present in the platform's * plugin directory. By default it exports "org.eclipse.equinox.servletbridge" and a versioned export of the Servlet API. * Additional exports can be added by using the "extendedFrameworkExports" initial-param in the ServletConfig *//*from w ww. ja va2 s . c o m*/ private void deployExtensionBundle(File plugins) { File extensionBundle = new File(plugins, "org.eclipse.equinox.servletbridge.extensionbundle_1.0.0.jar"); //$NON-NLS-1$ File extensionBundleDir = new File(plugins, "org.eclipse.equinox.servletbridge.extensionbundle_1.0.0"); //$NON-NLS-1$ if (Boolean.valueOf(config.getInitParameter(CONFIG_OVERRIDE_AND_REPLACE_EXTENSION_BUNDLE)).booleanValue()) { extensionBundle.delete(); deleteDirectory(extensionBundleDir); } else if (extensionBundle.exists() || extensionBundleDir.isDirectory()) return; Manifest mf = new Manifest(); Attributes attribs = mf.getMainAttributes(); attribs.putValue(MANIFEST_VERSION, "1.0"); //$NON-NLS-1$ attribs.putValue(BUNDLE_MANIFEST_VERSION, "2"); //$NON-NLS-1$ attribs.putValue(BUNDLE_NAME, "Servletbridge Extension Bundle"); //$NON-NLS-1$ attribs.putValue(BUNDLE_SYMBOLIC_NAME, "org.eclipse.equinox.servletbridge.extensionbundle"); //$NON-NLS-1$ attribs.putValue(BUNDLE_VERSION, "1.0.0"); //$NON-NLS-1$ attribs.putValue(FRAGMENT_HOST, "system.bundle; extension:=framework"); //$NON-NLS-1$ String servletVersion = context.getMajorVersion() + "." + context.getMinorVersion(); //$NON-NLS-1$ String packageExports = "org.eclipse.equinox.servletbridge; version=1.0" + //$NON-NLS-1$ ", javax.servlet; version=" + servletVersion + //$NON-NLS-1$ ", javax.servlet.http; version=" + servletVersion + //$NON-NLS-1$ ", javax.servlet.resources; version=" + servletVersion; //$NON-NLS-1$ String extendedExports = config.getInitParameter(CONFIG_EXTENDED_FRAMEWORK_EXPORTS); if (extendedExports != null && extendedExports.trim().length() != 0) packageExports += ", " + extendedExports; //$NON-NLS-1$ attribs.putValue(EXPORT_PACKAGE, packageExports); try { JarOutputStream jos = null; try { jos = new JarOutputStream(new FileOutputStream(extensionBundle), mf); jos.finish(); } finally { if (jos != null) jos.close(); } } catch (IOException e) { context.log("Error generating extension bundle", e); //$NON-NLS-1$ } }
From source file:org.springframework.boot.loader.tools.Repackager.java
private Manifest buildManifest(JarFile source) throws IOException { Manifest manifest = source.getManifest(); if (manifest == null) { manifest = new Manifest(); manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); }/*from w w w .ja v a 2s . co m*/ manifest = new Manifest(manifest); String startClass = this.mainClass; if (startClass == null) { startClass = manifest.getMainAttributes().getValue(MAIN_CLASS_ATTRIBUTE); } if (startClass == null) { startClass = findMainMethodWithTimeoutWarning(source); } String launcherClassName = this.layout.getLauncherClassName(); if (launcherClassName != null) { manifest.getMainAttributes().putValue(MAIN_CLASS_ATTRIBUTE, launcherClassName); if (startClass == null) { throw new IllegalStateException("Unable to find main class"); } manifest.getMainAttributes().putValue(START_CLASS_ATTRIBUTE, startClass); } else if (startClass != null) { manifest.getMainAttributes().putValue(MAIN_CLASS_ATTRIBUTE, startClass); } String bootVersion = getClass().getPackage().getImplementationVersion(); manifest.getMainAttributes().putValue(BOOT_VERSION_ATTRIBUTE, bootVersion); manifest.getMainAttributes().putValue(BOOT_CLASSES_ATTRIBUTE, (this.layout instanceof RepackagingLayout) ? ((RepackagingLayout) this.layout).getRepackagedClassesLocation() : this.layout.getClassesLocation()); String lib = this.layout.getLibraryDestination("", LibraryScope.COMPILE); if (StringUtils.hasLength(lib)) { manifest.getMainAttributes().putValue(BOOT_LIB_ATTRIBUTE, lib); } return manifest; }
From source file:org.reficio.p2.FeatureBuilder.java
public void generateSourceFeature(File destinationFolder) { Element featureElement = XmlUtils.fetchOrCreateElement(xmlDoc, xmlDoc, "feature"); featureElement.setAttribute("id", featureElement.getAttribute("id") + ".source"); featureElement.setAttribute("label", featureElement.getAttribute("label") + " Developer Resources"); NodeList nl = featureElement.getElementsByTagName("plugin"); List<Element> elements = new ArrayList<Element>(); //can't remove as we iterate over nl, because its size changes when we remove for (int n = 0; n < nl.getLength(); ++n) { elements.add((Element) nl.item(n)); }//from w w w . j a v a 2 s. com for (Element e : elements) { featureElement.removeChild(e); } for (P2Artifact artifact : this.p2FeatureDefintion.artifacts) { Element pluginElement = XmlUtils.createElement(xmlDoc, featureElement, "plugin"); String id = this.bundlerInstructions.get(artifact).getSourceSymbolicName(); String version = this.bundlerInstructions.get(artifact).getProposedVersion(); pluginElement.setAttribute("id", id); pluginElement.setAttribute("download-size", "0"); //TODO pluginElement.setAttribute("install-size", "0"); //TODO pluginElement.setAttribute("version", version); pluginElement.setAttribute("unpack", "false"); } try { File sourceFeatureContent = new File(destinationFolder, this.getFeatureFullName() + ".source"); sourceFeatureContent.mkdir(); XmlUtils.writeXml(this.xmlDoc, new File(sourceFeatureContent, "feature.xml")); //TODO: add other files that are required by the feature FileOutputStream fos = new FileOutputStream( new File(destinationFolder, this.getFeatureFullName() + ".jar")); Manifest mf = new Manifest(); JarOutputStream jar = new JarOutputStream(fos, mf); addToJar(jar, sourceFeatureContent); } catch (Exception e) { throw new RuntimeException("Cannot generate feature", e); } }
From source file:gov.nih.nci.restgen.util.GeneratorUtil.java
public static void createJarArchive(File jarFile, File[] listFiles) throws IOException { byte b[] = new byte[10240]; FileOutputStream fout = new FileOutputStream(jarFile); JarOutputStream out = new JarOutputStream(fout, new Manifest()); for (int i = 0; i < listFiles.length; i++) { if (listFiles[i] == null || !listFiles[i].exists() || listFiles[i].isDirectory()) { System.out.println(); }/*from w ww . java 2 s .c om*/ JarEntry addFiles = new JarEntry(listFiles[i].getName()); addFiles.setTime(listFiles[i].lastModified()); out.putNextEntry(addFiles); FileInputStream fin = new FileInputStream(listFiles[i]); while (true) { int len = fin.read(b, 0, b.length); if (len <= 0) break; out.write(b, 0, len); } fin.close(); } out.close(); fout.close(); }
From source file:org.apache.hadoop.hive.ql.metadata.JarUtils.java
public static void jarDir(File dir, String relativePath, ZipOutputStream zos) throws IOException { Preconditions.checkNotNull(relativePath, "relativePath"); Preconditions.checkNotNull(zos, "zos"); // by JAR spec, if there is a manifest, it must be the first entry in // the//from w w w .j a v a 2 s.c o m // ZIP. File manifestFile = new File(dir, JarFile.MANIFEST_NAME); ZipEntry manifestEntry = new ZipEntry(JarFile.MANIFEST_NAME); if (!manifestFile.exists()) { zos.putNextEntry(manifestEntry); new Manifest().write(new BufferedOutputStream(zos)); zos.closeEntry(); } else { InputStream is = new FileInputStream(manifestFile); copyToZipStream(is, manifestEntry, zos); } zos.closeEntry(); zipDir(dir, relativePath, zos, true); zos.close(); }