List of usage examples for java.util.jar JarOutputStream JarOutputStream
public JarOutputStream(OutputStream out) throws IOException
JarOutputStream
with no manifest. 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()); }//from w ww . j a v a 2 s .c o m 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:com.netflix.nicobar.core.persistence.JarArchiveRepository.java
@Override public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException { Objects.requireNonNull(jarScriptArchive, "jarScriptArchive"); ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec(); ModuleId moduleId = moduleSpec.getModuleId(); Path moduleJarPath = getModuleJarPath(moduleId); Files.deleteIfExists(moduleJarPath); JarFile sourceJarFile;//ww w.jav a 2 s.c o m try { sourceJarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath()); } catch (URISyntaxException e) { throw new IOException(e); } JarOutputStream destJarFile = new JarOutputStream(new FileOutputStream(moduleJarPath.toFile())); try { String moduleSpecFileName = moduleSpecSerializer.getModuleSpecFileName(); Enumeration<JarEntry> sourceEntries = sourceJarFile.entries(); while (sourceEntries.hasMoreElements()) { JarEntry sourceEntry = sourceEntries.nextElement(); if (sourceEntry.getName().equals(moduleSpecFileName)) { // avoid double entry for module spec continue; } destJarFile.putNextEntry(sourceEntry); if (!sourceEntry.isDirectory()) { InputStream inputStream = sourceJarFile.getInputStream(sourceEntry); IOUtils.copy(inputStream, destJarFile); IOUtils.closeQuietly(inputStream); } destJarFile.closeEntry(); } // write the module spec String serialized = moduleSpecSerializer.serialize(moduleSpec); JarEntry moduleSpecEntry = new JarEntry(moduleSpecSerializer.getModuleSpecFileName()); destJarFile.putNextEntry(moduleSpecEntry); IOUtils.write(serialized, destJarFile); destJarFile.closeEntry(); } finally { IOUtils.closeQuietly(sourceJarFile); IOUtils.closeQuietly(destJarFile); } // update the timestamp on the jar file to indicate that the module has been updated Files.setLastModifiedTime(moduleJarPath, FileTime.fromMillis(jarScriptArchive.getCreateTime())); }
From source file:com.moss.nomad.core.packager.Packager.java
public void write(OutputStream o) throws Exception { JarOutputStream out = new JarOutputStream(o); {/*from ww w .ja v a2s . co m*/ ByteArrayOutputStream bao = new ByteArrayOutputStream(); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.marshal(container, bao); byte[] containerIndex = bao.toByteArray(); JarEntry entry = new JarEntry("META-INF/container.xml"); out.putNextEntry(entry); out.write(containerIndex); } final byte[] buffer = new byte[1024 * 10]; //10k buffer for (String path : dependencies.keySet()) { ResolvedDependencyInfo info = dependencies.get(path); JarEntry entry = new JarEntry(path); out.putNextEntry(entry); InputStream in = new FileInputStream(info.file()); for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) { out.write(buffer, 0, numRead); } in.close(); } out.close(); }
From source file:com.jhash.oimadmin.Utils.java
public static void createJarFileFromDirectory(String directory, String jarFileName) { File jarDirectory = new File(directory); try (JarOutputStream jarFileOutputStream = new JarOutputStream(new FileOutputStream(jarFileName))) { for (Iterator<File> fileIterator = FileUtils.iterateFiles(jarDirectory, null, true); fileIterator .hasNext();) {/*ww w . ja v a 2s. com*/ File inputFile = fileIterator.next(); String inputFileName = inputFile.getAbsolutePath(); String directoryFileName = jarDirectory.getAbsolutePath(); String relativeInputFileName = inputFileName.substring(directoryFileName.length() + 1); JarEntry newFileEntry = new JarEntry(relativeInputFileName); newFileEntry.setTime(System.currentTimeMillis()); jarFileOutputStream.putNextEntry(newFileEntry); jarFileOutputStream.write(FileUtils.readFileToByteArray(inputFile)); } } catch (Exception exception) { throw new OIMAdminException( "Failed to create the jar file " + jarFileName + " from directory " + directory, exception); } }
From source file:org.wso2.carbon.integration.common.utils.FileManager.java
public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory) throws URISyntaxException, IOException { File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI()); File destinationFileDirectory = new File(destinationDirectory); JarOutputStream jarOutputStream = null; InputStream inputStream = null; try {//w w w .j ava 2 s . com JarFile jarFile = new JarFile(sourceFile); String fileName = jarFile.getName(); String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator)); File destinationFile = new File(destinationFileDirectory, fileNameLastPart); jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile)); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { try { JarEntry jarEntry = entries.nextElement(); inputStream = jarFile.getInputStream(jarEntry); //jarOutputStream.putNextEntry(jarEntry); //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName())); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) != -1) { jarOutputStream.write(buffer, 0, bytesRead); } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.warn("Fail to close jarOutStream"); } } if (jarOutputStream != null) { try { jarOutputStream.flush(); jarOutputStream.closeEntry(); } catch (IOException e) { log.warn("Error while closing jar out stream"); } } if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { log.warn("Error while closing jar file"); } } } } } finally { if (jarOutputStream != null) { try { jarOutputStream.close(); } catch (IOException e) { log.warn("Fail to close jarOutStream"); } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { log.warn("Error while closing input stream"); } } } }
From source file:org.wso2.carbon.automation.test.utils.common.FileManager.java
public static void copyJarFile(File sourceFile, String destinationDirectory) throws IOException { File destinationFileDirectory = new File(destinationDirectory); JarFile jarFile = new JarFile(sourceFile); String fileName = jarFile.getName(); String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator)); File destinationFile = new File(destinationFileDirectory, fileNameLastPart); JarOutputStream jarOutputStream = null; try {// w ww . j a v a 2s .com jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile)); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); InputStream inputStream = jarFile.getInputStream(jarEntry); //jarOutputStream.putNextEntry(jarEntry); //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName())); byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) != -1) { jarOutputStream.write(buffer, 0, bytesRead); } inputStream.close(); jarOutputStream.flush(); jarOutputStream.closeEntry(); } } finally { if (jarOutputStream != null) { try { jarOutputStream.close(); } catch (IOException e) { } } } }
From source file:edu.stanford.muse.email.JarDocCache.java
/** returns a jar outputstream for the given filename. * copies over jar entries if the file was already existing. * unfortunately, we can't append to the end of a jar file easily. * see e.g.http://stackoverflow.com/questions/2223434/appending-files-to-a-zip-file-with-java * and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4129445 * may consider using truezip at some point, but the doc is dense. *//*from w w w. j a v a 2 s.co m*/ private static JarOutputStream appendOrCreateJar(String filename) throws IOException { JarOutputStream jos; File f = new File(filename); if (!f.exists()) return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename))); // bak* is going to be all the previous file entries String bakFilename = filename + ".bak"; File bakFile = new File(bakFilename); f.renameTo(new File(bakFilename)); jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename))); JarFile bakJF; try { bakJF = new JarFile(bakFilename); } catch (Exception e) { log.warn("Bad jar file! " + bakFilename + " size " + new File(filename).length() + " bytes"); Util.print_exception(e, log); return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename))); } // copy all entries from bakJF to jos Enumeration<JarEntry> bakEntries = bakJF.entries(); while (bakEntries.hasMoreElements()) { JarEntry je = bakEntries.nextElement(); jos.putNextEntry(je); InputStream is = bakJF.getInputStream(je); // copy over everything from is to jos byte buf[] = new byte[32 * 1024]; // randomly 32K int nBytes; while ((nBytes = is.read(buf)) != -1) jos.write(buf, 0, nBytes); jos.closeEntry(); } bakFile.delete(); return jos; }
From source file:com.goldmansachs.kata2go.tools.utils.TarGz.java
public static void decompressFromStream2(InputStream inputStream) throws IOException { GzipCompressorInputStream gzipStream = new GzipCompressorInputStream(inputStream); TarArchiveInputStream tarInput = new TarArchiveInputStream(gzipStream); TarArchiveEntry entry;//from w w w . j av a 2s .c o m int bufferSize = 1024; while ((entry = (TarArchiveEntry) tarInput.getNextEntry()) != null) { String entryName = entry.getName(); // strip out the leading directory like the --strip tar argument String entryNameWithoutLeadingDir = entryName.substring(entryName.indexOf("/") + 1); if (entryNameWithoutLeadingDir.isEmpty()) { continue; } if (entry.isDirectory()) { System.out.println("found dir " + entry.getName()); } else { int count; byte data[] = new byte[bufferSize]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((count = tarInput.read(data, 0, bufferSize)) != -1) { baos.write(data, 0, count); } JarOutputStream jarOutputStream = new JarOutputStream(baos); System.out.println(new String(baos.toByteArray())); } } tarInput.close(); gzipStream.close(); }
From source file:org.apache.pig.test.TestRegisteredJarVisibility.java
/** * Create a jar file containing the generated classes. * * @param filesToJar map of canonical class name to class file * @throws IOException on error/*ww w. ja v a 2s .c o m*/ */ private static void jar(Map<String, File> filesToJar) throws IOException { LOG.info("Creating jar file containing: " + filesToJar); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile.getAbsolutePath())); try { for (Map.Entry<String, File> entry : filesToJar.entrySet()) { String zipEntryName = entry.getKey().replace(".", "/") + ".class"; LOG.info("Adding " + zipEntryName + " to " + jarFile.getAbsolutePath()); jos.putNextEntry(new ZipEntry(zipEntryName)); InputStream classInputStream = new FileInputStream(entry.getValue().getAbsolutePath()); try { ByteStreams.copy(classInputStream, jos); } finally { classInputStream.close(); } } } finally { jos.close(); } Assert.assertTrue(jarFile.exists()); LOG.info("Created " + jarFile.getAbsolutePath()); }
From source file:ezbake.deployer.publishers.EzAzkabanPublisher.java
/** * This will publish the artifact to Azkaban for scheduled running. The artifact should be of the format * <p/>//from www . j a v a 2 s .c o m * <p/> * The artifact at this point in time will already have included the SSL certs. * <p/> * Its up to the publisher to reorganize the tar file if needed for its PaaS * * @param artifact The artifact to deploy * @param callerToken - The token of the user or application that initiated this call * @throws DeploymentException - On any exceptions */ @Override public void publish(DeploymentArtifact artifact, EzSecurityToken callerToken) throws DeploymentException { File unzippedPack = null; File azkabanZip = null; ZipOutputStream zipOutputStream = null; String flowName; final BatchJobInfo jobInfo = artifact.getMetadata().getManifest().getBatchJobInfo(); // Get the Azkaban authentication token final AuthenticationResult authenticatorResult; try { authenticatorResult = new AuthenticationManager(new URI(azConf.getAzkabanUrl()), azConf.getUsername(), azConf.getPassword()).login(); } catch (URISyntaxException e) { throw new DeploymentException(e.getMessage()); } if (authenticatorResult.hasError()) { log.error("Could not log into Azkaban: " + authenticatorResult.getError()); throw new DeploymentException(authenticatorResult.getError()); } log.info("Successfully logged into Azkaban. Now creating .zip to upload"); try { // Unzip the artifact unzippedPack = UnzipUtil.unzip(new File(unzipDir), ByteBuffer.wrap(artifact.getArtifact())); log.info("Unzipped artifact to: " + unzippedPack.getAbsolutePath()); // Create a .zip file to submit to Azkaban azkabanZip = File.createTempFile("ezbatch_", ".zip"); log.info("Created temporary zip file: " + azkabanZip.getCanonicalPath()); zipOutputStream = new ZipOutputStream(new FileOutputStream(azkabanZip)); // Copy the configs from the artifact to the top level of the zip. This should contain the Azkaban // .jobs and .properties final String configDir = UnzipUtil.getConfDirectory(unzippedPack).get(); final File configDirFile = new File(configDir); for (File f : FileUtils.listFiles(configDirFile, TrueFileFilter.TRUE, TrueFileFilter.TRUE)) { zipOutputStream.putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(configDir, ""))); IOUtils.copy(new FileInputStream(f), zipOutputStream); zipOutputStream.closeEntry(); } log.info("Copied configs to the .zip"); // Copy the jars from bin/ in the artifact to lib/ in the .zip file and other things to the jar as needed final String dirPrefix = unzippedPack.getAbsolutePath() + "/bin/"; for (File f : FileUtils.listFiles(new File(dirPrefix), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) { zipOutputStream .putNextEntry(new ZipArchiveEntry(f.getCanonicalPath().replaceFirst(dirPrefix, "lib/"))); final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(f)); final JarOutputStream jarOutputStream = new JarOutputStream(zipOutputStream); JarEntry je; while ((je = jarInputStream.getNextJarEntry()) != null) { jarOutputStream.putNextEntry(je); IOUtils.copy(jarInputStream, jarOutputStream); jarOutputStream.closeEntry(); } log.info("Created Jar file"); // Add the SSL certs to the jar final String sslPath = UnzipUtil.getSSLPath(configDirFile).get(); for (File sslFile : FileUtils.listFiles(new File(sslPath), TrueFileFilter.TRUE, TrueFileFilter.TRUE)) { if (sslFile.isFile()) { jarOutputStream.putNextEntry(new JarArchiveEntry("ssl/" + sslFile.getName())); IOUtils.copy(new FileInputStream(sslFile), jarOutputStream); jarOutputStream.closeEntry(); } } log.info("Added SSL certs to jar"); // Add the application.properties to the jar file so the jobs can read it final File appProps = new File(configDir, "application.properties"); final Properties adjustedProperties = new Properties(); adjustedProperties.load(new FileInputStream(appProps)); adjustedProperties.setProperty("ezbake.security.ssl.dir", "/ssl/"); jarOutputStream.putNextEntry(new JarArchiveEntry("application.properties")); adjustedProperties.store(jarOutputStream, null); jarOutputStream.closeEntry(); jarOutputStream.finish(); zipOutputStream.closeEntry(); } // Check to see if there are any .job files. If there aren't, this is an external job and we need to create // one for the .zip file final Collection<File> jobFiles = FileUtils.listFiles(configDirFile, new String[] { "job" }, false); if (jobFiles.isEmpty()) { // If there are no job files present then we need to create one for the user final StringBuilder sb = new StringBuilder( "type=hadoopJava\n" + "job.class=ezbatch.amino.api.EzFrameworkDriver\n" + "classpath=./lib/*\n" + "main.args=-d /ezbatch/amino/config"); for (File xmlConfig : FileUtils.listFiles(configDirFile, new String[] { "xml" }, false)) { sb.append(" -c ").append(xmlConfig.getName()); } zipOutputStream.putNextEntry(new ZipEntry("Analytic.job")); IOUtils.copy(new StringReader(sb.toString()), zipOutputStream); zipOutputStream.closeEntry(); log.info("There was no .job file so one was created for the .zip"); flowName = "Analytic"; } else { flowName = jobInfo.getFlowName(); if (flowName == null) { log.warn("Manifest did not contain flow_name. Guessing what it should be"); flowName = FilenameUtils.getBaseName(jobFiles.toArray(new File[jobFiles.size()])[0].getName()); log.info("Guessing the flow name should be:" + flowName); } } zipOutputStream.finish(); log.info("Finished creating .zip"); // Now that we've created the zip to upload, attempt to create a project for it to be uploaded to. Every .zip // file needs to be uploaded to a project, and the project may or may not already exist. final String projectName = ArtifactHelpers.getAppId(artifact) + "_" + ArtifactHelpers.getServiceId(artifact); final ProjectManager projectManager = new ProjectManager(authenticatorResult.getSessionId(), new URI(azConf.getAzkabanUrl())); final ManagerResult managerResult = projectManager.createProject(projectName, "EzBatch Deployed"); // If the project already exists, it will return an error, but really it's not a problem if (managerResult.hasError()) { if (!managerResult.getMessage().contains("already exists")) { log.error("Could not create project: " + managerResult.getMessage()); throw new DeploymentException(managerResult.getMessage()); } else { log.info("Reusing the existing project: " + projectName); } } else { log.info("Created new project: " + projectName); log.info("Path: " + managerResult.getPath()); } // Upload the .zip file to the project final UploadManager uploader = new UploadManager(authenticatorResult.getSessionId(), azConf.getAzkabanUrl(), projectName, azkabanZip); final UploaderResult uploaderResult = uploader.uploadZip(); if (uploaderResult.hasError()) { log.error("Could not upload the zip file: " + uploaderResult.getError()); throw new DeploymentException(uploaderResult.getError()); } log.info("Successfully submitted zip file to Azkaban"); // Schedule the jar to run. If the start times aren't provided, it will run in 2 minutes final ScheduleManager scheduler = new ScheduleManager(authenticatorResult.getSessionId(), new URI(azConf.getAzkabanUrl())); // Add the optional parameters if they are present if (jobInfo.isSetStartDate()) { scheduler.setScheduleDate(jobInfo.getStartDate()); } if (jobInfo.isSetStartTime()) { scheduler.setScheduleTime(jobInfo.getStartTime()); } if (jobInfo.isSetRepeat()) { scheduler.setPeriod(jobInfo.getRepeat()); } final SchedulerResult schedulerResult = scheduler.scheduleFlow(projectName, flowName, uploaderResult.getProjectId()); if (schedulerResult.hasError()) { log.error("Failure to schedule job: " + schedulerResult.getError()); throw new DeploymentException(schedulerResult.getError()); } log.info("Successfully scheduled flow: " + flowName); } catch (Exception ex) { log.error("No Nos!", ex); throw new DeploymentException(ex.getMessage()); } finally { IOUtils.closeQuietly(zipOutputStream); FileUtils.deleteQuietly(azkabanZip); FileUtils.deleteQuietly(unzippedPack); } }