List of usage examples for java.util.jar JarFile getInputStream
public synchronized InputStream getInputStream(ZipEntry ze) throws IOException
From source file:org.tobarsegais.webapp.ContentServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = req.getPathInfo(); if (path == null) { path = req.getServletPath();/* w ww.ja v a 2 s.c om*/ } int index = path.indexOf(PLUGINS_ROOT); if (index != -1) { path = path.substring(index + PLUGINS_ROOT.length() - 1); } Map<String, String> bundles = (Map<String, String>) getServletContext().getAttribute("bundles"); for (index = path.indexOf('/'); index != -1; index = path.indexOf('/', index + 1)) { String key = path.substring(0, index); if (key.startsWith("/")) { key = key.substring(1); } if (bundles.containsKey(key)) { key = bundles.get(key); } URL resource = getServletContext() .getResource(ServletContextListenerImpl.BUNDLE_PATH + "/" + key + ".jar"); if (resource == null) { continue; } URL jarResource = new URL("jar:" + resource + "!/"); URLConnection connection = jarResource.openConnection(); if (!(connection instanceof JarURLConnection)) { continue; } JarURLConnection jarConnection = (JarURLConnection) connection; JarFile jarFile = jarConnection.getJarFile(); try { int endOfFileName = path.indexOf('#', index); endOfFileName = endOfFileName == -1 ? path.length() : endOfFileName; String fileName = path.substring(index + 1, endOfFileName); JarEntry jarEntry = jarFile.getJarEntry(fileName); if (jarEntry == null) { continue; } long size = jarEntry.getSize(); if (size > 0 && size < Integer.MAX_VALUE) { resp.setContentLength((int) size); } resp.setContentType(getServletContext().getMimeType(fileName)); InputStream in = null; OutputStream out = resp.getOutputStream(); try { in = jarFile.getInputStream(jarEntry); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); out.close(); } return; } finally { //jarFile.close(); } } resp.sendError(404); }
From source file:com.tobedevoured.solrsail.SolrConfig.java
/** * Install Solr Config t the local file system by extracting from the * SolrSail jar/*from w w w . j a va 2s.co m*/ * * @param jar File * @throws IOException */ public void installFromJar(File jar) throws IOException { logger.info("Installing config from Jar to {}", this.getSolrHome()); logger.debug("Opening Jar {}", jar.toString()); JarFile jarFile = new JarFile(jar); for (Enumeration<JarEntry> enumeration = jarFile.entries(); enumeration.hasMoreElements();) { JarEntry entry = enumeration.nextElement(); if (!entry.getName().equals("solr/") && entry.getName().startsWith("solr/")) { StringBuilder dest = new StringBuilder(getSolrHome()).append(File.separator) .append(entry.getName().replaceFirst("solr/", "")); File file = new File(dest.toString()); if (entry.isDirectory()) { file.mkdirs(); } else { if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } logger.debug("Copying {} to {}", entry.getName(), dest.toString()); InputStream input = jarFile.getInputStream(entry); Writer writer = new FileWriter(file.getAbsoluteFile()); IOUtils.copy(input, writer); input.close(); writer.close(); } } } }
From source file:org.wso2.carbon.ui.Utils.java
/** * Process one file from the zip, given its name. * Either print the name, or create the file on disk. * * @param e zip entry// w ww .java2s. co m * @param zippy jarfile * @param targetLocation target * @param dirsMade dir * @throws java.io.IOException will be thrown */ private static void getFile(ZipEntry e, JarFile zippy, File targetLocation, SortedSet<String> dirsMade) throws IOException { byte[] b = new byte[1024]; String zipName = e.getName(); if (zipName.startsWith("/")) { zipName = zipName.substring(1); } //Process only fliles that start with "ui" if (!zipName.startsWith("ui")) { return; } // Strip off the ui bit zipName = zipName.substring(2); // if a directory, just return. We mkdir for every file, // since some widely-used Zip creators don't put out // any directory entries, or put them in the wrong place. if (zipName.endsWith("/")) { return; } // Else must be a file; open the file for output // Get the directory part. int ix = zipName.lastIndexOf('/'); if (ix > 0) { String dirName = zipName.substring(0, ix); if (!dirsMade.contains(dirName)) { File d = new File(targetLocation, dirName); // If it already exists as a dir, don't do anything if (!(d.exists() && d.isDirectory())) { // Try to create the directory, warn if it fails if (log.isDebugEnabled()) { log.debug("Deploying Directory: " + dirName); } if (!d.mkdirs()) { log.warn("Warning: unable to mkdir " + dirName); } dirsMade.add(dirName); } } } if (log.isDebugEnabled()) { log.debug("Deploying " + zipName); } File file = new File(targetLocation, zipName); FileOutputStream os = new FileOutputStream(file); InputStream is = zippy.getInputStream(e); int n; while ((n = is.read(b)) > 0) { os.write(b, 0, n); } is.close(); os.close(); }
From source file:com.izforge.izpack.util.SelfModifier.java
/** * @throws IOException if an error occured *//*from w w w. j av a 2s. c o m*/ private void extractJarFile() throws IOException { int extracted = 0; InputStream in = null; String MANIFEST = "META-INF/MANIFEST.MF"; JarFile jar = new JarFile(jarFile, true); try { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) { continue; } String pathname = entry.getName(); if (MANIFEST.equals(pathname.toUpperCase())) { continue; } in = jar.getInputStream(entry); FileUtils.copyToFile(in, new File(sandbox, pathname)); extracted++; } log("Extracted " + extracted + " file" + (extracted > 1 ? "s" : "") + " into " + sandbox.getPath()); } finally { try { jar.close(); } catch (IOException ignore) { } IOUtils.closeQuietly(in); } }
From source file:org.apache.flink.yarn.Client.java
private File generateDefaultConf(Path localJarPath) throws IOException, FileNotFoundException { JarFile jar = null; try {// w w w . j a v a 2 s.c o m jar = new JarFile(localJarPath.toUri().getPath()); } catch (FileNotFoundException fne) { LOG.error("Unable to access jar file. Specify jar file or configuration file.", fne); System.exit(1); } InputStream confStream = jar.getInputStream(jar.getEntry("flink-conf.yaml")); if (confStream == null) { LOG.warn("Given jar file does not contain yaml conf."); confStream = this.getClass().getResourceAsStream("flink-conf.yaml"); if (confStream == null) { throw new RuntimeException("Unable to find flink-conf in jar file"); } } File outFile = new File("flink-conf.yaml"); if (outFile.exists()) { throw new RuntimeException("File unexpectedly exists"); } FileOutputStream outputStream = new FileOutputStream(outFile); int read = 0; byte[] bytes = new byte[1024]; while ((read = confStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } confStream.close(); outputStream.close(); jar.close(); return outFile; }
From source file:org.wso2.carbon.utils.Utils.java
/** * Process one file from the zip, given its name. * Either print the name, or create the file on disk. * * @param zipEntry zip entry * @param zippy jarfile/*from w w w . j a v a2 s .c om*/ * @param targetLocation target * @param dirsMade dir * @throws java.io.IOException will be thrown */ private static void getFile(ZipEntry zipEntry, JarFile zippy, File targetLocation, SortedSet<String> dirsMade) throws IOException { byte[] b = new byte[BYTE_ARRAY_SIZE]; String zipName = zipEntry.getName(); if (zipName.startsWith("/")) { zipName = zipName.substring(1); } //Process only fliles that start with "ui" if (!zipName.startsWith("ui")) { return; } // Strip off the ui bit zipName = zipName.substring(2); // if a directory, just return. We mkdir for every file, // since some widely-used Zip creators don't put out // any directory entries, or put them in the wrong place. if (zipName.endsWith("/")) { return; } // Else must be a file; open the file for output // Get the directory part. int ix = zipName.lastIndexOf('/'); if (ix > 0) { String dirName = zipName.substring(0, ix); if (!dirsMade.contains(dirName)) { File d = new File(targetLocation, dirName); // If it already exists as a dir, don't do anything if (!(d.exists() && d.isDirectory())) { // Try to create the directory, warn if it fails if (log.isDebugEnabled()) { log.debug("Deploying Directory: " + dirName); } if (!d.mkdirs()) { log.warn("Warning: unable to mkdir " + dirName); } dirsMade.add(dirName); } } } if (log.isDebugEnabled()) { log.debug("Deploying " + zipName); } int n; InputStream is = zippy.getInputStream(zipEntry); File file = new File(targetLocation, zipName); FileOutputStream os = null; try { os = new FileOutputStream(file); while ((n = is.read(b)) > 0) { os.write(b, 0, n); } } finally { try { is.close(); } catch (IOException e) { log.warn("Unable to close the InputStream " + e.getMessage(), e); } try { if (os != null) { os.close(); } } catch (IOException e) { log.warn("Unable to close the OutputStream " + e.getMessage(), e); } } }
From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java
@Test public void testUpdateZipfile() throws Exception { // First, set up our zipfile test. // Create a manifest with a random header so that we can ensure it's preserved by the configurator. Manifest mf = new Manifest(); Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR; String mfTestValue = "someCrazyValue"; mf.getMainAttributes().put(mfTestHeader, mfTestValue); // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you // don't add it, your manifest will be blank. mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader)); File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {/*from w w w . j a v a2 s . c om*/ JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf); 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 expectedHomeDir = "/some/silly/random/homeDir"; String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; File webappsTargetDir = new File(webappsTarget); if (webappsTargetDir.exists()) { FileUtils.deleteDirectory(webappsTargetDir); } String expectedDestFile = webappsTarget + "s#test#jenkins.war"; configurator.setTargetJenkinsHomeBaseDir(expectedHomeDir); configurator.setTargetWebappsDir(webappsTarget); configurator.setJenkinsPath("/s/"); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); config.setProjectIdentifier("test"); // 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 { JarFile configuredWarJar = new JarFile(configuredWar); Manifest extractedMF = configuredWarJar.getManifest(); assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader)); // Make sure all of our entries are present, and contain the data we expected. JarEntry curEntry = null; Enumeration<JarEntry> entries = configuredWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry)); if (curEntry.getName().equals(specialFileName)) { assertFalse(fileContents.equals(entryContents)); assertTrue(entryContents.contains(expectedHomeDir)); } else { // Make sure our content was unchanged. assertEquals(fileContents, entryContents); assertFalse(entryContents.contains(expectedHomeDir)); } } } 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() throws Exception { // First, set up our zipfile test. // Create a manifest with a random header so that we can ensure it's preserved by the configurator. Manifest mf = new Manifest(); Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR; String mfTestValue = "someCrazyValue"; mf.getMainAttributes().put(mfTestHeader, mfTestValue); // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you // don't add it, your manifest will be blank. mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader)); File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {/*from w w w . ja va 2 s .c o m*/ JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf); 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 expectedHomeDir = "/some/silly/random/homeDir"; String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; File webappsTargetDir = new File(webappsTarget); if (webappsTargetDir.exists()) { FileUtils.deleteDirectory(webappsTargetDir); } String expectedDestFile = webappsTarget + "s#test#hudson.war"; HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy(); warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war"); configurator.setHudsonWarNamingStrategy(warNamingStrategy); configurator.setTargetHudsonHomeBaseDir(expectedHomeDir); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); config.setProjectIdentifier("test"); // 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 { JarFile configuredWarJar = new JarFile(configuredWar); Manifest extractedMF = configuredWarJar.getManifest(); assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader)); // Make sure all of our entries are present, and contain the data we expected. JarEntry curEntry = null; Enumeration<JarEntry> entries = configuredWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry)); if (curEntry.getName().equals(specialFileName)) { assertFalse(fileContents.equals(entryContents)); assertTrue(entryContents.contains(expectedHomeDir)); } else { // Make sure our content was unchanged. assertEquals(fileContents, entryContents); assertFalse(entryContents.contains(expectedHomeDir)); } } } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:org.jahia.data.templates.ModulesPackage.java
private ModulesPackage(JarFile jarFile) throws IOException { modules = new LinkedHashMap<String, PackagedModule>(); Attributes manifestAttributes = jarFile.getManifest().getMainAttributes(); version = new Version(manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_VERSION)); name = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_NAME); description = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_DESCRIPTION); // read jars//w w w. j a va2 s. co m Enumeration<JarEntry> jars = jarFile.entries(); while (jars.hasMoreElements()) { JarEntry jar = jars.nextElement(); JarFile moduleJarFile = null; OutputStream output = null; if (StringUtils.endsWith(jar.getName(), ".jar")) { try { InputStream input = jarFile.getInputStream(jar); File moduleFile = File.createTempFile(jar.getName(), ""); output = new FileOutputStream(moduleFile); int read = 0; byte[] bytes = new byte[1024]; while ((read = input.read(bytes)) != -1) { output.write(bytes, 0, read); } moduleJarFile = new JarFile(moduleFile); Attributes moduleManifestAttributes = moduleJarFile.getManifest().getMainAttributes(); String bundleName = moduleManifestAttributes.getValue(Constants.ATTR_NAME_BUNDLE_SYMBOLIC_NAME); String jahiaGroupId = moduleManifestAttributes.getValue(Constants.ATTR_NAME_GROUP_ID); if (bundleName == null || jahiaGroupId == null) { throw new IOException( "Jar file " + jar.getName() + " in package does not seems to be a DX bundle."); } modules.put(bundleName, new PackagedModule(bundleName, moduleManifestAttributes, moduleFile)); } finally { IOUtils.closeQuietly(output); if (moduleJarFile != null) { moduleJarFile.close(); } } } } // we finally sort modules based on dependencies try { sortByDependencies(modules); } catch (CycleDetectedException e) { throw new JahiaRuntimeException("A cyclic dependency detected in the modules of the supplied package", e); } }
From source file:org.xwiki.webjars.internal.FilesystemResourceReferenceCopier.java
void copyResourceFromJAR(String resourcePrefix, String resourceName, String targetPrefix, FilesystemExportContext exportContext) throws IOException { // Note that we cannot use ClassLoader.getResource() to access the resource since the resourcePath may point // to a directory inside the JAR, and in this case we need to copy all resources inside that directory in the // JAR!// w w w . j av a 2 s . com String resourcePath = String.format(CONCAT_PATH_FORMAT, resourcePrefix, resourceName); JarFile jar = new JarFile(getJARFile(resourcePath)); try { for (Enumeration<JarEntry> enumeration = jar.entries(); enumeration.hasMoreElements();) { JarEntry entry = enumeration.nextElement(); if (entry.getName().startsWith(resourcePath) && !entry.isDirectory()) { // Copy the resource! // TODO: Won't this cause collisions if the same resource is available on several subwikis // for example? String targetPath = targetPrefix + entry.getName().substring(resourcePrefix.length()); File targetLocation = new File(exportContext.getExportDir(), targetPath); if (!targetLocation.exists()) { targetLocation.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(targetLocation); InputStream is = jar.getInputStream(entry); IOUtils.copy(is, fos); fos.close(); is.close(); } } } } finally { jar.close(); } }