List of usage examples for java.util.jar JarFile entries
public Enumeration<JarEntry> entries()
From source file:com.github.ithildir.liferay.mobile.go.GoSDKBuilder.java
protected void copyJarResource(JarURLConnection jarConnection, File destinationDir) throws IOException { String jarConnectionEntryName = jarConnection.getEntryName(); JarFile jarFile = jarConnection.getJarFile(); Enumeration<JarEntry> enu = jarFile.entries(); while (enu.hasMoreElements()) { JarEntry jarEntry = enu.nextElement(); String jarEntryName = jarEntry.getName(); if (jarEntryName.startsWith(jarConnectionEntryName)) { String fileName = jarEntryName; if (fileName.startsWith(jarConnectionEntryName)) { fileName = fileName.substring(jarConnectionEntryName.length()); }/*from w w w .j a va 2s .com*/ File file = new File(destinationDir, fileName); if (jarEntry.isDirectory()) { file.mkdirs(); } else { InputStream is = null; try { is = jarFile.getInputStream(jarEntry); FileUtils.copyInputStreamToFile(is, file); } finally { IOUtils.closeQuietly(is); } } } } }
From source file:org.springframework.web.context.support.ServletContextResourcePatternResolver.java
/** * Extract entries from the given jar by pattern. * @param jarFilePath the path to the jar file * @param entryPattern the pattern for jar entries to match * @param result the Set of matching Resources to add to *//*from w w w .j av a 2 s.c o m*/ private void doRetrieveMatchingJarEntries(String jarFilePath, String entryPattern, Set<Resource> result) { if (logger.isDebugEnabled()) { logger.debug("Searching jar file [" + jarFilePath + "] for entries matching [" + entryPattern + "]"); } try { JarFile jarFile = new JarFile(jarFilePath); try { for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) { JarEntry entry = entries.nextElement(); String entryPath = entry.getName(); if (getPathMatcher().match(entryPattern, entryPath)) { result.add(new UrlResource(ResourceUtils.URL_PROTOCOL_JAR, ResourceUtils.FILE_URL_PREFIX + jarFilePath + ResourceUtils.JAR_URL_SEPARATOR + entryPath)); } } } finally { jarFile.close(); } } catch (IOException ex) { if (logger.isWarnEnabled()) { logger.warn("Cannot search for matching resources in jar file [" + jarFilePath + "] because the jar cannot be opened through the file system", ex); } } }
From source file:com.imaginabit.yonodesperdicion.gcm.RegistrationIntentService.java
String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException { URL dirURL = clazz.getClassLoader().getResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) { /* A file path: easy enough */ return new File(dirURL.toURI()).list(); }// www .j a va 2s .com if (dirURL == null) { /* * In case of a jar file, we can't actually find a directory. * Have to assume the same jar as clazz. */ String me = clazz.getName().replace(".", "/") + ".class"; dirURL = clazz.getClassLoader().getResource(me); } if (dirURL.getProtocol().equals("jar")) { /* A JAR path */ String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file 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()); int checkSubdir = entry.indexOf("/"); if (checkSubdir >= 0) { // if it is a subdirectory, we just return the directory name entry = entry.substring(0, checkSubdir); } result.add(entry); } } return result.toArray(new String[result.size()]); } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); }
From source file:com.krikelin.spotifysource.AppInstaller.java
protected void extractJar(String destDir, String jarFile) throws IOException { File destination = new File(destDir); java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile); java.util.Enumeration<JarEntry> enu = jar.entries(); while (enu.hasMoreElements()) { try {//w w w . j a va 2 s . c o m java.util.jar.JarEntry file = (java.util.jar.JarEntry) enu.nextElement(); java.io.File f = new java.io.File(destDir + java.io.File.separator + file.getName()); if (file.isDirectory()) { // if its a directory, create it f.mkdir(); continue; } java.io.InputStream is = jar.getInputStream(file); // get the input stream if (!(destination.exists())) { destination.createNewFile(); } java.io.FileOutputStream fos = new java.io.FileOutputStream(f); while (is.available() > 0) { // write contents of 'is' to 'fos' fos.write(is.read()); } fos.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.kuali.rice.krad.labs.LabsMultiFileUploadMultipleUsesOnOnePageAft.java
protected String[] getResourceListing(Class clazz, String pathStartsWith) throws Exception { System.out.println("In for getResourceListing"); String classPath = clazz.getName().replace(".", "/") + ".class"; URL dirUrl = clazz.getClassLoader().getResource(classPath); if (!"jar".equals(dirUrl.getProtocol())) { throw new UnsupportedOperationException("Cannot list files for URL " + dirUrl); }//from ww w .j a v a 2 s. c o m String jarPath = dirUrl.getPath().substring(5, dirUrl.getPath().indexOf("!")); //strip out only the JAR file JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")); Enumeration<JarEntry> entries = jar.entries(); Set<String> result = new HashSet<String>(); while (entries.hasMoreElements()) { String entry = entries.nextElement().getName(); if (entry.startsWith(pathStartsWith) && !entry.endsWith("/")) { //filter according to the pathStartsWith skipping directories result.add(entry); } } return result.toArray(new String[result.size()]); }
From source file:org.rhq.cassandra.schema.UpdateFolder.java
/** * Loads the initial set of update files based on the input folder. * * @return list of update files/* w ww. j a v a2s.c om*/ * @throws Exception */ private List<UpdateFile> loadUpdateFiles() throws Exception { List<UpdateFile> files = new ArrayList<UpdateFile>(); InputStream stream = null; try { URL resourceFolderURL = this.getClass().getClassLoader().getResource(folder); if (resourceFolderURL.getProtocol().equals("file")) { stream = this.getClass().getClassLoader().getResourceAsStream(folder); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String updateFile; while ((updateFile = reader.readLine()) != null) { files.add(new UpdateFile(folder + "/" + updateFile)); } } else if (resourceFolderURL.getProtocol().equals("jar")) { URL jarURL = this.getClass().getClassLoader().getResources(folder).nextElement(); JarURLConnection jarURLCon = (JarURLConnection) (jarURL.openConnection()); JarFile jarFile = jarURLCon.getJarFile(); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { String entry = entries.nextElement().getName(); if (entry.startsWith(folder) && !entry.equals(folder) && !entry.equals(folder + "/")) { files.add(new UpdateFile(entry)); } } } else if (resourceFolderURL.getProtocol().equals("vfs")) { URLConnection conn = resourceFolderURL.openConnection(); VirtualFile virtualFolder = (VirtualFile) conn.getContent(); for (VirtualFile virtualChild : virtualFolder.getChildren()) { if (!virtualChild.isDirectory()) { files.add(new UpdateFile(virtualChild.getPathNameRelativeTo(virtualFolder.getParent()))); } } } else { // In the event we get another protocol that we do not recognize, throw an // exception instead of failing silently. throw new RuntimeException( "The URL protocol [" + resourceFolderURL.getProtocol() + "] is not " + "supported"); } Collections.sort(files, new Comparator<UpdateFile>() { @Override public int compare(UpdateFile o1, UpdateFile o2) { return o1.compareTo(o2); } }); } catch (Exception e) { log.error("Error reading the list of update files.", e); throw e; } finally { if (stream != null) { try { stream.close(); } catch (Exception e) { log.error("Error closing the stream with the list of update files.", e); throw e; } } } return files; }
From source file:abs.backend.erlang.ErlApp.java
private void copyJarDirectory(JarFile jarFile, String inname, String outname) throws IOException { InputStream is = null;/* w ww .j av a2s .c om*/ for (JarEntry entry : Collections.list(jarFile.entries())) { if (entry.getName().startsWith(inname)) { String relFilename = entry.getName().substring(inname.length()); if (!entry.isDirectory()) { is = jarFile.getInputStream(entry); ByteStreams.copy(is, Files.newOutputStreamSupplier(new File(outname, relFilename))); } else { new File(outname, relFilename).mkdirs(); } } } is.close(); }
From source file:org.wisdom.test.WisdomBlackBoxRunner.java
/** * Detects if the bundle is present in the given directory. * The detection stops when a jar file contains a class file from target/classes and where sizes are equals. * * @param directory the directory to analyze. * @return the bundle file if detected./*from w w w.j a v a 2 s .c o m*/ * @throws java.io.IOException cannot open files. */ private File detectApplicationBundleIfExist(File directory) throws IOException { if (!directory.isDirectory()) { return null; } File[] files = directory.listFiles(); if (files == null) { return null; } // Find one entry from classes. final File classes = new File("target/classes"); Collection<File> clazzes = FileUtils.listFiles(classes, new String[] { "class" }, true); // Transform into classnames but using / and not . as package separator. Collection<String> classnames = Collections2.transform(clazzes, new Function<File, String>() { @Override public String apply(File input) { String absolute = input.getAbsolutePath(); return absolute.substring(classes.getAbsolutePath().length() + 1); } }); // Iterate over the set of jar files. for (File file : files) { if (!file.getName().endsWith("jar")) { continue; } JarFile jar = null; try { jar = new JarFile(file); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().endsWith(".class") && classnames.contains(entry.getName())) { // Found ! return file; } } } finally { IOUtils.closeQuietly(jar); } } return null; }
From source file:net.ymate.framework.unpack.Unpackers.java
private boolean __unpack(JarFile jarFile, String prefixPath) throws Exception { boolean _results = false; Enumeration<JarEntry> _entriesEnum = jarFile.entries(); for (; _entriesEnum.hasMoreElements();) { JarEntry _entry = _entriesEnum.nextElement(); if (StringUtils.startsWith(_entry.getName(), prefixPath)) { if (!_entry.isDirectory()) { _LOG.info("Synchronizing resource file: " + _entry.getName()); // String _entryName = StringUtils.substringAfter(_entry.getName(), prefixPath); File _targetFile = new File(RuntimeUtils.getRootPath(false), _entryName); _targetFile.getParentFile().mkdirs(); IOUtils.copyLarge(jarFile.getInputStream(_entry), new FileOutputStream(_targetFile)); _results = true;// w w w. ja v a2 s . c om } } } return _results; }
From source file:com.aurel.track.util.PluginUtils.java
/** * Gets the names of all the subclasses from a jar which extend (implement) a superclass (interface). * It does not deal with packages, it tries to find all such classes within the jar * Sometimes it is not enough to find the classes in a package because: * 1. The subclasses are not necessary in the same package as the superclass * 2. When the same package exists in two or more jar files then only the first jar is found (by URL) * @param file the jar file//from w ww . j av a 2s . co m * @param superclass * @param constructorClasses * @param constructorParameters * @return */ private static List<String> getSubclassesFromJarInLib(File file, Class superclass, Class[] constructorClasses, Object[] constructorParameters) { List<String> classes = new ArrayList<String>(); Object o; if (file == null || !file.exists() || superclass == null) { return classes; } JarFile jfile = null; try { jfile = new JarFile(file); } catch (IOException e1) { } if (jfile != null) { LOGGER.debug("Searching in " + file.getName()); try { Enumeration e = jfile.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); String entryname = entry.getName(); if (//entryname.startsWith(starts) && //(entryname.lastIndexOf('/')<=starts.length()) && entryname.endsWith(".class")) { String classname = entryname.substring(0, entryname.length() - 6); if (classname.startsWith("/")) { classname = classname.substring(1); } classname = classname.replace('/', '.'); try { // Try to create an instance of the object Class c = null; try { c = Class.forName(classname); } catch (Exception classByName) { LOGGER.debug( "Finding a class by name " + classname + " failed with " + classByName); } if (c != null) { o = null; if (constructorClasses == null || constructorClasses.length == 0) { //default constructor o = c.newInstance(); } else { //probably lucene analyzers with Version Constructor ct = null; try { ct = c.getConstructor(constructorClasses); } catch (Exception getConst) { LOGGER.debug(getConst); } if (ct == null) { //older analyzers (lucene<3) try { //default constructor. Some analyzers use default constructor even in lucene 3.0 //(although the corresponding javadoc states it with Version parameter) o = c.newInstance(); } catch (Exception exception) { } } else { try { if (ct != null) { o = ct.newInstance(constructorParameters); } } catch (Exception callConst) { } } } if (o != null && superclass.isInstance(o)) { classes.add(classname); LOGGER.debug("Found analizer: " + classname); } } } catch (InstantiationException iex) { // We try to instanciate an interface // or an object that does not have a // default constructor, ignore } catch (IllegalAccessException iaex) { // The class is not public, ignore } catch (Exception ex) { LOGGER.warn("Finding a class in a jar failed with exception " + ex.getMessage()); } } } } catch (Exception t) { LOGGER.warn("Finding a class in a jar failed with throwable " + t.getMessage()); } } return classes; }