List of usage examples for java.util.jar JarOutputStream JarOutputStream
public JarOutputStream(OutputStream out, Manifest man) throws IOException
JarOutputStream
with the specified Manifest
. From source file:net.cliseau.composer.javacor.MissingToolException.java
/** * Create a JAR file for startup of the unit. * * The created JAR file contains all the specified archive files and contains a * manifest which in particular determines the class path for the JAR file. * All files in startupArchiveFileNames are deleted during the execution of * this method.//w ww . ja v a2s.com * * @param fileName Name of the file to write the result to. * @param startupArchiveFileNames Names of files to include in the JAR file. * @param startupDependencies Names of classpath entries to include in the JAR file classpath. * @exception IOException Thrown if file operations fail, such as creating the JAR file or reading from the input file(s). */ private void createJAR(final String fileName, final Collection<String> startupArchiveFileNames, final Collection<String> startupDependencies) throws IOException, InvalidConfigurationException { // Code inspired by: // http://www.java2s.com/Code/Java/File-Input-Output/CreateJarfile.htm // http://www.massapi.com/class/java/util/jar/Manifest.java.html // construct manifest with appropriate "Class-path" property Manifest starterManifest = new Manifest(); Attributes starterAttributes = starterManifest.getMainAttributes(); // Remark for those who read this code to learn something: // If one forgets to set the MANIFEST_VERSION attribute, then // silently *nothing* (except for a line break) will be written // to the JAR file manifest! starterAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); starterAttributes.put(Attributes.Name.MAIN_CLASS, getStartupName()); starterAttributes.put(Attributes.Name.CLASS_PATH, StringUtils.join(startupDependencies, manifestClassPathSeparator)); // create output JAR file FileOutputStream fos = new FileOutputStream(fileName); JarOutputStream jos = new JarOutputStream(fos, starterManifest); // add the entries for the starter archive's files for (String archFileName : startupArchiveFileNames) { File startupArchiveFile = new File(archFileName); JarEntry startupEntry = new JarEntry(startupArchiveFile.getName()); startupEntry.setTime(startupArchiveFile.lastModified()); jos.putNextEntry(startupEntry); // copy the content of the starter archive's file // TODO: if we used Apache Commons IO 2.1, then the following // code block could be simplified as: // FileUtils.copyFile(startupArchiveFile, jos); FileInputStream fis = new FileInputStream(startupArchiveFile); byte buffer[] = new byte[1024 /*bytes*/]; while (true) { int nRead = fis.read(buffer, 0, buffer.length); if (nRead <= 0) break; jos.write(buffer, 0, nRead); } fis.close(); // end of FileUtils.copyFile() substitution code jos.closeEntry(); startupArchiveFile.delete(); // cleanup the disk a bit } jos.close(); fos.close(); }
From source file:org.talend.utils.io.FilesUtils.java
/** * /*from w w w. j a v a2 s . com*/ * Method "jar". * * @param manifest * @param sourceDir * @param zip * @param fileFilter optional * @throws IOException */ public static void jar(Manifest manifest, File sourceDir, File zip, FileFilter fileFilter) throws IOException { ZipOutputStream out = new JarOutputStream(new FileOutputStream(zip), manifest); try { zips(sourceDir.listFiles(fileFilter), out, fileFilter); } finally { out.close(); } }
From source file:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java
/** * Updates the dependency jar packaged by the {@link ApplicationBundler#createBundle(Location, Iterable, * Iterable)} by moving the things inside classes, lib, resources a level up as expected by spark. * * @param dependencyJar {@link Location} of the job jar to be updated * @param context {@link BasicSparkContext} of this job *//*from ww w. java2 s . com*/ private Location updateDependencyJar(Location dependencyJar, BasicSparkContext context) throws IOException { final String[] prefixToStrip = { ApplicationBundler.SUBDIR_CLASSES, ApplicationBundler.SUBDIR_LIB, ApplicationBundler.SUBDIR_RESOURCES }; Id.Program programId = context.getProgram().getId(); Location updatedJar = locationFactory.create(String.format("%s.%s.%s.%s.%s.jar", ProgramType.SPARK.name().toLowerCase(), programId.getAccountId(), programId.getApplicationId(), programId.getId(), context.getRunId().getId())); // Creates Manifest Manifest manifest = new Manifest(); manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0"); JarOutputStream jarOutput = new JarOutputStream(updatedJar.getOutputStream(), manifest); try { JarInputStream jarInput = new JarInputStream(dependencyJar.getInputStream()); try { JarEntry jarEntry = jarInput.getNextJarEntry(); while (jarEntry != null) { boolean isDir = jarEntry.isDirectory(); String entryName = jarEntry.getName(); String newEntryName = entryName; for (String prefix : prefixToStrip) { if (entryName.startsWith(prefix) && !entryName.equals(prefix)) { newEntryName = entryName.substring(prefix.length()); } } jarEntry = new JarEntry(newEntryName); jarOutput.putNextEntry(jarEntry); if (!isDir) { ByteStreams.copy(jarInput, jarOutput); } jarEntry = jarInput.getNextJarEntry(); } } finally { jarInput.close(); Locations.deleteQuietly(dependencyJar); } } finally { jarOutput.close(); } return updatedJar; }
From source file:com.theoryinpractise.clojure.AbstractClojureCompilerMojo.java
private File createJar(final String cp, final String mainClass) { try {/* ww w . j av a2 s . c o m*/ Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, cp); manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass); File tempFile = File.createTempFile("clojuremavenplugin", "jar"); tempFile.deleteOnExit(); JarOutputStream target = new JarOutputStream(new FileOutputStream(tempFile), manifest); target.close(); return tempFile; } catch (IOException e) { throw new RuntimeException(e); } }
From source file:rita.widget.SourceCode.java
private void createCompileButton() { ImageIcon imgIcon = new ImageIcon(getClass().getResource("/images/sourcecode/bytecode.png")); this.compileButton = new JButton(imgIcon); this.compileButton.setToolTipText(Language.get("compileButton.tooltip")); final File basePathRobots = new File(Settings.getRobotsPath()); compileButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { // guardar el codigo fuente File sourcePath = saveSourceCode(); // COMPILA EN EL DIRECTORIO POR DEFAULT + LA RUTA DEL PACKAGE Collection<File> inFiles = createClassFiles(sourcePath); if (inFiles != null) { /* transformar el codigo fuente, que no tiene errores, para que los println aparezcan en una ventana. * La transformacin no deberia generar errores. *///from ww w . java 2 s. co m writeSourceFile(sourcePath, AgregadorDeConsola.getInstance().transformar(readSourceFile(sourcePath))); // volver a compilar, ahora con el codigo transformado inFiles = createClassFiles(sourcePath); if (inFiles != null) { createJarFile(inFiles); System.out.println("INSTALLPATH=" + Settings.getInstallPath()); System.out.println("SE ENVIA ROBOT:" + HelperEditor.currentRobotPackage + "." + HelperEditor.currentRobotName); // si quiere seleccionar enemigos if (Settings.getProperty("level.default").equals(Language.get("level.four"))) { try { DialogSelectEnemies.getInstance(); } catch (NoEnemiesException e2) { new MessageDialog(Language.get("robot.noEnemies"), MessageType.ERROR); } return; } else { callBatalla(null, null); } } else { System.out.println("Error en codigo transformado por AgregadorDeConsola"); } } } catch (Exception e1) { e1.printStackTrace(); } } /** Recibe un archivo conteniendo codigo fuente java, y crea el .class correspondiente * @param sourcePath El archivo .java * @return Un archivo conteniendo el path al .class generado, o null si no fue posible compilar porque hubo errores en el codigo fuente. */ private Collection<File> createClassFiles(File sourcePath) throws Exception, IOException { Collection<File> f = CompileString.compile(sourcePath, basePathRobots); if (CompileString.hasError()) { int cantErrores = 0; for (Diagnostic<?> diag : CompileString.diagnostics) { if (!diag.getKind().equals(Kind.WARNING)) { int line = (int) diag.getLineNumber(); int col = (int) diag.getColumnNumber(); if (line > 0 && col > 0) { highlightCode(line, col); cantErrores++; } } } if (cantErrores > 0) { new MessageDialog(Language.get("compile.error"), MessageType.ERROR); } return null; } else { return f; } } /* crea un jar con todas las clases del robot. el nombre del jar es el nombre del robot */ private void createJarFile(Collection<File> inFiles) throws FileNotFoundException, IOException { File jarFile = new File(basePathRobots, HelperEditor.currentRobotName + ".jar"); if (jarFile.exists()) { jarFile.delete(); } System.out.println("Path del JAR ==" + jarFile); jarFile.createNewFile(); FileOutputStream fos = new FileOutputStream(jarFile); BufferedOutputStream bo = new BufferedOutputStream(fos); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); JarOutputStream jarOutput = new JarOutputStream(fos, manifest); int basePathLength = basePathRobots.getAbsolutePath().length() + 1; // +1 para incluir al "/" final byte[] buf = new byte[1024]; int anz; try { // para todas las clases... for (File inFile : inFiles) { BufferedInputStream bi = new BufferedInputStream(new FileInputStream(inFile)); try { String relative = inFile.getAbsolutePath().substring(basePathLength); // copia y agrega el archivo .class al jar JarEntry je2 = new JarEntry(relative); jarOutput.putNextEntry(je2); while ((anz = bi.read(buf)) != -1) { jarOutput.write(buf, 0, anz); } jarOutput.closeEntry(); } finally { try { bi.close(); } catch (IOException ignored) { } } } } finally { try { jarOutput.close(); } catch (IOException ignored) { } try { fos.close(); } catch (IOException ignored) { } try { bo.close(); } catch (IOException ignored) { } } } }); compileButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { e.getComponent().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } @Override public void mouseExited(MouseEvent e) { e.getComponent().setCursor(Cursor.getDefaultCursor()); } }); compileButton.setBounds(MIN_WIDTH, 0, MAX_WIDTH - MIN_WIDTH, BUTTON_HEIGHT); compileButton.setFont(smallButtonFont); compileButton.setAlignmentX(LEFT_ALIGNMENT); compileButton.setText(Language.get("compileButton.title")); }
From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java
private Manifest jarDirectoryAndReadManifest(Manifest fromJar, Manifest fromUser, boolean mergeEntries) throws IOException { // Create a jar with a manifest we'd expect to see merged. Path originalJar = folder.newFile("unexpected.jar"); JarOutputStream ignored = new JarOutputStream(Files.newOutputStream(originalJar), fromJar); ignored.close();/*from w ww . ja v a 2 s. c om*/ // Now create the actual manifest Path manifestFile = folder.newFile("actual_manfiest.mf"); try (OutputStream os = Files.newOutputStream(manifestFile)) { fromUser.write(os); } Path tmp = folder.newFolder(); Path output = tmp.resolve("example.jar"); JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output, ImmutableSortedSet.of(originalJar), /* main class */ null, manifestFile, mergeEntries, /* blacklist */ ImmutableSet.of()); ExecutionContext context = TestExecutionContext.newInstance(); step.execute(context); // Now verify that the created manifest matches the expected one. try (JarInputStream jis = new JarInputStream(Files.newInputStream(output))) { return jis.getManifest(); } }
From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java
/** * Creates a Jar archive that includes the given list of files * /*from www . j a v a 2s .c o m*/ * @param archiveFile the name of the jar archive file * @param tobeJared the files to be included in the jar file * * @return if the operation was successful */ public static boolean createJarArchive(File archiveFile, List<File> tobeJared) { try { byte buffer[] = new byte[BUFFER_SIZE]; // Open archive file FileOutputStream stream = new FileOutputStream(archiveFile); JarOutputStream out = new JarOutputStream(stream, new Manifest()); for (int i = 0; i < tobeJared.size(); i++) { if (tobeJared.get(i) == null || !tobeJared.get(i).exists() || tobeJared.get(i).isDirectory()) continue; // Just in case... log.debug("Adding " + tobeJared.get(i).getName()); // Add archive entry JarEntry jarAdd = new JarEntry(tobeJared.get(i).getName()); jarAdd.setTime(tobeJared.get(i).lastModified()); out.putNextEntry(jarAdd); // Write file to archive FileInputStream in = new FileInputStream(tobeJared.get(i)); while (true) { int nRead = in.read(buffer, 0, buffer.length); if (nRead <= 0) break; out.write(buffer, 0, nRead); } in.close(); } out.close(); stream.close(); log.info("Adding completed OK"); return true; } catch (Exception e) { log.error("Creating jar file failed", e); return false; } }
From source file:com.taobao.android.TPatchTool.java
/** * ?so//from w w w . j a v a 2s .c o m * * @param toZipFolder * @param soOutputFile */ private void zipBundle(File toZipFolder, File soOutputFile) throws IOException { FileOutputStream fileOutputStream = null; JarOutputStream jos = null; try { // ?so Manifest manifest = createManifest(); fileOutputStream = new FileOutputStream(soOutputFile); jos = new JarOutputStream(new BufferedOutputStream(fileOutputStream), manifest); jos.setLevel(9); // jos.setComment(baseApkVersion+"@"+newApkVersion); // Add ZIP entry to output stream. File[] files = toZipFolder.listFiles(); for (File file : files) { if (file.isDirectory()) { addDirectory(jos, file, file.getName()); } else { addFile(jos, file); } } } finally { IOUtils.closeQuietly(jos); if (null != fileOutputStream) { IOUtils.closeQuietly(fileOutputStream); } } }
From source file:org.eclipse.birt.build.mavenrepogen.RepoGen.java
private void createJar(final File jarFile, final File[] files) throws IOException { final Manifest manifest = new Manifest(); final Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Manifest-Version", "1.0"); attributes.putValue("Created-By", "RepoGen 1.0.0"); final FileOutputStream fos = new FileOutputStream(jarFile); final JarOutputStream jos = new JarOutputStream(fos, manifest); for (final File file : files) { final ZipEntry entry = new ZipEntry(file.getName()); jos.putNextEntry(entry);/*from w w w. ja va 2s . c om*/ final FileInputStream fis = new FileInputStream(file); pipeStream(fis, jos); fis.close(); } jos.close(); }
From source file:com.buaa.cfs.utils.FileUtil.java
/** * Create a jar file at the given path, containing a manifest with a classpath that references all specified * entries./*w ww . j a v a 2s .com*/ * <p> * Some platforms may have an upper limit on command line length. For example, the maximum command line length on * Windows is 8191 characters, but the length of the classpath may exceed this. To work around this limitation, use * this method to create a small intermediate jar with a manifest that contains the full classpath. It returns the * absolute path to the new jar, which the caller may set as the classpath for a new process. * <p> * Environment variable evaluation is not supported within a jar manifest, so this method expands environment * variables before inserting classpath entries to the manifest. The method parses environment variables according * to platform-specific syntax (%VAR% on Windows, or $VAR otherwise). On Windows, environment variables are * case-insensitive. For example, %VAR% and %var% evaluate to the same value. * <p> * Specifying the classpath in a jar manifest does not support wildcards, so this method expands wildcards * internally. Any classpath entry that ends with * is translated to all files at that path with extension .jar or * .JAR. * * @param inputClassPath String input classpath to bundle into the jar manifest * @param pwd Path to working directory to save jar * @param targetDir path to where the jar execution will have its working dir * @param callerEnv Map<String, String> caller's environment variables to use for expansion * * @return String[] with absolute path to new jar in position 0 and unexpanded wild card entry path in position 1 * * @throws IOException if there is an I/O error while writing the jar file */ public static String[] createJarWithClassPath(String inputClassPath, Path pwd, Path targetDir, Map<String, String> callerEnv) throws IOException { // Replace environment variables, case-insensitive on Windows @SuppressWarnings("unchecked") Map<String, String> env = Shell.WINDOWS ? new CaseInsensitiveMap(callerEnv) : callerEnv; String[] classPathEntries = inputClassPath.split(File.pathSeparator); for (int i = 0; i < classPathEntries.length; ++i) { classPathEntries[i] = StringUtils.replaceTokens(classPathEntries[i], StringUtils.ENV_VAR_PATTERN, env); } File workingDir = new File(pwd.toString()); if (!workingDir.mkdirs()) { // If mkdirs returns false because the working directory already exists, // then this is acceptable. If it returns false due to some other I/O // error, then this method will fail later with an IOException while saving // the jar. LOG.debug("mkdirs false for " + workingDir + ", execution will continue"); } StringBuilder unexpandedWildcardClasspath = new StringBuilder(); // Append all entries List<String> classPathEntryList = new ArrayList<String>(classPathEntries.length); for (String classPathEntry : classPathEntries) { if (classPathEntry.length() == 0) { continue; } if (classPathEntry.endsWith("*")) { boolean foundWildCardJar = false; // Append all jars that match the wildcard Path globPath = new Path(classPathEntry).suffix("{.jar,.JAR}"); FileStatus[] wildcardJars = FileContext.getLocalFSFileContext().util().globStatus(globPath); if (wildcardJars != null) { for (FileStatus wildcardJar : wildcardJars) { foundWildCardJar = true; classPathEntryList.add(wildcardJar.getPath().toUri().toURL().toExternalForm()); } } if (!foundWildCardJar) { unexpandedWildcardClasspath.append(File.pathSeparator); unexpandedWildcardClasspath.append(classPathEntry); } } else { // Append just this entry File fileCpEntry = null; if (!new Path(classPathEntry).isAbsolute()) { fileCpEntry = new File(targetDir.toString(), classPathEntry); } else { fileCpEntry = new File(classPathEntry); } String classPathEntryUrl = fileCpEntry.toURI().toURL().toExternalForm(); // File.toURI only appends trailing '/' if it can determine that it is a // directory that already exists. (See JavaDocs.) If this entry had a // trailing '/' specified by the caller, then guarantee that the // classpath entry in the manifest has a trailing '/', and thus refers to // a directory instead of a file. This can happen if the caller is // creating a classpath jar referencing a directory that hasn't been // created yet, but will definitely be created before running. if (classPathEntry.endsWith(Path.SEPARATOR) && !classPathEntryUrl.endsWith(Path.SEPARATOR)) { classPathEntryUrl = classPathEntryUrl + Path.SEPARATOR; } classPathEntryList.add(classPathEntryUrl); } } String jarClassPath = StringUtils.join(" ", classPathEntryList); // Create the manifest Manifest jarManifest = new Manifest(); jarManifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); jarManifest.getMainAttributes().putValue(Attributes.Name.CLASS_PATH.toString(), jarClassPath); // Write the manifest to output JAR file File classPathJar = File.createTempFile("classpath-", ".jar", workingDir); FileOutputStream fos = null; BufferedOutputStream bos = null; JarOutputStream jos = null; try { fos = new FileOutputStream(classPathJar); bos = new BufferedOutputStream(fos); jos = new JarOutputStream(bos, jarManifest); } finally { IOUtils.cleanup(LOG, jos, bos, fos); } String[] jarCp = { classPathJar.getCanonicalPath(), unexpandedWildcardClasspath.toString() }; return jarCp; }