List of usage examples for java.util.jar JarEntry JarEntry
public JarEntry(JarEntry je)
JarEntry
with fields taken from the specified JarEntry
object. From source file:averroes.JarFile.java
/** * Add a class file from source to the Jar file. * //from w w w . ja v a 2 s . c o m * @param dir * @param source * @throws IOException */ public void add(File dir, File source) throws IOException { BufferedInputStream in = null; try { if (source.isDirectory()) { String name = relativize(dir, source).replace("\\", "/"); if (!name.isEmpty()) { if (!name.endsWith("/")) name += "/"; JarEntry entry = new JarEntry(name); entry.setTime(source.lastModified()); getJarOutputStream().putNextEntry(entry); getJarOutputStream().closeEntry(); } for (File nestedFile : source.listFiles()) add(dir, nestedFile); return; } JarEntry entry = new JarEntry(relativize(dir, source).replace("\\", "/")); entry.setTime(source.lastModified()); getJarOutputStream().putNextEntry(entry); in = new BufferedInputStream(new FileInputStream(source)); byte[] buffer = new byte[1024]; while (true) { int count = in.read(buffer); if (count == -1) break; getJarOutputStream().write(buffer, 0, count); } getJarOutputStream().closeEntry(); } finally { if (in != null) in.close(); } }
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 w w . 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;//from ww w. j a v 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:JarBuilder.java
/** Add the contents of a directory that match a filter to the archive * @param dir the directory to add/* www . ja v a 2 s. c om*/ * @param parent the directory to add into * @param buffer a buffer that is 2048 bytes * @param filter the FileFilter to filter the files by * @return true on success, false on failure */ private boolean addDirectoryRecursiveHelper(File dir, String parent, byte[] buffer, FileFilter filter) { try { File[] files = dir.listFiles(filter); BufferedInputStream origin = null; if (files == null) // listFiles may return null if there's an IO error return true; for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { origin = new BufferedInputStream(new FileInputStream(files[i]), 2048); JarEntry entry = new JarEntry(makeName(parent, files[i].getName())); _output.putNextEntry(entry); int count; while ((count = origin.read(buffer, 0, 2048)) != -1) { _output.write(buffer, 0, count); } origin.close(); } else if (files[i].isDirectory()) { addDirectoryRecursiveHelper(files[i], makeName(parent, files[i].getName()), buffer, filter); } } } catch (Exception e) { e.printStackTrace(); } return true; }
From source file:au.com.addstar.objects.Plugin.java
/** * Adds the Spigot.ver file to the jar// ww w . ja va2 s . c om * * @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.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java
@Test public void testUpdateZipfile_warAlreadyExists() throws Exception { // First, set up our zipfile test. File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {//ww w. j av a 2s. co m JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), new Manifest()); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; String expectedDestFile = webappsTarget + "s#test123#jenkins.war"; configurator.setTargetWebappsDir(webappsTarget); configurator.setJenkinsPath("/s/"); configurator.setTargetJenkinsHomeBaseDir("/some/silly/random/homeDir"); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test123"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { // Now, try and create it a second time - this should work, even though the war exists. configurator.configure(config); } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java
@Test public void testUpdateZipfile_warAlreadyExists() throws Exception { // First, set up our zipfile test. File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {/*from w ww. j a v a2 s. c om*/ JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), new Manifest()); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; String expectedDestFile = webappsTarget + "s#test123#hudson.war"; HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy(); warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war"); configurator.setHudsonWarNamingStrategy(warNamingStrategy); configurator.setTargetHudsonHomeBaseDir("/some/silly/random/homeDir"); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test123"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { // Now, try and create it a second time - this should work, even though the war exists. configurator.configure(config); } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:com.jhash.oimadmin.Utils.java
public static void createJarFileFromContent(Map<String, byte[]> content, String[] fileSequence, String jarFileName) {//w w w . ja v a 2 s .c o m logger.trace("createJarFileFromContent({},{})", content, jarFileName); logger.trace("Trying to create a new jar file"); try (ZipOutputStream jarFileOutputStream = new ZipOutputStream(new FileOutputStream(jarFileName))) { jarFileOutputStream.setMethod(ZipOutputStream.STORED); for (String jarItem : fileSequence) { logger.trace("Processing item {}", jarItem); byte[] fileContent = content.get(jarItem); if (fileContent == null) throw new NullPointerException("Failed to locate content for file " + jarItem); JarEntry pluginXMLFileEntry = new JarEntry(jarItem); pluginXMLFileEntry.setTime(System.currentTimeMillis()); pluginXMLFileEntry.setSize(fileContent.length); pluginXMLFileEntry.setCompressedSize(fileContent.length); CRC32 crc = new CRC32(); crc.update(fileContent); pluginXMLFileEntry.setCrc(crc.getValue()); jarFileOutputStream.putNextEntry(pluginXMLFileEntry); jarFileOutputStream.write(fileContent); jarFileOutputStream.closeEntry(); } } catch (Exception exception) { throw new OIMAdminException("Failed to create the Jar file " + jarFileName, exception); } }
From source file:be.wimsymons.intellij.polopolyimport.PPImporter.java
private void addToJar(JarOutputStream jarOS, VirtualFile file) throws IOException { JarEntry entry = new JarEntry(file.getCanonicalPath()); entry.setTime(file.getTimeStamp());/*w w w. j av a 2 s . com*/ jarOS.putNextEntry(entry); Reader reader = wrapWithReplacements(file.getInputStream(), file.getCharset()); Writer writer = new OutputStreamWriter(jarOS); try { CharStreams.copy(reader, writer); } finally { Closeables.close(reader, true); Closeables.close(writer, true); } }
From source file:averroes.JarFile.java
/** * Add the given file with the given entry name to this JAR file. * /*from www . ja va2 s. c o m*/ * @param source * @param entryName * @throws IOException */ public void add(File source, String entryName) throws IOException { JarEntry entry = new JarEntry(entryName); entry.setTime(source.lastModified()); getJarOutputStream().putNextEntry(entry); BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) { getJarOutputStream().write(buffer, 0, len); } getJarOutputStream().closeEntry(); in.close(); }