List of usage examples for java.util.jar JarFile entries
public Enumeration<JarEntry> entries()
From source file:com.ebay.cloud.cms.metadata.dataloader.MetadataDataLoader.java
private void loadMetaClassesFromPath(String pathName) { try {//from ww w. ja va 2s.co m URL url = MetadataDataLoader.class.getResource(pathName); URI uri = url.toURI(); BasicDBList metas = new BasicDBList(); if (uri.isOpaque()) { JarURLConnection connection = (JarURLConnection) url.openConnection(); JarFile jar = connection.getJarFile(); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith(pathName.substring(1)) && entry.getName().endsWith(".json")) { InputStream is = jar.getInputStream(entry); readMetaClass(is, metas); } } } else { File dir = new File(url.toURI()); Collection<File> files = FileUtils.listFiles(dir, new String[] { "json" }, true); for (File f : files) { InputStream is = new FileInputStream(f); readMetaClass(is, metas); } } loadMetaClasses(metas); } catch (Exception e) { logger.error("error in loading metadata: ", e); } }
From source file:com.technophobia.substeps.report.DefaultExecutionReportBuilder.java
public void copyJarResourcesRecursively(final File destination, final JarURLConnection jarConnection) throws IOException { final JarFile jarFile = jarConnection.getJarFile(); for (final JarEntry entry : Collections.list(jarFile.entries())) { if (entry.getName().startsWith(jarConnection.getEntryName())) { final String fileName = StringUtils.removeStart(entry.getName(), jarConnection.getEntryName()); if (!entry.isDirectory()) { InputStream entryInputStream = null; try { entryInputStream = jarFile.getInputStream(entry); FileUtils.copyInputStreamToFile(entryInputStream, new File(destination, fileName)); } finally { IOUtils.closeQuietly(entryInputStream); }/*from w w w . j a v a 2 s.co m*/ } else { new File(destination, fileName).mkdirs(); } } } }
From source file:org.lightcouch.CouchDbDesign.java
private void enumerateJar(String path) throws IOException { path = path.substring(5, path.indexOf("!")); JarFile j = new JarFile(path); Enumeration<JarEntry> e = j.entries(); while (e.hasMoreElements()) { JarEntry f = e.nextElement(); String name = f.getName(); if (name.startsWith(DESIGN_DOCS_DIR + "/") && name.length() > DESIGN_DOCS_DIR.length() + 1) { name = name.substring(DESIGN_DOCS_DIR.length() + 1); if (log.isWarnEnabled() && !name.endsWith("/") && allDesignResources.contains(name)) log.warn("Design resource duplicate: " + name); allDesignResources.add(name); }/*from w ww.j a v a2 s.co m*/ } }
From source file:com.eviware.soapui.plugins.JarClassLoader.java
private void addScriptsIn(JarFile jarFile) throws IOException { boolean hasScripts = false; if (containsScripts(jarFile)) { File scriptsDirectory = Tools.createTemporaryDirectory(); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); if (isScript(jarEntry)) { String pathToScript = jarEntry.getName(); File outputFile = null; int lastSlashIndex = pathToScript.lastIndexOf('/'); if (lastSlashIndex >= 0) { File packageDirectory = new File(scriptsDirectory, pathToScript.substring(0, lastSlashIndex)); if (!packageDirectory.exists() || !packageDirectory.isDirectory()) { if (!packageDirectory.mkdirs()) { log.error("Failed to create directory for [" + pathToScript + "]"); packageDirectory = null; }/*from w ww . j a v a2 s. co m*/ } if (packageDirectory != null) { outputFile = new File(packageDirectory, pathToScript.substring(lastSlashIndex + 1)); } } if (outputFile != null) { FileUtils.copyInputStreamToFile(jarFile.getInputStream(jarEntry), outputFile); hasScripts = true; } } } /* if (hasScripts) { URL scriptsUrl = scriptsDirectory.toURI().toURL(); SoapUIPro.getSoapUIGroovyClassLoader().addURL(scriptsUrl); scriptClassLoader = new GroovyClassLoader(SoapUIPro.getSoapUIGroovyClassLoader()); scriptClassLoader.addURL(scriptsUrl); } */ } }
From source file:com.liferay.ide.maven.core.util.DefaultMaven2OsgiConverter.java
private String getGroupIdFromPackage(File artifactFile) { try {// w w w .j a v a2 s . com /* get package names from jar */ Set packageNames = new HashSet(); JarFile jar = new JarFile(artifactFile, false); Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.getName().endsWith(".class")) { File f = new File(entry.getName()); String packageName = f.getParent(); if (packageName != null) { packageNames.add(packageName); } } } /* find the top package */ String[] groupIdSections = null; for (Iterator it = packageNames.iterator(); it.hasNext();) { String packageName = (String) it.next(); String[] packageNameSections = packageName.split("\\" + FILE_SEPARATOR); if (groupIdSections == null) { /* first candidate */ groupIdSections = packageNameSections; } else // if ( packageNameSections.length < groupIdSections.length ) { /* * find the common portion of current package and previous selected groupId */ int i; for (i = 0; (i < packageNameSections.length) && (i < groupIdSections.length); i++) { if (!packageNameSections[i].equals(groupIdSections[i])) { break; } } groupIdSections = new String[i]; System.arraycopy(packageNameSections, 0, groupIdSections, 0, i); } } if ((groupIdSections == null) || (groupIdSections.length == 0)) { return null; } /* only one section as id doesn't seem enough, so ignore it */ if (groupIdSections.length == 1) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < groupIdSections.length; i++) { sb.append(groupIdSections[i]); if (i < groupIdSections.length - 1) { sb.append('.'); } } return sb.toString(); } catch (IOException e) { /* we took all the precautions to avoid this */ throw new RuntimeException(e); } }
From source file:org.openeos.tools.maven.plugins.GenerateEntitiesMojo.java
private List<File> findLiquibaseFiles(Artifact artifact) throws IOException { if (artifact == null) { return Collections.emptyList(); }/*from w ww . j a va 2s .c o m*/ List<File> result = new ArrayList<File>(); if (artifact.getType().equals("jar")) { File file = artifact.getFile(); FileSystem fs = FileSystems.newFileSystem(Paths.get(file.getAbsolutePath()), this.getClass().getClassLoader()); PathMatcher matcher = fs.getPathMatcher("glob:" + searchpath); JarFile jarFile = new JarFile(file); Enumeration<JarEntry> entries = jarFile.entries(); TreeSet<JarEntry> setEntries = new TreeSet<JarEntry>(new Comparator<JarEntry>() { @Override public int compare(JarEntry o1, JarEntry o2) { return o1.getName().compareTo(o2.getName()); } }); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (matcher.matches(fs.getPath(entry.getName()))) { setEntries.add(entry); } } for (JarEntry entry : setEntries) { File resultFile = File.createTempFile("generate-entities-maven", ".xml"); FileOutputStream out = new FileOutputStream(resultFile); InputStream in = jarFile.getInputStream(entry); IOUtils.copy(in, out); in.close(); out.close(); result.add(resultFile); } jarFile.close(); } return result; }
From source file:org.ow2.proactive_grid_cloud_portal.studio.StudioRest.java
@Override public ArrayList<String> getClasses(@HeaderParam("sessionid") String sessionId) throws NotConnectedRestException { String userName = getUserName(sessionId); File classesDir = new File(getFileStorageSupport().getWorkflowsDir(userName), "classes"); ArrayList<String> classes = new ArrayList<>(); if (classesDir.exists()) { File[] jars = classesDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".jar"); }//from w w w . j a va 2 s . co m }); for (File jar : jars) { try { JarFile jarFile = new JarFile(jar.getAbsolutePath()); Enumeration allEntries = jarFile.entries(); while (allEntries.hasMoreElements()) { JarEntry entry = (JarEntry) allEntries.nextElement(); String name = entry.getName(); if (name.endsWith(".class")) { String noExt = name.substring(0, name.length() - ".class".length()); classes.add(noExt.replaceAll("/", ".")); } } } catch (IOException e) { logger.warn("Could not read jar file " + jar, e); } } } return classes; }
From source file:org.teavm.maven.BuildJavascriptTestMojo.java
private void findTestClassesInJar(ClassLoader classLoader, JarFile jarFile) { Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; }// ww w. j av a2s .c o m String className = entry.getName().substring(0, entry.getName().length() - ".class".length()) .replace('/', '.'); addCandidate(classLoader, className); } }
From source file:appeng.recipes.loader.RecipeResourceCopier.java
/** * List directory contents for a resource folder. Not recursive. This is basically a brute-force implementation. Works for regular files and also JARs. * * @param clazz Any java class that lives in the same place as the resources you want. * @param path Should end with "/", but not start with one. * * @return Just the name of each member item, not the full paths. * * @throws URISyntaxException if it is a file path and the URL can not be converted to URI * @throws IOException if jar path can not be decoded * @throws UnsupportedOperationException if it is neither in jar nor in file path *///from ww w . ja va2s. c o m @Nonnull private String[] getResourceListing(@Nonnull final Class<?> clazz, @Nonnull final String path) throws URISyntaxException, IOException { assert clazz != null; assert path != null; final ClassLoader classLoader = clazz.getClassLoader(); if (classLoader == null) { throw new IllegalStateException( "ClassLoader was not found. It was probably loaded at a inappropriate time"); } URL dirURL = classLoader.getResource(path); if (dirURL != null) { final String protocol = dirURL.getProtocol(); if (protocol.equals(FILE_PROTOCOL)) { // A file path: easy enough final URI uriOfURL = dirURL.toURI(); final File fileOfURI = new File(uriOfURL); final String[] filesAndDirectoriesOfURI = fileOfURI.list(); if (filesAndDirectoriesOfURI == null) { throw new IllegalStateException( "Files and Directories were illegal. Either an abstract pathname does not denote a directory, or an I/O error occured."); } else { return filesAndDirectoriesOfURI; } } } if (dirURL == null) { /* * In case of a jar file, we can't actually find a directory. * Have to assume the same jar as clazz. */ final String className = clazz.getName(); final Matcher matcher = DOT_COMPILE_PATTERN.matcher(className); final String me = matcher.replaceAll("/") + CLASS_EXTENSION; dirURL = classLoader.getResource(me); } if (dirURL != null) { final String protocol = dirURL.getProtocol(); if (protocol.equals(JAR_PROTOCOL)) { /* A JAR path */ final String dirPath = dirURL.getPath(); final String jarPath = dirPath.substring(5, dirPath.indexOf('!')); // strip out only // the JAR file final JarFile jar = new JarFile(URLDecoder.decode(jarPath, UTF_8_ENCODING)); try { final Enumeration<JarEntry> entries = jar.entries(); // gives ALL entries in jar final Collection<String> result = new HashSet<String>(INITIAL_RESOURCE_CAPACITY); // avoid duplicates // in case it is a // subdirectory while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); final String entryFullName = entry.getName(); if (entryFullName.startsWith(path)) { // filter according to the path String entryName = entryFullName.substring(path.length()); final int checkSubDir = entryName.indexOf('/'); if (checkSubDir >= 0) { // if it is a subdirectory, we just return the directory name entryName = entryName.substring(0, checkSubDir); } result.add(entryName); } } return result.toArray(new String[result.size()]); } finally { jar.close(); } } } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); }
From source file:edu.cornell.med.icb.io.ResourceFinder.java
/** * List directory contents for a resource folder. Not recursive, does not return * directory entries. Works for regular files and also JARs. * * @param clazz Any java class that lives in the same place as the resources you want. * @param pathVal the path to find files for * @return Each member item (no path information) * @throws URISyntaxException bad URI syntax * @throws IOException error reading/*from w w w. ja v a2 s .co m*/ */ public String[] getResourceListing(final Class clazz, final String pathVal) throws URISyntaxException, IOException { // Enforce all paths are separated by "/", they do not start with "/" and // the DO end with "/". String path = pathVal.replace("\\", "/"); if (!path.endsWith("/")) { path += "/"; } while (path.startsWith("/")) { path = path.substring(1); } URL dirURL = findResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) { /* A file path: easy enough */ return new File(dirURL.toURI()).list(); } if (dirURL == null) { /* * In case of a jar file, we can't actually find a directory. * Have to assume the same jar as clazz. */ final String classFilename = clazz.getName().replace(".", "/") + ".class"; dirURL = findResource(classFilename); } if (dirURL.getProtocol().equals("jar")) { /* A JAR path */ String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf('!')); if (jarPath.charAt(2) == ':') { jarPath = jarPath.substring(1); } jarPath = URLDecoder.decode(jarPath, "UTF-8"); final JarFile jar = new JarFile(jarPath); final Enumeration<JarEntry> entries = jar.entries(); final Set<String> result = new HashSet<String>(); while (entries.hasMoreElements()) { final String name = entries.nextElement().getName(); //filter according to the path if (name.startsWith(path)) { final String entry = name.substring(path.length()); if (entry.length() == 0) { // Skip the directory entry for path continue; } final int checkSubdir = entry.indexOf('/'); if (checkSubdir >= 0) { // Skip sub dirs continue; } result.add(entry); } } return result.toArray(new String[result.size()]); } throw new UnsupportedOperationException("Cannot list files for URL " + dirURL); }