List of usage examples for java.util.jar JarOutputStream close
public void close() throws IOException
From source file:com.simpligility.maven.plugins.android.phase09package.ApkMojo.java
private void addMetaInf(File outputFile, ArrayList<File> jarFiles) throws IOException { File tmp = File.createTempFile(outputFile.getName(), ".add", outputFile.getParentFile()); FileOutputStream fos = new FileOutputStream(tmp); JarOutputStream zos = new JarOutputStream(fos); Set<String> entries = new HashSet<String>(); updateWithMetaInf(zos, outputFile, entries, false); for (File f : jarFiles) { updateWithMetaInf(zos, f, entries, true); }/*from www. j a v a 2 s .c o m*/ if (transformers != null) { for (ResourceTransformer transformer : transformers) { if (transformer.hasTransformedResource()) { transformer.modifyOutputStream(zos); } } } zos.close(); outputFile.delete(); if (!tmp.renameTo(outputFile)) { throw new IOException(String.format("Cannot rename %s to %s", tmp, outputFile.getName())); } }
From source file:org.apache.oozie.action.hadoop.TestMapReduceActionExecutor.java
private Path makeUberJarWithLib(String testDir) throws Exception { Path jobJarPath = new Path(testDir, "uber.jar"); FileOutputStream fos = new FileOutputStream(new File(jobJarPath.toUri().getPath())); JarOutputStream jos = new JarOutputStream(fos); // Have to put in real jar files or it will complain createAndAddJarToJar(jos, new File(new Path(testDir, "lib1.jar").toUri().getPath())); createAndAddJarToJar(jos, new File(new Path(testDir, "lib2.jar").toUri().getPath())); jos.close(); return jobJarPath; }
From source file:net.hasor.maven.ExecMojo.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 classPath List<String> of all classpath elements. * @return//from www .j a v a 2s.c om * @throws IOException */ private File createJar(List<String> classPath, String mainClass) throws IOException { File file = File.createTempFile("maven-exec", ".jar"); file.deleteOnExit(); FileOutputStream fos = new FileOutputStream(file); JarOutputStream jos = new JarOutputStream(fos); jos.setLevel(JarOutputStream.STORED); JarEntry je = new JarEntry("META-INF/MANIFEST.MF"); jos.putNextEntry(je); 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(); for (String el : classPath) { // NOTE: if File points to a directory, this entry MUST end in '/'. cp.append(new URL(new File(el).toURI().toASCIIString()).toExternalForm() + " "); } man.getMainAttributes().putValue("Manifest-Version", "1.0"); man.getMainAttributes().putValue("Class-Path", cp.toString().trim()); man.getMainAttributes().putValue("Main-Class", mainClass); man.write(jos); jos.close(); return file; }
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.//from ww w . j a v a2 s .co m * * @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.kepler.kar.KARBuilder.java
/** * *///w ww . ja v a 2s. c o m private void writeKARFile() throws IOException { JarOutputStream jos = new JarOutputStream(new FileOutputStream(_karFile), _manifest); Iterator<KAREntry> li = _karItems.keySet().iterator(); while (li.hasNext()) { KAREntry entry = (KAREntry) li.next(); if (isDebugging) log.debug("Writing " + entry.getName()); try { jos.putNextEntry(entry); if (_karItems.get(entry) instanceof InputStream) { // inputstream from a bin file byte[] b = new byte[1024]; InputStream is = (InputStream) _karItems.get(entry); int numread = is.read(b, 0, 1024); while (numread != -1) { jos.write(b, 0, numread); numread = is.read(b, 0, 1024); } is.close(); // jos.flush(); jos.closeEntry(); } } catch (IOException ioe) { log.error(" Tried to write Duplicate Entry to kar " + entry.getName() + " " + entry.getLSID()); ioe.printStackTrace(); } } jos.flush(); jos.close(); log.info("done writing KAR file to " + _karFile.getAbsolutePath()); }
From source file:au.com.addstar.objects.Plugin.java
/** * Adds the Spigot.ver file to the jar//from ww w .j ava 2 s . co m * * @param ver */ public void addSpigotVer(String ver) { if (latestFile == null) return; File newFile = new File(latestFile.getParentFile(), SpigotUpdater.getFormat().format(Calendar.getInstance().getTime()) + "-" + ver + "-s.jar"); File spigotFile = new File(latestFile.getParentFile(), "spigot.ver"); if (spigotFile.exists()) FileUtils.deleteQuietly(spigotFile); try { JarFile oldjar = new JarFile(latestFile); if (oldjar.getEntry("spigot.ver") != null) return; JarOutputStream tempJarOutputStream = new JarOutputStream(new FileOutputStream(newFile)); try (Writer wr = new FileWriter(spigotFile); BufferedWriter writer = new BufferedWriter(wr)) { writer.write(ver); writer.newLine(); } try (FileInputStream stream = new FileInputStream(spigotFile)) { byte[] buffer = new byte[1024]; int bytesRead = 0; JarEntry je = new JarEntry(spigotFile.getName()); tempJarOutputStream.putNextEntry(je); while ((bytesRead = stream.read(buffer)) != -1) { tempJarOutputStream.write(buffer, 0, bytesRead); } stream.close(); } Enumeration jarEntries = oldjar.entries(); while (jarEntries.hasMoreElements()) { JarEntry entry = (JarEntry) jarEntries.nextElement(); InputStream entryInputStream = oldjar.getInputStream(entry); tempJarOutputStream.putNextEntry(entry); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = entryInputStream.read(buffer)) != -1) { tempJarOutputStream.write(buffer, 0, bytesRead); } entryInputStream.close(); } tempJarOutputStream.close(); oldjar.close(); FileUtils.deleteQuietly(latestFile); FileUtils.deleteQuietly(spigotFile); FileUtils.moveFile(newFile, latestFile); latestFile = newFile; } catch (ZipException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.paniclauncher.workers.InstanceInstaller.java
public void deleteMetaInf() { File inputFile = getMinecraftJar(); File outputTmpFile = new File(App.settings.getTempDir(), pack.getSafeName() + "-minecraft.jar"); try {// www .jav a 2s. c om JarInputStream input = new JarInputStream(new FileInputStream(inputFile)); JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile)); JarEntry entry; while ((entry = input.getNextJarEntry()) != null) { if (entry.getName().contains("META-INF")) { continue; } output.putNextEntry(entry); byte buffer[] = new byte[1024]; int amo; while ((amo = input.read(buffer, 0, 1024)) != -1) { output.write(buffer, 0, amo); } output.closeEntry(); } input.close(); output.close(); inputFile.delete(); outputTmpFile.renameTo(inputFile); } catch (IOException e) { App.settings.getConsole().logStackTrace(e); } }
From source file:com.speed.ob.api.ClassStore.java
public void dump(File in, File out, Config config) throws IOException { if (in.isDirectory()) { for (ClassNode node : nodes()) { String[] parts = node.name.split("\\."); String dirName = node.name.substring(0, node.name.lastIndexOf(".")); dirName = dirName.replace(".", "/"); File dir = new File(out, dirName); if (!dir.exists()) { if (!dir.mkdirs()) throw new IOException("Could not make output dir: " + dir.getAbsolutePath()); }/* www.j av a 2s . c om*/ ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(writer); byte[] data = writer.toByteArray(); FileOutputStream fOut = new FileOutputStream( new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1))); fOut.write(data); fOut.flush(); fOut.close(); } } else if (in.getName().endsWith(".jar")) { File output = new File(out, in.getName()); JarFile jf = new JarFile(in); HashMap<JarEntry, Object> existingData = new HashMap<>(); if (output.exists()) { try { JarInputStream jarIn = new JarInputStream(new FileInputStream(output)); JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if (!entry.isDirectory()) { byte[] data = IOUtils.toByteArray(jarIn); existingData.put(entry, data); jarIn.closeEntry(); } } jarIn.close(); } catch (IOException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Could not read existing output file, overwriting", e); } } FileOutputStream fout = new FileOutputStream(output); Manifest manifest = null; if (jf.getManifest() != null) { manifest = jf.getManifest(); if (!config.getBoolean("ClassNameTransform.keep_packages") && config.getBoolean("ClassNameTransform.exclude_mains")) { manifest = new Manifest(manifest); if (manifest.getMainAttributes().getValue("Main-Class") != null) { String manifestName = manifest.getMainAttributes().getValue("Main-Class"); if (manifestName.contains(".")) { manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1); manifest.getMainAttributes().putValue("Main-Class", manifestName); } } } } jf.close(); JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout) : new JarOutputStream(fout, manifest); Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files"); if (!existingData.isEmpty()) { for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) { Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName()); jarOut.putNextEntry(entry.getKey()); jarOut.write((byte[]) entry.getValue()); jarOut.closeEntry(); } } for (ClassNode node : nodes()) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); node.accept(writer); byte[] data = writer.toByteArray(); int index = node.name.lastIndexOf("/"); String fileName; if (index > 0) { fileName = node.name.substring(0, index + 1).replace(".", "/"); fileName += node.name.substring(index + 1).concat(".class"); } else { fileName = node.name.concat(".class"); } JarEntry entry = new JarEntry(fileName); jarOut.putNextEntry(entry); jarOut.write(data); jarOut.closeEntry(); } jarOut.close(); } else { if (nodes().size() == 1) { File outputFile = new File(out, in.getName()); ClassNode node = nodes().iterator().next(); ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS); byte[] data = writer.toByteArray(); FileOutputStream stream = new FileOutputStream(outputFile); stream.write(data); stream.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 *///ww w . j av a2 s . c o m 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:kr.motd.maven.exec.ExecMojo.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 classPath List<String> of all classpath elements. * @return/*from w ww .ja va 2 s. c o m*/ * @throws IOException */ private File createJar(List<String> classPath, String mainClass) throws IOException { File file = File.createTempFile("maven-exec", ".jar"); file.deleteOnExit(); FileOutputStream fos = new FileOutputStream(file); JarOutputStream jos = new JarOutputStream(fos); jos.setLevel(JarOutputStream.STORED); JarEntry je = new JarEntry("META-INF/MANIFEST.MF"); jos.putNextEntry(je); 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(); for (String el : classPath) { // NOTE: if File points to a directory, this entry MUST end in '/'. cp.append(new URL(new File(el).toURI().toASCIIString()).toExternalForm() + " "); } man.getMainAttributes().putValue("Manifest-Version", "1.0"); man.getMainAttributes().putValue("Class-Path", cp.toString().trim()); man.getMainAttributes().putValue("Main-Class", mainClass); man.write(jos); jos.close(); return file; }