List of usage examples for java.util.jar JarFile close
public void close() throws IOException
From source file:org.kantega.revoc.source.MavenSourceArtifactSourceSource.java
private MavenSourceInfo parseInfo(String filePath, URL resource) { File file = new File(filePath); JarFile jarFile = null; boolean isNewFile = false; try {/* w w w . j av a 2 s. com*/ URLConnection urlConnection = resource.openConnection(); if (urlConnection instanceof JarURLConnection) { jarFile = ((JarURLConnection) urlConnection).getJarFile(); } else { jarFile = new JarFile(file); isNewFile = true; } Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String prefix = "META-INF/maven/"; String propSuffix = "/pom.properties"; if (entry.getName().startsWith(prefix) && entry.getName().endsWith(propSuffix)) { Properties props = new Properties(); InputStream inputStream = jarFile.getInputStream(entry); props.load(inputStream); inputStream.close(); String groupId = props.getProperty("groupId"); String artifactId = props.getProperty("artifactId"); String version = props.getProperty("version"); if (file.getName().startsWith(artifactId + "-" + version)) { return new MavenSourceInfo(groupId, artifactId, version); } } } return null; } catch (IOException e) { throw new RuntimeException(e); } finally { if (isNewFile) { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } }
From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java
@Test public void testMdlModuleDefault() throws IOException { compile("modules/def/CeylonClass.ceylon"); File carFile = getModuleArchive("default", null); assertTrue(carFile.exists());//from w w w . ja v a2 s. c om JarFile car = new JarFile(carFile); ZipEntry moduleClass = car .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/def/CeylonClass.class"); assertNotNull(moduleClass); car.close(); }
From source file:com.rbmhtechnology.apidocserver.controller.ApiDocController.java
private void serveFileFromJarFile(HttpServletResponse response, File jar, String subPath) throws IOException { JarFile jarFile = null; try {/* www. j a v a 2 s . c o m*/ jarFile = new JarFile(jar); JarEntry entry = jarFile.getJarEntry(subPath); if (entry == null) { response.sendError(404); return; } // fallback for requesting a directory without a trailing / // this leads to a jarentry which is not null, and not a directory and of size 0 // this shouldn't be if (!entry.isDirectory() && entry.getSize() == 0) { if (!subPath.endsWith("/")) { JarEntry entryWithSlash = jarFile.getJarEntry(subPath + "/"); if (entryWithSlash != null && entryWithSlash.isDirectory()) { entry = entryWithSlash; } } } if (entry.isDirectory()) { for (String indexFile : DEFAULT_INDEX_FILES) { entry = jarFile.getJarEntry((subPath.endsWith("/") ? subPath : subPath + "/") + indexFile); if (entry != null) { break; } } } if (entry == null) { response.sendError(404); return; } response.setContentLength((int) entry.getSize()); String mimetype = getMimeType(entry.getName()); response.setContentType(mimetype); InputStream input = jarFile.getInputStream(entry); try { ByteStreams.copy(input, response.getOutputStream()); } finally { input.close(); } } finally { if (jarFile != null) { jarFile.close(); } } }
From source file:org.wso2.carbon.mss.examples.petstore.security.ldap.server.ApacheDirectoryServerActivator.java
private void copyResources() throws IOException, EmbeddingLDAPException { final File jarFile = new File( this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath()); final String repositoryDirectory = "repository"; final File destinationRoot = new File(getCarbonHome()); //Check whether ladap configs are already configured File repository = new File(getCarbonHome() + File.separator + repositoryDirectory); if (!repository.exists()) { JarFile jar = null; try {//w ww . j a v a 2s .co m jar = new JarFile(jarFile); final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); // Skip if the entry is not about the 'repository' directory. if (!entry.getName().startsWith(repositoryDirectory)) { continue; } // If the entry is a directory create the relevant directory in the destination. File destination = new File(destinationRoot, entry.getName()); if (entry.isDirectory()) { if (destination.mkdirs()) { continue; } } InputStream in = null; OutputStream out = null; try { // If the entry is a file, copy the file to the destination in = jar.getInputStream(entry); out = new FileOutputStream(destination); IOUtils.copy(in, out); IOUtils.closeQuietly(in); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } } } finally { if (jar != null) { jar.close(); } } } }
From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java
@Ignore("See https://github.com/ceylon/ceylon/issues/6027") @Test//from w ww .ja v a2s . com public void testMdlCarWithInvalidSHA1() throws IOException { compile("modules/single/module.ceylon"); File carFile = getModuleArchive("com.redhat.ceylon.compiler.java.test.cmr.modules.single", "6.6.6"); assertTrue(carFile.exists()); JarFile car = new JarFile(carFile); // just to be sure ZipEntry moduleClass = car .getEntry("com/redhat/ceylon/compiler/java/test/cmr/modules/single/$module_.class"); assertNotNull(moduleClass); car.close(); // now let's break the SHA1 File shaFile = getArchiveName("com.redhat.ceylon.compiler.java.test.cmr.modules.single", "6.6.6", destDir, "car.sha1"); Writer w = new FileWriter(shaFile); w.write("fubar"); w.flush(); w.close(); // now try to compile the subpackage with a broken SHA1 String carName = "/com/redhat/ceylon/compiler/java/test/cmr/modules/single/6.6.6/com.redhat.ceylon.compiler.java.test.cmr.modules.single-6.6.6.car"; carName = carName.replace('/', File.separatorChar); assertErrors("modules/single/subpackage/Subpackage", new CompilerError(-1, "Module car " + carName + " obtained from repository " + (new File(destDir).getAbsolutePath()) + " has an invalid SHA1 signature: you need to remove it and rebuild the archive, since it may be corrupted.")); }
From source file:org.apache.jasper.compiler.TldLocationsCache.java
/** * Scans the given JarURLConnection for TLD files located in META-INF * (or a subdirectory of it), adding an implicit map entry to the taglib * map for any TLD that has a <uri> element. * * @param conn The JarURLConnection to the JAR file to scan * @param ignore true if any exceptions raised when processing the given * JAR should be ignored, false otherwise *//* ww w .j a v a2 s . c om*/ private void scanJar(JarURLConnection conn, boolean ignore) throws JasperException { JarFile jarFile = null; String resourcePath = conn.getJarFileURL().toString(); try { if (redeployMode) { conn.setUseCaches(false); } jarFile = conn.getJarFile(); Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry) entries.nextElement(); String name = entry.getName(); if (!name.startsWith("META-INF/")) continue; if (!name.endsWith(".tld")) continue; InputStream stream = jarFile.getInputStream(entry); try { String uri = getUriFromTld(resourcePath, stream); // Add implicit map entry only if its uri is not already // present in the map if (uri != null && mappings.get(uri) == null) { mappings.put(uri, new String[] { resourcePath, name }); } } finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { // do nothing } } } } } catch (Exception ex) { if (!redeployMode) { // if not in redeploy mode, close the jar in case of an error if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { // ignore } } } if (!ignore) { throw new JasperException(ex); } } finally { if (redeployMode) { // if in redeploy mode, always close the jar if (jarFile != null) { try { jarFile.close(); } catch (Throwable t) { // ignore } } } } }
From source file:org.corpus_tools.salt.util.VisJsVisualizer.java
private File createOutputResources(URI outputFileUri) throws SaltParameterException, SecurityException, FileNotFoundException, IOException { File outputFolder = null;// ww w . j a va 2 s . c o m if (outputFileUri == null) { throw new SaltParameterException("Cannot store salt-vis, because the passed output uri is empty. "); } outputFolder = new File(outputFileUri.path()); if (!outputFolder.exists()) { if (!outputFolder.mkdirs()) { throw new SaltException("Can't create folder " + outputFolder.getAbsolutePath()); } } File cssFolderOut = new File(outputFolder, CSS_FOLDER_OUT); if (!cssFolderOut.exists()) { if (!cssFolderOut.mkdir()) { throw new SaltException("Can't create folder " + cssFolderOut.getAbsolutePath()); } } File jsFolderOut = new File(outputFolder, JS_FOLDER_OUT); if (!jsFolderOut.exists()) { if (!jsFolderOut.mkdir()) { throw new SaltException("Can't create folder " + jsFolderOut.getAbsolutePath()); } } File imgFolderOut = new File(outputFolder, IMG_FOLDER_OUT); if (!imgFolderOut.exists()) { if (!imgFolderOut.mkdirs()) { throw new SaltException("Can't create folder " + imgFolderOut.getAbsolutePath()); } } copyResourceFile( getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + CSS_FILE), outputFolder.getPath(), CSS_FOLDER_OUT, CSS_FILE); copyResourceFile( getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JS_FILE), outputFolder.getPath(), JS_FOLDER_OUT, JS_FILE); copyResourceFile( getClass() .getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JQUERY_FILE), outputFolder.getPath(), JS_FOLDER_OUT, JQUERY_FILE); ClassLoader classLoader = getClass().getClassLoader(); CodeSource srcCode = VisJsVisualizer.class.getProtectionDomain().getCodeSource(); URL codeSourceUrl = srcCode.getLocation(); File codeSourseFile = new File(codeSourceUrl.getPath()); if (codeSourseFile.isDirectory()) { File imgFolder = new File(classLoader.getResource(RESOURCE_FOLDER_IMG_NETWORK).getFile()); File[] imgFiles = imgFolder.listFiles(); if (imgFiles != null) { for (File imgFile : imgFiles) { InputStream inputStream = getClass() .getResourceAsStream(System.getProperty("file.separator") + RESOURCE_FOLDER_IMG_NETWORK + System.getProperty("file.separator") + imgFile.getName()); copyResourceFile(inputStream, outputFolder.getPath(), IMG_FOLDER_OUT, imgFile.getName()); } } } else if (codeSourseFile.getName().endsWith("jar")) { JarFile jarFile = new JarFile(codeSourseFile); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith(RESOURCE_FOLDER_IMG_NETWORK) && !entry.isDirectory()) { copyResourceFile(jarFile.getInputStream(entry), outputFolder.getPath(), IMG_FOLDER_OUT, entry.getName().replaceFirst(RESOURCE_FOLDER_IMG_NETWORK, "")); } } jarFile.close(); } return outputFolder; }
From source file:org.rhq.plugins.jbossas.JBossASServerComponent.java
/** * Check to see if the passed file is actually in jar format and contains a * <ul>/*w ww .j a v a 2 s.c o m*/ * <li>WEB-INF/web.xml for .war </li> * <li>META-INF/application.xml for .ear</li> * <li>META-INF/jboss.service.xml for .sar</li> * </ul> * @param file File to check * @param type Type to match - see RESOURCE_TYPE_SAR, RESOURCE_TYPE_WAR and RESOURCE_TYPE_EAR * @return true is the file is in jar format and matches the type */ private boolean isOfType(File file, String type) { JarFile jfile = null; try { jfile = new JarFile(file); JarEntry entry; if (RESOURCE_TYPE_WAR.equals(type)) entry = jfile.getJarEntry("WEB-INF/web.xml"); else if (RESOURCE_TYPE_EAR.equals(type)) entry = jfile.getJarEntry("META-INF/application.xml"); else if (RESOURCE_TYPE_SAR.equals(type)) // Not yet used entry = jfile.getJarEntry("META-INF/jboss-service.xml"); else { entry = null; // unknown type log.warn("isOfType: " + type + " is unknown - not a valid file"); } if (entry != null) return true; return false; } catch (Exception e) { log.info(e.getMessage()); return false; } finally { if (jfile != null) try { jfile.close(); } catch (IOException e) { log.info("Exception when trying to close the war file: " + e.getMessage()); } } }
From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java
@Test public void testMdlByName() throws IOException { List<String> options = new LinkedList<String>(); options.add("-src"); options.add(getPackagePath() + "/modules/byName"); options.addAll(defaultOptions);/*from www. j a v a 2 s. co m*/ CeyloncTaskImpl task = getCompilerTask(options, null, Arrays.asList("default", "mod")); Boolean ret = task.call(); assertTrue(ret); File carFile = getModuleArchive("default", null); assertTrue(carFile.exists()); JarFile car = new JarFile(carFile); ZipEntry moduleClass = car.getEntry("def/Foo.class"); assertNotNull(moduleClass); ZipEntry moduleClassDir = car.getEntry("def/"); assertNotNull(moduleClassDir); assertTrue(moduleClassDir.isDirectory()); car.close(); carFile = getModuleArchive("mod", "1"); assertTrue(carFile.exists()); car = new JarFile(carFile); moduleClass = car.getEntry("mod/$module_.class"); assertNotNull(moduleClass); moduleClassDir = car.getEntry("mod/"); assertNotNull(moduleClassDir); assertTrue(moduleClassDir.isDirectory()); car.close(); }
From source file:org.openmrs.util.OpenmrsUtil.java
/** * Opens input stream for given resource. This method behaves differently for different URL * types:/*from w w w. jav a 2 s .c o m*/ * <ul> * <li>for <b>local files</b> it returns buffered file input stream;</li> * <li>for <b>local JAR files</b> it reads resource content into memory buffer and returns byte * array input stream that wraps those buffer (this prevents locking JAR file);</li> * <li>for <b>common URL's</b> this method simply opens stream to that URL using standard URL * API.</li> * </ul> * It is not recommended to use this method for big resources within JAR files. * * @param url resource URL * @return input stream for given resource * @throws IOException if any I/O error has occurred */ public static InputStream getResourceInputStream(final URL url) throws IOException { File file = url2file(url); if (file != null) { return new BufferedInputStream(new FileInputStream(file)); } if (!"jar".equalsIgnoreCase(url.getProtocol())) { return url.openStream(); } String urlStr = url.toExternalForm(); if (urlStr.endsWith("!/")) { // JAR URL points to a root entry throw new FileNotFoundException(url.toExternalForm()); } int p = urlStr.indexOf("!/"); if (p == -1) { throw new MalformedURLException(url.toExternalForm()); } String path = urlStr.substring(p + 2); file = url2file(new URL(urlStr.substring(4, p))); if (file == null) {// non-local JAR file URL return url.openStream(); } JarFile jarFile = new JarFile(file); try { ZipEntry entry = jarFile.getEntry(path); if (entry == null) { throw new FileNotFoundException(url.toExternalForm()); } InputStream in = jarFile.getInputStream(entry); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); copyFile(in, out); return new ByteArrayInputStream(out.toByteArray()); } finally { in.close(); } } finally { jarFile.close(); } }