List of usage examples for java.util.jar JarEntry getName
public String getName()
From source file:org.openmrs.module.webservices.rest.web.RestUtil.java
/** * Gets a list of classes in a given package. Note that interfaces are not returned. * // w w w . ja va 2s . com * @param pkgname the package name. * @param suffix the ending text on name. eg "Resource.class" * @return the list of classes. */ public static ArrayList<Class<?>> getClassesForPackage(String pkgname, String suffix) throws IOException { ArrayList<Class<?>> classes = new ArrayList<Class<?>>(); //Get a File object for the package File directory = null; String relPath = pkgname.replace('.', '/'); Enumeration<URL> resources = OpenmrsClassLoader.getInstance().getResources(relPath); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); if (resource == null) { throw new RuntimeException("No resource for " + relPath); } try { directory = new File(resource.toURI()); } catch (URISyntaxException e) { throw new RuntimeException(pkgname + " (" + resource + ") does not appear to be a valid URL / URI. Strange, since we got it from the system...", e); } catch (IllegalArgumentException ex) { //ex.printStackTrace(); } //If folder exists, look for all resource class files in it. if (directory != null && directory.exists()) { //Get the list of the files contained in the package String[] files = directory.list(); for (int i = 0; i < files.length; i++) { //We are only interested in Resource.class files if (files[i].endsWith(suffix)) { //Remove the .class extension String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6); try { Class<?> cls = Class.forName(className); if (!cls.isInterface()) classes.add(cls); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException loading " + className); } } } } else { //Directory does not exist, look in jar file. try { String fullPath = resource.getFile(); String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", ""); JarFile jarFile = new JarFile(jarPath); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String entryName = entry.getName(); if (!entryName.endsWith(suffix)) continue; if (entryName.startsWith(relPath) && entryName.length() > (relPath.length() + "/".length())) { String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", ""); try { Class<?> cls = Class.forName(className); if (!cls.isInterface()) classes.add(cls); } catch (ClassNotFoundException e) { throw new RuntimeException("ClassNotFoundException loading " + className); } } } } catch (IOException e) { throw new RuntimeException( pkgname + " (" + directory + ") does not appear to be a valid package", e); } } } return classes; }
From source file:org.mule.util.FileUtils.java
/** * Extract recources contain if jar (have to in classpath) * * @param connection JarURLConnection to jar library * @param outputDir Directory for unpack recources * @param keepParentDirectory true - full structure of directories is kept; false - file - removed all directories, directory - started from resource point * @throws IOException if any error//from ww w. j a v a 2 s. c o m */ private static void extractJarResources(JarURLConnection connection, File outputDir, boolean keepParentDirectory) throws IOException { JarFile jarFile = connection.getJarFile(); JarEntry jarResource = connection.getJarEntry(); Enumeration entries = jarFile.entries(); InputStream inputStream = null; OutputStream outputStream = null; int jarResourceNameLenght = jarResource.getName().length(); for (; entries.hasMoreElements();) { JarEntry entry = (JarEntry) entries.nextElement(); if (entry.getName().startsWith(jarResource.getName())) { String path = outputDir.getPath() + File.separator + entry.getName(); //remove directory struct for file and first dir for directory if (!keepParentDirectory) { if (entry.isDirectory()) { if (entry.getName().equals(jarResource.getName())) { continue; } path = outputDir.getPath() + File.separator + entry.getName().substring(jarResourceNameLenght, entry.getName().length()); } else { if (entry.getName().length() > jarResourceNameLenght) { path = outputDir.getPath() + File.separator + entry.getName().substring(jarResourceNameLenght, entry.getName().length()); } else { path = outputDir.getPath() + File.separator + entry.getName() .substring(entry.getName().lastIndexOf("/"), entry.getName().length()); } } } File file = FileUtils.newFile(path); if (!file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { throw new IOException("Could not create directory: " + file.getParentFile()); } } if (entry.isDirectory()) { if (!file.exists() && !file.mkdirs()) { throw new IOException("Could not create directory: " + file); } } else { try { inputStream = jarFile.getInputStream(entry); outputStream = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } } } }
From source file:net.aepik.alasca.core.ldap.Schema.java
/** * Retourne l'ensemble des syntaxes connues, qui sont * contenues dans le package 'ldap.syntax'. * @return String[] L'ensemble des noms de classes de syntaxes. *///w w w . j av a 2s . c o m public static String[] getSyntaxes() { String[] result = null; try { String packageName = getSyntaxPackageName(); URL url = Schema.class.getResource("/" + packageName.replace('.', '/')); if (url == null) { return null; } if (url.getProtocol().equals("jar")) { Vector<String> vectTmp = new Vector<String>(); int index = url.getPath().indexOf('!'); String path = URLDecoder.decode(url.getPath().substring(index + 1), "UTF-8"); JarFile jarFile = new JarFile(URLDecoder.decode(url.getPath().substring(5, index), "UTF-8")); if (path.charAt(0) == '/') { path = path.substring(1); } Enumeration<JarEntry> jarFiles = jarFile.entries(); while (jarFiles.hasMoreElements()) { JarEntry tmp = jarFiles.nextElement(); // // Pour chaque fichier dans le jar, on regarde si c'est un // fichier de classe Java. // if (!tmp.isDirectory() && tmp.getName().substring(tmp.getName().length() - 6).equals(".class") && tmp.getName().startsWith(path)) { int i = tmp.getName().lastIndexOf('/'); String classname = tmp.getName().substring(i + 1, tmp.getName().length() - 6); vectTmp.add(classname); } } jarFile.close(); result = new String[vectTmp.size()]; for (int i = 0; i < vectTmp.size(); i++) { result[i] = vectTmp.elementAt(i); } } else if (url.getProtocol().equals("file")) { // // On cr le fichier associ pour parcourir son contenu. // En l'occurence, c'est un dossier. // File[] files = (new File(url.toURI())).listFiles(); // // On liste tous les fichiers qui sont dedans. // On les stocke dans un vecteur ... // Vector<File> vectTmp = new Vector<File>(); for (File f : files) { if (!f.isDirectory()) { vectTmp.add(f); } } // // ... pour ensuite les mettres dans le tableau de resultat. // result = new String[vectTmp.size()]; for (int i = 0; i < vectTmp.size(); i++) { String name = vectTmp.elementAt(i).getName(); int a = name.indexOf('.'); name = name.substring(0, a); result[i] = name; } } } catch (Exception e) { e.printStackTrace(); } if (result != null) { Arrays.sort(result); } return result; }
From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java
private static void writeJarEntries(JarFile jar, JarOutputStream jos, String signatureName) throws IOException { for (Enumeration<?> jarEntries = jar.entries(); jarEntries.hasMoreElements();) { JarEntry jarEntry = (JarEntry) jarEntries.nextElement(); if (!jarEntry.isDirectory()) { String entryName = jarEntry.getName(); // Signature files not to write across String sigFileLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName, SIGNATURE_EXT) .toUpperCase();/*from www . j ava 2 s . c om*/ String dsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName, DSA_SIG_BLOCK_EXT); String rsaSigBlockLocation = MessageFormat.format(METAINF_FILE_LOCATION, signatureName, RSA_SIG_BLOCK_EXT); // Do not write across existing manifest or matching signature files if ((!entryName.equalsIgnoreCase(MANIFEST_LOCATION)) && (!entryName.equalsIgnoreCase(sigFileLocation)) && (!entryName.equalsIgnoreCase(dsaSigBlockLocation)) && (!entryName.equalsIgnoreCase(rsaSigBlockLocation))) { // New JAR entry based on original JarEntry newJarEntry = new JarEntry(jarEntry.getName()); newJarEntry.setMethod(jarEntry.getMethod()); newJarEntry.setCompressedSize(jarEntry.getCompressedSize()); newJarEntry.setCrc(jarEntry.getCrc()); jos.putNextEntry(newJarEntry); InputStream jis = null; try { jis = jar.getInputStream(jarEntry); byte[] buffer = new byte[2048]; int read = -1; while ((read = jis.read(buffer)) != -1) { jos.write(buffer, 0, read); } jos.closeEntry(); } finally { IOUtils.closeQuietly(jis); } } } } }
From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java
/** * Find all resources from a given jar file and add them to the provided * list.//from ww w . ja v a 2s .c o m * * @author paouelle * * @param urls the non-<code>null</code> collection of resources where to add new * found resources * @param url the non-<code>null</code> url for the jar where to find resources * @param resource the non-<code>null</code> resource being scanned that * corresponds to given package * @param cl the classloader to find the resources with */ private static void findResourcesFromJar(Collection<URL> urls, URL url, String resource, ClassLoader cl) { try { final JarURLConnection conn = (JarURLConnection) url.openConnection(); final URL jurl = conn.getJarFileURL(); try (final JarInputStream jar = new JarInputStream(jurl.openStream());) { while (true) { final JarEntry entry = jar.getNextJarEntry(); if (entry == null) { break; } final String name = entry.getName(); if (name.startsWith(resource)) { final URL u = cl.getResource(name); if (u != null) { urls.add(u); } } } } } catch (IOException e) { throw new IllegalArgumentException("unable to find resources in package", e); } }
From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java
/** * Find all classes from a given jar file and add them to the provided * list.// www. j a v a 2 s.c o m * * @author paouelle * * @param classes the non-<code>null</code> collection of classes where to add new * found classes * @param url the non-<code>null</code> url for the jar where to find classes * @param resource the non-<code>null</code> resource being scanned that * corresponds to given package * @param cl the classloader to find the classes with */ private static void findClassesFromJar(Collection<Class<?>> classes, URL url, String resource, ClassLoader cl) { try { final JarURLConnection conn = (JarURLConnection) url.openConnection(); final URL jurl = conn.getJarFileURL(); try (final JarInputStream jar = new JarInputStream(jurl.openStream());) { while (true) { final JarEntry entry = jar.getNextJarEntry(); if (entry == null) { break; } final String name = entry.getName(); if (name.endsWith(".class") && name.startsWith(resource)) { final String cname = name.substring(0, name.length() - 6 // 6 for .class ).replace(File.separatorChar, '.'); try { classes.add(cl.loadClass(cname)); } catch (ClassNotFoundException e) { // ignore it } } } } } catch (IOException e) { throw new IllegalArgumentException("unable to find classes in package", e); } }
From source file:co.cask.cdap.internal.app.runtime.webapp.JarExploderTest.java
@Test public void testExplodeA() throws Exception { URL jarUrl = getClass().getResource("/test_explode.jar"); Assert.assertNotNull(jarUrl);/*from ww w. j ava 2 s .c om*/ File dest = TEMP_FOLDER.newFolder(); int numFiles = JarExploder.explode(new File(jarUrl.toURI()), dest, new Predicate<JarEntry>() { @Override public boolean apply(JarEntry input) { return input.getName().startsWith("test_explode/a"); } }); Assert.assertEquals(aFileContentMap.size(), numFiles); verifyA(dest); }
From source file:nl.tue.gale.ae.config.GaleContextLoader.java
private void findInJar(ServletContext sc, String path, List<String> locations) { try {//from ww w . j ava 2s . co m JarFile jar = new JarFile(sc.getRealPath(path)); for (JarEntry entry : enumIterable(jar.entries())) { if (entry.getName().endsWith("-galeconfig.xml")) locations.add("classpath:" + entry.getName()); } jar.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.navercorp.pinpoint.bootstrap.java9.module.JarFileAnalyzerTest.java
@Test public void filter_emptyPackage() { JarFileAnalyzer.JarEntryFilter filter = new JarFileAnalyzer.PackageFilter(); JarEntry jarEntry = mock(JarEntry.class); when(jarEntry.getName()).thenReturn("test.class"); String empty = filter.filter(jarEntry); Assert.assertNull(empty);/* w w w . j a v a 2 s . c o m*/ }
From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.TypeLibraryUtil.java
/** * Adding the TypeLibProtocal to the name for the xsd entry. * * @param typeLibName the type lib name/*from ww w. j a va2 s .c o m*/ * @param baseLocation the base location * @return the dependency stream * @throws CoreException the core exception * @throws IOException Signals that an I/O exception has occurred. */ public static InputStream getDependencyStream(String typeLibName, String baseLocation) throws CoreException, IOException { if (baseLocation.toLowerCase().startsWith("jar:file:/")) { JarFile jarFile = new JarFile(getJarFile(baseLocation.substring(10, baseLocation.length()))); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith(SOATypeLibraryConstants.INFO_DEP_XML_PATH_IN_JAR) && entry.getName().endsWith(SOATypeLibraryConstants.FILE_TYPE_DEP_XML)) { return jarFile.getInputStream(entry); } } } else { IProject project = WorkspaceUtil.getProject(typeLibName); if (project.isAccessible() && project.hasNature(GlobalRepositorySystem.instanceOf() .getActiveRepositorySystem().getProjectNatureId(SupportedProjectType.TYPE_LIBRARY))) { return project.getFile(SOATypeLibraryConstants.FOLDER_META_SRC_META_INF + WorkspaceUtil.PATH_SEPERATOR + project.getName() + WorkspaceUtil.PATH_SEPERATOR + SOATypeLibraryConstants.FILE_TYPE_DEP_XML).getContents(); } } throw new IOException("InpuStream could not be obtained with the type lib Name " + typeLibName + " and base location " + baseLocation); }