List of usage examples for java.util.jar JarFile close
public void close() throws IOException
From source file:org.apache.maven.shared.osgi.DefaultMaven2OsgiConverter.java
/** * Get the symbolic name as groupId + "." + artifactId, with the following exceptions * <ul>/*from ww w .ja v a 2s.c o m*/ * <li>if artifact.getFile is not null and the jar contains a OSGi Manifest with * Bundle-SymbolicName property then that value is returned</li> * <li>if groupId has only one section (no dots) and artifact.getFile is not null then the * first package name with classes is returned. eg. commons-logging:commons-logging -> * org.apache.commons.logging</li> * <li>if artifactId is equal to last section of groupId then groupId is returned. eg. * org.apache.maven:maven -> org.apache.maven</li> * <li>if artifactId starts with last section of groupId that portion is removed. eg. * org.apache.maven:maven-core -> org.apache.maven.core</li> * </ul> */ public String getBundleSymbolicName(Artifact artifact) { if ((artifact.getFile() != null) && artifact.getFile().isFile()) { Analyzer analyzer = new Analyzer(); JarFile jar = null; try { jar = new JarFile(artifact.getFile(), false); if (jar.getManifest() != null) { String symbolicNameAttribute = jar.getManifest().getMainAttributes() .getValue(Analyzer.BUNDLE_SYMBOLICNAME); Map bundleSymbolicNameHeader = analyzer.parseHeader(symbolicNameAttribute); Iterator it = bundleSymbolicNameHeader.keySet().iterator(); if (it.hasNext()) { return (String) it.next(); } } } catch (IOException e) { throw new ManifestReadingException( "Error reading manifest in jar " + artifact.getFile().getAbsolutePath(), e); } finally { if (jar != null) { try { jar.close(); } catch (IOException e) { } } } } int i = artifact.getGroupId().lastIndexOf('.'); if ((i < 0) && (artifact.getFile() != null) && artifact.getFile().isFile()) { String groupIdFromPackage = getGroupIdFromPackage(artifact.getFile()); if (groupIdFromPackage != null) { return groupIdFromPackage; } } String lastSection = artifact.getGroupId().substring(++i); if (artifact.getArtifactId().equals(lastSection)) { return artifact.getGroupId(); } if (artifact.getArtifactId().startsWith(lastSection)) { String artifactId = artifact.getArtifactId().substring(lastSection.length()); if (Character.isLetterOrDigit(artifactId.charAt(0))) { return getBundleSymbolicName(artifact.getGroupId(), artifactId); } else { return getBundleSymbolicName(artifact.getGroupId(), artifactId.substring(1)); } } return getBundleSymbolicName(artifact.getGroupId(), artifact.getArtifactId()); }
From source file:org.spoutcraft.launcher.util.Utils.java
public static void extractJar(JarFile jar, File dest, List<String> ignores) throws IOException { if (!dest.exists()) { dest.mkdirs();/*from ww w .j a v a2 s. com*/ } else { if (!dest.isDirectory()) { throw new IllegalArgumentException("The destination was not a directory"); } FileUtils.cleanDirectory(dest); } Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); File file = new File(dest, entry.getName()); if (ignores != null) { boolean skip = false; for (String path : ignores) { if (entry.getName().startsWith(path)) { skip = true; break; } } if (skip) { continue; } } if (entry.getName().endsWith("/")) { if (!file.mkdir()) { if (ignores == null) { ignores = new ArrayList<String>(); } ignores.add(entry.getName()); } continue; } if (file.exists()) { file.delete(); } file.createNewFile(); InputStream in = new BufferedInputStream(jar.getInputStream(entry)); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); byte buffer[] = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); in.close(); } jar.close(); }
From source file:org.xwiki.webjars.internal.FilesystemResourceReferenceSerializer.java
private 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!//from ww w . ja va 2 s .c o m String resourcePath = String.format("%s/%s", resourcePrefix, resourceName); JarFile jar = new JarFile(getJARFile(resourcePath)); 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(); } } } jar.close(); }
From source file:org.apache.maven.plugin.cxx.GenerateMojo.java
protected Map<String, String> listResourceFolderContent(String path, Map valuesMap) { String location = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); final File jarFile = new File(location); HashMap<String, String> resources = new HashMap<String, String>(); StrSubstitutor substitutor = new StrSubstitutor(valuesMap); path = (StringUtils.isEmpty(path)) ? "" : path + "/"; getLog().debug("listResourceFolderContent : " + location + ", sublocation : " + path); if (jarFile.isFile()) { getLog().debug("listResourceFolderContent : jar case"); try {/* w ww. j a v a 2s . c o m*/ final JarFile jar = new JarFile(jarFile); final Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { final String name = entries.nextElement().getName(); if (name.startsWith(path)) { String resourceFile = File.separator + name; if (!(resourceFile.endsWith("/") || resourceFile.endsWith("\\"))) { getLog().debug("resource entry = " + resourceFile); String destFile = substitutor.replace(resourceFile); getLog().debug("become entry = " + destFile); resources.put(resourceFile, destFile); } } } jar.close(); } catch (IOException ex) { getLog().error("unable to list jar content : " + ex); } } else { getLog().debug("listResourceFolderContent : file case"); //final URL url = Launcher.class.getResource("/" + path); final URL url = getClass().getResource("/" + path); if (url != null) { try { final File names = new File(url.toURI()); Collection<File> entries = FileUtils.listFiles(names, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); for (File name : entries) { String resourceFile = name.getPath(); if (!(resourceFile.endsWith("/") || resourceFile.endsWith("\\"))) { getLog().debug("resource entry = " + resourceFile); String destFile = substitutor.replace(resourceFile); destFile = destFile.replaceFirst(Pattern.quote(location), "/"); getLog().debug("become entry = " + destFile); resources.put(resourceFile, destFile); } } } catch (URISyntaxException ex) { // never happens } } } return resources; }
From source file:org.opoo.util.ClassPathUtils.java
/** * //from w ww .j av a 2 s . c o m * @param jarFileURL * @param sourcePath * @param destination * @param overwrite * @throws Exception */ protected static void copyJarPath(URL jarFileURL, String sourcePath, File destination, boolean overwrite) throws Exception { //URL jarFileURL = ResourceUtils.extractJarFileURL(url); if (!sourcePath.endsWith("/")) { sourcePath += "/"; } String root = jarFileURL.toString() + "!/"; if (!root.startsWith("jar:")) { root = "jar:" + root; } JarFile jarFile = new JarFile(new File(jarFileURL.toURI())); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); String name = jarEntry.getName(); //log.debug(name + "." + sourcePath + "." + name.startsWith(sourcePath)); if (name.startsWith(sourcePath)) { String relativePath = name.substring(sourcePath.length()); //log.debug("relativePath: " + relativePath); if (relativePath != null && relativePath.length() > 0) { File tmp = new File(destination, relativePath); //not exists or overwrite permitted if (overwrite || !tmp.exists()) { if (jarEntry.isDirectory()) { tmp.mkdirs(); if (IS_DEBUG_ENABLED) { log.debug("Create directory: " + tmp); } } else { File parent = tmp.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } //1.FileCopyUtils.copy //InputStream is = jarFile.getInputStream(jarEntry); //FileCopyUtils.copy(is, new FileOutputStream(tmp)); //2. url copy URL u = new URL(root + name); //log.debug(u.toString()); FileUtils.copyURLToFile(u, tmp); if (IS_DEBUG_ENABLED) { log.debug("Copyed file '" + u + "' to '" + tmp + "'."); } } } } } } try { jarFile.close(); } catch (Exception ie) { } }
From source file:org.jenkinsci.maven.plugins.hpi.RunMojo.java
private VersionNumber versionOfPlugin(File p) throws IOException { if (!p.isFile()) { return new VersionNumber("0.0"); }/*w ww . j av a2s. com*/ JarFile j = new JarFile(p); try { String v = j.getManifest().getMainAttributes().getValue("Plugin-Version"); if (v == null) { throw new IOException("no Plugin-Version in " + p); } try { return new VersionNumber(v); } catch (IllegalArgumentException x) { throw new IOException("malformed Plugin-Version in " + p + ": " + x, x); } } finally { j.close(); } }
From source file:com.chiorichan.plugin.loader.JavaPluginLoader.java
public PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException { Validate.notNull(file, "File cannot be null"); JarFile jar = null; InputStream stream = null;/* ww w .j a va 2 s . c o m*/ try { jar = new JarFile(file); JarEntry entry = jar.getJarEntry("plugin.yaml"); if (entry == null) entry = jar.getJarEntry("plugin.yml"); if (entry == null) { throw new InvalidDescriptionException( new FileNotFoundException("Jar does not contain plugin.yaml")); } stream = jar.getInputStream(entry); return new PluginDescriptionFile(stream); } catch (IOException ex) { throw new InvalidDescriptionException(ex); } catch (YAMLException ex) { throw new InvalidDescriptionException(ex); } finally { if (jar != null) { try { jar.close(); } catch (IOException e) { } } if (stream != null) { try { stream.close(); } catch (IOException e) { } } } }
From source file:org.mksmart.ecapi.couchdb.CouchDbSanityChecker.java
/** * Utility method, might need to move elsewhere. * //from www .jav a 2 s . c o m * @param path * @return * @throws URISyntaxException * @throws IOException */ protected String[] listSubResources(String path) throws URISyntaxException, IOException { URL dirURL = getClass().getResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) { // A file path: easy enough return new File(dirURL.toURI()).list(); } // In case of a jar file, we can't actually find a directory. // Have to assume the same jar as this class. if (dirURL == null) { String me = getClass().getName().replace(".", "/") + ".class"; dirURL = getClass().getClassLoader().getResource(me); } // a JAR path if (dirURL.getProtocol().equals("jar")) { // strip out only the JAR file String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar Set<String> result = new HashSet<String>(); // avoid duplicates in case it is a subdirectory while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(path)) { // filter according to the path String entry = name.substring(path.length()); if (entry.startsWith("/")) entry = entry.substring(1); int checkSubdir = entry.indexOf("/"); // if it is a subdirectory, we just return the directory name if (checkSubdir >= 0) entry = entry.substring(0, checkSubdir); if (!entry.isEmpty()) result.add(entry); } } jar.close(); return result.toArray(new String[result.size()]); } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); }
From source file:org.jahia.services.templates.ModuleBuildHelper.java
public void deployToMaven(String groupId, String artifactId, ModuleReleaseInfo releaseInfo, File generatedJar) throws IOException { if (!isMavenConfigured()) { throw new JahiaRuntimeException("Cannot deploy module to maven, either current instance is not " + "in development mode or maven configuration is not good"); }//www .j a v a2 s. c o m File settings = null; File pomFile = null; try { if (!StringUtils.isEmpty(releaseInfo.getUsername()) && !StringUtils.isEmpty(releaseInfo.getPassword())) { settings = File.createTempFile("settings", ".xml"); BufferedWriter w = new BufferedWriter(new FileWriter(settings)); w.write("<settings><servers><server><id>" + releaseInfo.getRepositoryId() + "</id><username>"); w.write(releaseInfo.getUsername()); w.write("</username><password>"); w.write(releaseInfo.getPassword()); w.write("</password></server></servers></settings>"); w.close(); } JarFile jar = new JarFile(generatedJar); pomFile = PomUtils.extractPomFromJar(jar, groupId, artifactId); jar.close(); Model pom; try { pom = PomUtils.read(pomFile); } catch (XmlPullParserException e) { throw new IOException(e); } String version = pom.getVersion(); if (version == null) { version = pom.getParent().getVersion(); } if (version == null) { throw new IOException("unable to read project version"); } String[] deployParams = { "deploy:deploy-file", "-Dfile=" + generatedJar, "-DrepositoryId=" + releaseInfo.getRepositoryId(), "-Durl=" + releaseInfo.getRepositoryUrl(), "-DpomFile=" + pomFile.getPath(), "-Dpackaging=" + StringUtils.substringAfterLast(generatedJar.getName(), "."), "-DgroupId=" + PomUtils.getGroupId(pom), "-DartifactId=" + pom.getArtifactId(), "-Dversion=" + version }; if (settings != null) { deployParams = (String[]) ArrayUtils.addAll(deployParams, new String[] { "--settings", settings.getPath() }); } StringBuilder out = new StringBuilder(); int ret = ProcessHelper.execute(mavenExecutable, deployParams, null, generatedJar.getParentFile(), out, out); if (ret > 0) { String s = getMavenError(out.toString()); logger.error("Maven archetype call returned " + ret); logger.error("Maven out : " + out); throw new IOException("Maven invocation failed\n" + s); } } finally { FileUtils.deleteQuietly(settings); FileUtils.deleteQuietly(pomFile); } }
From source file:com.google.gdt.eclipse.designer.util.Utils.java
/** * @return the default version of GWT, configured in preferences. *///from w w w .j a v a 2 s.c o m public static Version getDefaultVersion() { String userLocation = Activator.getGWTLocation() + "/gwt-user.jar"; File userFile = new File(userLocation); if (userFile.exists()) { try { JarFile jarFile = new JarFile(userFile); try { if (hasClassEntry(jarFile, "com.google.gwt.user.cellview.client.RowHoverEvent")) { return GWT_2_5; } if (hasClassEntry(jarFile, "com.google.gwt.user.cellview.client.DataGrid")) { return GWT_2_4; } if (hasClassEntry(jarFile, "com.google.gwt.canvas.client.Canvas")) { return GWT_2_2; } if (hasClassEntry(jarFile, "com.google.gwt.user.client.ui.DirectionalTextHelper")) { return GWT_2_1_1; } if (hasClassEntry(jarFile, "com.google.gwt.cell.client.Cell")) { return GWT_2_1; } if (hasClassEntry(jarFile, "com.google.gwt.user.client.ui.LayoutPanel")) { return GWT_2_0; } } finally { jarFile.close(); } } catch (Throwable e) { } } // default version return GWT_2_4; }