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:rubah.tools.ConversionClassGenerator.java
public void generateConversionClasses(File outJar) throws IOException { FileOutputStream fos = new FileOutputStream(outJar); JarOutputStream jos = new JarOutputStream(fos, new Manifest()); for (Clazz cl : this.namespace.getDefinedClasses()) { this.addConversionClassesToJar(jos, cl); }/*from w w w. j a va 2s . co m*/ jos.close(); fos.close(); }
From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfigurator.java
@Override public void configure(ProjectServiceConfiguration configuration) { // Get a reference to our template WAR, and make sure it exists. File hudsonTemplateWar = new File(warTemplateFile); if (!hudsonTemplateWar.exists() || !hudsonTemplateWar.isFile()) { String message = "The given Hudson template WAR [" + hudsonTemplateWar + "] either did not exist or was not a file!"; LOG.error(message);/*from w w w .j a v a2 s . c o m*/ throw new IllegalStateException(message); } String deployLocation = hudsonWarNamingStrategy.getWarFilePath(configuration); File hudsonDeployFile = new File(deployLocation); if (hudsonDeployFile.exists()) { String message = "When trying to deploy new WARfile [" + hudsonDeployFile.getAbsolutePath() + "] a file or directory with that name already existed! Continuing with provisioning."; LOG.info(message); return; } try { // Get a reference to our template war JarFile hudsonTemplateWarJar = new JarFile(hudsonTemplateWar); // Extract our web.xml from this war JarEntry webXmlEntry = hudsonTemplateWarJar.getJarEntry(webXmlFilename); String webXmlContents = IOUtils.toString(hudsonTemplateWarJar.getInputStream(webXmlEntry)); // Update the web.xml to contain the correct HUDSON_HOME value String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration); File tempDirFile = new File(tempDir); if (!tempDirFile.exists()) { tempDirFile.mkdirs(); } // Put the web.xml back into the war File updatedHudsonWar = File.createTempFile("hudson", ".war", tempDirFile); JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedHudsonWar), hudsonTemplateWarJar.getManifest()); // Loop through our existing zipfile and add in all of the entries to it except for our web.xml JarEntry curEntry = null; Enumeration<JarEntry> entries = hudsonTemplateWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } if (curEntry.getName().equals(webXmlEntry.getName())) { JarEntry newEntry = new JarEntry(curEntry.getName()); jarOutStream.putNextEntry(newEntry); // Substitute our edited entry content. IOUtils.write(updatedXml, jarOutStream); } else { jarOutStream.putNextEntry(curEntry); IOUtils.copy(hudsonTemplateWarJar.getInputStream(curEntry), jarOutStream); } } // Clean up our resources. jarOutStream.close(); // Move the war into it's deployment location so that it can be picked up and deployed by Tomcat. FileUtils.moveFile(updatedHudsonWar, hudsonDeployFile); } catch (IOException ioe) { // Log this exception and rethrow wrapped in a RuntimeException LOG.error(ioe.getMessage()); throw new RuntimeException(ioe); } }
From source file:org.apache.hadoop.yarn.util.TestFSDownload.java
static LocalResource createJar(FileContext files, Path p, LocalResourceVisibility vis) throws IOException { LOG.info("Create jar file " + p); File jarFile = new File((files.makeQualified(p)).toUri()); FileOutputStream stream = new FileOutputStream(jarFile); LOG.info("Create jar out stream "); JarOutputStream out = new JarOutputStream(stream, new Manifest()); LOG.info("Done writing jar stream "); out.close();/* w ww . jav a 2 s.c o m*/ LocalResource ret = recordFactory.newRecordInstance(LocalResource.class); ret.setResource(URL.fromPath(p)); FileStatus status = files.getFileStatus(p); ret.setSize(status.getLen()); ret.setTimestamp(status.getModificationTime()); ret.setType(LocalResourceType.PATTERN); ret.setVisibility(vis); ret.setPattern("classes/.*"); return ret; }
From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.JarUtils.java
/** * Creates a jar based on the given entries and manifest. This method will * always close the given output stream. * // www.j a v a 2 s . c om * @param manifest jar manifest * @param entries map of resources keyed by the jar entry named * @param outputStream output stream for writing the jar * @return number of byte written to the jar */ public static int createJar(Manifest manifest, Map entries, OutputStream outputStream) throws IOException { int writtenBytes = 0; // load manifest // add it to the jar JarOutputStream jarStream = null; try { // add a jar stream on top jarStream = (manifest != null ? new JarOutputStream(outputStream, manifest) : new JarOutputStream(outputStream)); // select fastest level (no compression) jarStream.setLevel(Deflater.NO_COMPRESSION); // add deps for (Iterator iter = entries.entrySet().iterator(); iter.hasNext();) { Map.Entry element = (Map.Entry) iter.next(); String entryName = (String) element.getKey(); // safety check - all entries must start with / if (!entryName.startsWith(SLASH)) entryName = SLASH + entryName; Resource entryValue = (Resource) element.getValue(); // skip special/duplicate entries (like MANIFEST.MF) if (MANIFEST_JAR_LOCATION.equals(entryName)) { iter.remove(); } else { // write jar entry writtenBytes += JarUtils.writeToJar(entryValue, entryName, jarStream); } } } finally { try { jarStream.flush(); } catch (IOException ex) { // ignore } try { jarStream.finish(); } catch (IOException ex) { // ignore } } return writtenBytes; }
From source file:com.ikanow.aleph2.analytics.spark.services.SparkCompilerService.java
/** Compiles a scala class * @param script/*w w w . j av a 2s . c o m*/ * @param clazz_name * @return * @throws IOException * @throws InstantiationException * @throws IllegalAccessException * @throws ClassNotFoundException */ public Tuple2<ClassLoader, Object> buildClass(final String script, final String clazz_name, final Optional<IBucketLogger> logger) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { final String relative_dir = "./script_classpath/"; new File(relative_dir).mkdirs(); final File source_file = new File(relative_dir + clazz_name + ".scala"); FileUtils.writeStringToFile(source_file, script); final String this_path = LiveInjector.findPathJar(this.getClass(), "./dummy.jar"); final File f = new File(this_path); final File fp = new File(f.getParent()); final String classpath = Arrays.stream(fp.listFiles()).map(ff -> ff.toString()) .filter(ff -> ff.endsWith(".jar")).collect(Collectors.joining(":")); // Need this to make the URL classloader be used, not the system classloader (which doesn't know about Aleph2..) final Settings s = new Settings(); s.classpath().value_$eq(System.getProperty("java.class.path") + classpath); s.usejavacp().scala$tools$nsc$settings$AbsSettings$AbsSetting$$internalSetting_$eq(true); final StoreReporter reporter = new StoreReporter(); final Global g = new Global(s, reporter); final Run r = g.new Run(); r.compile(JavaConverters.asScalaBufferConverter(Arrays.<String>asList(source_file.toString())).asScala() .toList()); if (reporter.hasErrors() || reporter.hasWarnings()) { final String errors = "Compiler: Errors/warnings (**to get to user script line substract 22**): " + JavaConverters.asJavaSetConverter(reporter.infos()).asJava().stream() .map(info -> info.toString()).collect(Collectors.joining(" ;; ")); logger.ifPresent(l -> l.log(reporter.hasErrors() ? Level.ERROR : Level.DEBUG, false, () -> errors, () -> "SparkScalaInterpreterTopology", () -> "compile")); //ERROR: if (reporter.hasErrors()) { System.err.println(errors); } } // Move any class files (eg including sub-classes) Arrays.stream(fp.listFiles()).filter(ff -> ff.toString().endsWith(".class")) .forEach(Lambdas.wrap_consumer_u(ff -> { FileUtils.moveFile(ff, new File(relative_dir + ff.getName())); })); // Create a JAR file... Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); final JarOutputStream target = new JarOutputStream(new FileOutputStream("./script_classpath.jar"), manifest); Arrays.stream(new File(relative_dir).listFiles()).forEach(Lambdas.wrap_consumer_i(ff -> { JarEntry entry = new JarEntry(ff.getName()); target.putNextEntry(entry); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(ff))) { byte[] buffer = new byte[1024]; while (true) { int count = in.read(buffer); if (count == -1) break; target.write(buffer, 0, count); } target.closeEntry(); } })); target.close(); final String created = "Created = " + new File("./script_classpath.jar").toURI().toURL() + " ... " + Arrays.stream(new File(relative_dir).listFiles()).map(ff -> ff.toString()) .collect(Collectors.joining(";")); logger.ifPresent(l -> l.log(Level.DEBUG, true, () -> created, () -> "SparkScalaInterpreterTopology", () -> "compile")); final Tuple2<ClassLoader, Object> o = Lambdas.get(Lambdas.wrap_u(() -> { _cl.set(new java.net.URLClassLoader( Arrays.asList(new File("./script_classpath.jar").toURI().toURL()).toArray(new URL[0]), Thread.currentThread().getContextClassLoader())); Object o_ = _cl.get().loadClass("ScriptRunner").newInstance(); return Tuples._2T(_cl.get(), o_); })); return o; }
From source file:net.sourceforge.jweb.maven.mojo.OneExecutablejarMojo.java
public void execute() throws MojoExecutionException { // Show some info about the plugin. displayPluginInfo();/* w w w . j a va2s.c o m*/ JarOutputStream out = null; JarInputStream template = null; File onejarFile; try { // Create the target file onejarFile = new File(outputDirectory, filename); // Open a stream to write to the target file out = new JarOutputStream(new FileOutputStream(onejarFile, false), getManifest()); // Main jar if (getLog().isDebugEnabled()) { getLog().debug("Adding main jar main/[" + mainJarFilename + "]"); } addToZip(new File(outputDirectory, mainJarFilename), "main/", out); // All dependencies, including transient dependencies, but excluding system scope dependencies List<File> dependencyJars = extractDependencyFiles(artifacts); if (getLog().isDebugEnabled()) { getLog().debug("Adding [" + dependencyJars.size() + "] dependency libraries..."); } for (File jar : dependencyJars) { addToZip(jar, "lib/", out); } // System scope dependencies List<File> systemDependencyJars = extractSystemDependencyFiles(dependencies); if (getLog().isDebugEnabled()) { getLog().debug("Adding [" + systemDependencyJars.size() + "] system dependency libraries..."); } for (File jar : systemDependencyJars) { addToZip(jar, "lib/", out); } // Native libraries if (binlibs != null) { for (FileSet eachFileSet : binlibs) { List<File> includedFiles = toFileList(eachFileSet); if (getLog().isDebugEnabled()) { getLog().debug("Adding [" + includedFiles.size() + "] native libraries..."); } for (File eachIncludedFile : includedFiles) { addToZip(eachIncludedFile, "binlib/", out); } } } // One-jar stuff getLog().debug("Adding one-jar components..."); template = openOnejarTemplateArchive(); ZipEntry entry; while ((entry = template.getNextEntry()) != null) { // Skip the manifest file, no need to clutter... if (!"boot-manifest.mf".equals(entry.getName())) { addToZip(out, entry, template); } } } catch (IOException e) { getLog().error(e); throw new MojoExecutionException("One-jar Mojo failed.", e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(template); } // Attach the created one-jar to the build. if (attachToBuild) { projectHelper.attachArtifact(project, "jar", classifier, onejarFile); } }
From source file:org.codehaus.mojo.jspc.CompileMojo.java
protected void createJarArchive(File archiveFile, File tempJarDir) throws IOException { JarOutputStream jos = null;/*from w ww . j a va2 s .c o m*/ try { jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile)), new Manifest()); int pathLength = tempJarDir.getAbsolutePath().length() + 1; Collection<File> files = FileUtils.listFiles(tempJarDir, null, true); for (final File file : files) { if (!file.isFile()) { continue; } if (getLog().isDebugEnabled()) { getLog().debug("file: " + file.getAbsolutePath()); } // Add entry String name = file.getAbsolutePath().substring(pathLength); // normalize path as the JspCompiler expects '/' as separator name = name.replace('\\', '/'); JarEntry jarFile = new JarEntry(name); jos.putNextEntry(jarFile); FileUtils.copyFile(file, jos); } } finally { IOUtils.closeQuietly(jos); } }
From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfigurator.java
@Override public void configure(ProjectServiceConfiguration configuration) { // Get a reference to our template WAR, and make sure it exists. File jenkinsTemplateWar = new File(warTemplateFile); if (!jenkinsTemplateWar.exists() || !jenkinsTemplateWar.isFile()) { String message = "The given Jenkins template WAR [" + jenkinsTemplateWar + "] either did not exist or was not a file!"; LOG.error(message);//from w w w . j a v a2s .c o m throw new IllegalStateException(message); } String pathProperty = perOrg ? configuration.getOrganizationIdentifier() : configuration.getProjectIdentifier(); String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL) + jenkinsPath + pathProperty + "/jenkins/"; deployedUrl.replace("//", "/"); URL deployedJenkinsUrl; try { deployedJenkinsUrl = new URL(deployedUrl); } catch (MalformedURLException e) { throw new RuntimeException(e); } String webappName = deployedJenkinsUrl.getPath(); if (webappName.startsWith("/")) { webappName = webappName.substring(1); } if (webappName.endsWith("/")) { webappName = webappName.substring(0, webappName.length() - 1); } webappName = webappName.replace("/", "#"); webappName = webappName + ".war"; // Calculate our final filename. String deployLocation = targetWebappsDir + webappName; File jenkinsDeployFile = new File(deployLocation); if (jenkinsDeployFile.exists()) { String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.getAbsolutePath() + "] a file or directory with that name already existed! Continuing with provisioning."; LOG.info(message); return; } try { // Get a reference to our template war JarFile jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar); // Extract our web.xml from this war JarEntry webXmlEntry = jenkinsTemplateWarJar.getJarEntry(webXmlFilename); String webXmlContents = IOUtils.toString(jenkinsTemplateWarJar.getInputStream(webXmlEntry)); // Update the web.xml to contain the correct JENKINS_HOME value String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration); File tempDirFile = new File(tempDir); if (!tempDirFile.exists()) { tempDirFile.mkdirs(); } // Put the web.xml back into the war File updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile); JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar), jenkinsTemplateWarJar.getManifest()); // Loop through our existing zipfile and add in all of the entries to it except for our web.xml JarEntry curEntry = null; Enumeration<JarEntry> entries = jenkinsTemplateWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } if (curEntry.getName().equals(webXmlEntry.getName())) { JarEntry newEntry = new JarEntry(curEntry.getName()); jarOutStream.putNextEntry(newEntry); // Substitute our edited entry content. IOUtils.write(updatedXml, jarOutStream); } else { jarOutStream.putNextEntry(curEntry); IOUtils.copy(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream); } } // Clean up our resources. jarOutStream.close(); // Move the war into its deployment location so that it can be picked up and deployed by the app server. FileUtils.moveFile(updatedJenkinsWar, jenkinsDeployFile); } catch (IOException ioe) { // Log this exception and rethrow wrapped in a RuntimeException LOG.error(ioe.getMessage()); throw new RuntimeException(ioe); } }
From source file:ZipImploder.java
/** * Implode target JAR file from a source directory * /*ww w . j a va2 s. c o m*/ * @param jarName - * name of target .jar * @param sourceDir - * source directory * @param comment - * comment for .jar file * @param method * @param level * @throws IOException */ public void processJar(String jarName, String sourceDir, String comment, int method, int level) throws IOException { String dest = setup(jarName, sourceDir); Manifest man = getManifest(); JarOutputStream jos = man != null ? new JarOutputStream(new BufferedOutputStream(new FileOutputStream(dest)), man) : new JarOutputStream(new BufferedOutputStream(new FileOutputStream(dest))); configure(jos, comment, method, level); process(jos, new File(sourceDir)); }
From source file:ai.h2o.servicebuilder.Util.java
/** * Create jar archive out of files list. Names in archive have paths starting from relativeToDir * * @param tobeJared list of files/*from ww w.j a v a2s . c o m*/ * @param relativeToDir starting directory for paths * @return jar as byte array * @throws IOException */ public static byte[] createJarArchiveByteArray(File[] tobeJared, String relativeToDir) throws IOException { int BUFFER_SIZE = 10240; byte buffer[] = new byte[BUFFER_SIZE]; ByteArrayOutputStream stream = new ByteArrayOutputStream(); JarOutputStream out = new JarOutputStream(stream, new Manifest()); for (File t : tobeJared) { if (t == null || !t.exists() || t.isDirectory()) { if (t != null && !t.isDirectory()) logger.error("Can't add to jar {}", t); continue; } // Create jar entry String filename = t.getPath().replace(relativeToDir, "").replace("\\", "/"); // if (filename.endsWith("MANIFEST.MF")) { // skip to avoid duplicates // continue; // } JarEntry jarAdd = new JarEntry(filename); jarAdd.setTime(t.lastModified()); out.putNextEntry(jarAdd); // Write file to archive FileInputStream in = new FileInputStream(t); 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(); return stream.toByteArray(); }