Example usage for java.util.jar JarEntry getName

List of usage examples for java.util.jar JarEntry getName

Introduction

In this page you can find the example usage for java.util.jar JarEntry getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

From source file:net.sf.keystore_explorer.crypto.jcepolicy.JcePolicyUtil.java

/**
 * Get a JCE policy's details./* ww  w.ja  v  a 2 s.  c o m*/
 *
 * @param jcePolicy
 *            JCE policy
 * @return Policy details
 * @throws CryptoException
 *             If there was a problem getting the policy details
 */
public static String getPolicyDetails(JcePolicy jcePolicy) throws CryptoException {
    try {
        StringWriter sw = new StringWriter();

        File file = getJarFile(jcePolicy);

        // if there is no policy file at all, return empty string
        if (!file.exists()) {
            return "";
        }

        JarFile jar = new JarFile(file);

        Enumeration<JarEntry> jarEntries = jar.entries();

        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();

            String entryName = jarEntry.getName();

            if (!jarEntry.isDirectory() && entryName.endsWith(".policy")) {
                sw.write(entryName + ":\n\n");

                InputStreamReader isr = null;
                try {
                    isr = new InputStreamReader(jar.getInputStream(jarEntry));
                    CopyUtil.copy(isr, sw);
                } finally {
                    IOUtils.closeQuietly(isr);
                }

                sw.write('\n');
            }
        }

        return sw.toString();
    } catch (IOException ex) {
        throw new CryptoException(
                MessageFormat.format(res.getString("NoGetPolicyDetails.exception.message"), jcePolicy), ex);
    }
}

From source file:eu.sisob.uma.footils.File.FileFootils.java

public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection)
        throws IOException {

    final JarFile jarFile = jarConnection.getJarFile();

    for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
        final JarEntry entry = e.nextElement();
        if (entry.getName().startsWith(jarConnection.getEntryName())) {
            final String filename = StringUtils.removeStart(entry.getName(), //
                    jarConnection.getEntryName());

            final File f = new File(destDir, filename);
            if (!entry.isDirectory()) {
                final InputStream entryInputStream = jarFile.getInputStream(entry);
                if (!FileFootils.copyStream(entryInputStream, f)) {
                    return false;
                }/*from  w  ww  .  jav  a 2  s . co  m*/
                entryInputStream.close();
            } else {
                if (!FileFootils.ensureDirectoryExists(f)) {
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    return true;
}

From source file:org.jahia.utils.maven.plugin.support.MavenAetherHelperUtils.java

public static Set<PackageInfo> getJarPackages(File jarFile, boolean optionalJar, String version,
        ParsingContext parsingContext, Log log) {
    JarInputStream jarInputStream = null;
    Set<PackageInfo> packageInfos = new LinkedHashSet<PackageInfo>();
    if (jarFile == null) {
        log.warn("File is null !");
        return packageInfos;
    }/*  w w  w.  j  a  va 2  s. co  m*/
    if (!jarFile.exists()) {
        log.warn("File " + jarFile + " does not exist !");
        return packageInfos;
    }
    log.debug("Scanning JAR " + jarFile + "...");
    try {
        jarInputStream = new JarInputStream(new FileInputStream(jarFile));
        JarEntry jarEntry = null;
        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
            String jarPackageName = jarEntry.getName().replaceAll("/", ".");
            if (jarPackageName.endsWith(".")) {
                jarPackageName = jarPackageName.substring(0, jarPackageName.length() - 1);
            }
            if (jarPackageName.startsWith("META-INF") || jarPackageName.startsWith("WEB-INF")
                    || jarPackageName.startsWith("OSGI-INF")) {
                continue;
            }
            packageInfos.addAll(PackageUtils.getPackagesFromClass(jarPackageName, optionalJar, version,
                    jarFile.getCanonicalPath(), parsingContext));
        }
    } catch (IOException e) {
        log.error(e);
        ;
    } finally {
        IOUtils.closeQuietly(jarInputStream);
    }
    return packageInfos;
}

From source file:net.dataforte.commons.resources.ClassUtils.java

/**
 * Returns all resources beneath a folder. Supports filesystem, JARs and JBoss VFS
 * /* w w  w  .j  a va  2  s .c om*/
 * @param folder
 * @return
 * @throws IOException
 */
public static URL[] getResources(String folder) throws IOException {
    List<URL> urls = new ArrayList<URL>();
    ArrayList<File> directories = new ArrayList<File>();
    try {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new IOException("Can't get class loader.");
        }
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(folder);
        while (resources.hasMoreElements()) {
            URL res = resources.nextElement();
            String resProtocol = res.getProtocol();
            if (resProtocol.equalsIgnoreCase("jar")) {
                JarURLConnection conn = (JarURLConnection) res.openConnection();
                JarFile jar = conn.getJarFile();
                for (JarEntry e : Collections.list(jar.entries())) {
                    if (e.getName().startsWith(folder) && !e.getName().endsWith("/")) {
                        urls.add(new URL(
                                joinUrl(res.toString(), "/" + e.getName().substring(folder.length() + 1)))); // FIXME: fully qualified name
                    }
                }
            } else if (resProtocol.equalsIgnoreCase("vfszip") || resProtocol.equalsIgnoreCase("vfs")) { // JBoss 5+
                try {
                    Object content = res.getContent();
                    Method getChildren = content.getClass().getMethod("getChildren");
                    List<?> files = (List<?>) getChildren.invoke(res.getContent());
                    Method toUrl = null;
                    for (Object o : files) {
                        if (toUrl == null) {
                            toUrl = o.getClass().getMethod("toURL");
                        }
                        urls.add((URL) toUrl.invoke(o));
                    }
                } catch (Exception e) {
                    throw new IOException("Error while scanning " + res.toString(), e);
                }
            } else if (resProtocol.equalsIgnoreCase("file")) {
                directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            } else {
                throw new IOException("Unknown protocol for resource: " + res.toString());
            }
        }
    } catch (NullPointerException x) {
        throw new IOException(folder + " does not appear to be a valid folder (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new IOException(folder + " does not appear to be a valid folder (Unsupported encoding)");
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (String file : files) {
                urls.add(new URL("file:///" + joinPath(directory.getAbsolutePath(), file)));
            }
        } else {
            throw new IOException(
                    folder + " (" + directory.getPath() + ") does not appear to be a valid folder");
        }
    }
    URL[] urlsA = new URL[urls.size()];
    urls.toArray(urlsA);
    return urlsA;
}

From source file:org.kse.crypto.jcepolicy.JcePolicyUtil.java

/**
 * Get a JCE policy's details.//from w w  w.  j  av a2 s  .c o m
 *
 * @param jcePolicy
 *            JCE policy
 * @return Policy details
 * @throws CryptoException
 *             If there was a problem getting the policy details
 */
public static String getPolicyDetails(JcePolicy jcePolicy) throws CryptoException {
    JarFile jarFile = null;
    try {
        StringWriter sw = new StringWriter();

        File file = getJarFile(jcePolicy);

        // if there is no policy file at all, return empty string
        if (!file.exists()) {
            return "";
        }

        jarFile = new JarFile(file);

        Enumeration<JarEntry> jarEntries = jarFile.entries();

        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();

            String entryName = jarEntry.getName();

            if (!jarEntry.isDirectory() && entryName.endsWith(".policy")) {
                sw.write(entryName + ":\n\n");

                InputStreamReader isr = null;
                try {
                    isr = new InputStreamReader(jarFile.getInputStream(jarEntry));
                    CopyUtil.copy(isr, sw);
                } finally {
                    IOUtils.closeQuietly(isr);
                }

                sw.write('\n');
            }
        }

        return sw.toString();
    } catch (IOException ex) {
        throw new CryptoException(
                MessageFormat.format(res.getString("NoGetPolicyDetails.exception.message"), jcePolicy), ex);
    } finally {
        IOUtils.closeQuietly(jarFile);
    }
}

From source file:org.sherlok.utils.BundleCreatorUtil.java

private static void createBundle(Set<BundleDef> bundleDefs) throws Exception {

    // create fake POM from bundles and copy it
    String fakePom = MavenPom.writePom(bundleDefs, "BundleCreator", System.currentTimeMillis() + "");// must be unique
    Artifact rootArtifact = new DefaultArtifact(fakePom);
    LOG.trace("* rootArtifact: '{}'", rootArtifact);

    // add remote repository urls
    RepositorySystem system = AetherResolver.newRepositorySystem();
    RepositorySystemSession session = AetherResolver.newRepositorySystemSession(system,
            AetherResolver.LOCAL_REPO_PATH);
    Map<String, String> repositoriesDefs = map();
    for (BundleDef b : bundleDefs) {
        b.validate(b.getId());/* w  w w.ja v  a 2 s . co m*/
        for (Entry<String, String> id_url : b.getRepositories().entrySet()) {
            repositoriesDefs.put(id_url.getKey(), id_url.getValue());
        }
    }
    List<RemoteRepository> repos = AetherResolver.newRepositories(system, session, repositoriesDefs);

    // solve dependencies
    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(new Dependency(rootArtifact, ""));
    collectRequest
            .setRepositories(AetherResolver.newRepositories(system, session, new HashMap<String, String>()));
    CollectResult collectResult = system.collectDependencies(session, collectRequest);
    collectResult.getRoot().accept(new AetherResolver.ConsoleDependencyGraphDumper());
    PreorderNodeListGenerator p = new PreorderNodeListGenerator();
    collectResult.getRoot().accept(p);

    // now do the real fetching, and add jars to classpath
    List<Artifact> resolvedArtifacts = list();
    for (Dependency dependency : p.getDependencies(true)) {
        Artifact resolvedArtifact = system
                .resolveArtifact(session, new ArtifactRequest(dependency.getArtifact(), repos, ""))
                .getArtifact();
        resolvedArtifacts.add(resolvedArtifact);
        File jar = resolvedArtifact.getFile();

        // add this jar to the classpath
        ClassPathHack.addFile(jar);
        LOG.trace("* resolved artifact '{}', added to classpath: '{}'", resolvedArtifact,
                jar.getAbsolutePath());
    }

    BundleDef createdBundle = new BundleDef();
    createdBundle.setVersion("TODO!");
    createdBundle.setName("TODO!");
    for (BundleDef bundleDef : bundleDefs) {
        for (BundleDependency dep : bundleDef.getDependencies()) {
            createdBundle.addDependency(dep);
        }
    }

    for (Artifact a : resolvedArtifacts) {

        // only consider artifacts that were included in the initial bundle
        boolean found = false;
        for (BundleDef bundleDef : bundleDefs) {
            for (BundleDependency dep : bundleDef.getDependencies()) {
                if (a.getArtifactId().equals(dep.getArtifactId())) {
                    found = true;
                    break;
                }
            }
        }

        if (found) {

            JarInputStream is = new JarInputStream(new FileInputStream(a.getFile()));
            JarEntry entry;
            while ((entry = is.getNextJarEntry()) != null) {
                if (entry.getName().endsWith(".class")) {

                    try {
                        Class<?> clazz = Class.forName(entry.getName().replace('/', '.').replace(".class", ""));

                        // scan for all uimafit AnnotationEngines
                        if (JCasAnnotator_ImplBase.class.isAssignableFrom(clazz)) {
                            LOG.debug("AnnotationEngine: {}", clazz.getSimpleName());

                            final EngineDef engine = new EngineDef().setClassz(clazz.getName())
                                    .setName(clazz.getSimpleName()).setBundle(createdBundle);
                            createdBundle.addEngine(engine);
                            LOG.debug("{}", engine);

                            ReflectionUtils.doWithFields(clazz, new FieldCallback() {
                                public void doWith(final Field f)
                                        throws IllegalArgumentException, IllegalAccessException {

                                    ConfigurationParameter c = f.getAnnotation(ConfigurationParameter.class);
                                    if (c != null) {
                                        LOG.debug("* param: {} {} {} {}", new Object[] { c.name(),
                                                c.defaultValue(), c.mandatory(), f.getType() });

                                        String deflt = c.mandatory() ? "TODO" : "IS OPTIONAL";

                                        String value = c.defaultValue()[0]
                                                .equals(ConfigurationParameter.NO_DEFAULT_VALUE) ? deflt
                                                        : c.defaultValue()[0].toString();
                                        engine.addParameter(c.name(), list(value));
                                    }
                                }
                            });
                        }
                    } catch (Throwable e) {
                        System.err.println("something wrong with class " + entry.getName() + " " + e);
                    }
                }
            }
            is.close();
        }
    }

    // delete fake pom
    deleteDirectory(new File(LOCAL_REPO_PATH + "/org/sherlok/BundleCreator"));

    System.out.println(FileBased.writeAsString(createdBundle));
}

From source file:net.dataforte.commons.resources.ClassUtils.java

/**
 * Returns all classes within the specified package. Supports filesystem, JARs and JBoss VFS
 * /*from   w w  w  .ja v a  2 s.  co m*/
 * @param folder
 * @return
 * @throws IOException
 */
public static Class<?>[] getClassesForPackage(String pckgname) throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname.
    // There may be more than one if a package is split over multiple
    // jars/paths
    List<Class<?>> classes = new ArrayList<Class<?>>();
    ArrayList<File> directories = new ArrayList<File>();
    try {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new ClassNotFoundException("Can't get class loader.");
        }
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(pckgname.replace('.', '/'));
        while (resources.hasMoreElements()) {
            URL res = resources.nextElement();
            if (res.getProtocol().equalsIgnoreCase("jar")) {
                JarURLConnection conn = (JarURLConnection) res.openConnection();
                JarFile jar = conn.getJarFile();
                for (JarEntry e : Collections.list(jar.entries())) {

                    if (e.getName().startsWith(pckgname.replace('.', '/')) && e.getName().endsWith(".class")
                            && !e.getName().contains("$")) {
                        String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6);
                        classes.add(Class.forName(className, true, cld));
                    }
                }
            } else if (res.getProtocol().equalsIgnoreCase("vfszip")) { // JBoss 5+
                try {
                    Object content = res.getContent();
                    Method getChildren = content.getClass().getMethod("getChildren");
                    List<?> files = (List<?>) getChildren.invoke(res.getContent());
                    Method getPathName = null;
                    for (Object o : files) {
                        if (getPathName == null) {
                            getPathName = o.getClass().getMethod("getPathName");
                        }
                        String pathName = (String) getPathName.invoke(o);
                        if (pathName.endsWith(".class")) {
                            String className = pathName.replace("/", ".").substring(0, pathName.length() - 6);
                            classes.add(Class.forName(className, true, cld));
                        }
                    }
                } catch (Exception e) {
                    throw new IOException("Error while scanning " + res.toString(), e);
                }
            } else {
                directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            }
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Null pointer exception)", x);
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Unsupported encoding)", encex);
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for " + pckgname, ioex);
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (String file : files) {
                // we are only interested in .class files
                if (file.endsWith(".class")) {
                    // removes the .class extension
                    classes.add(Class.forName(pckgname + '.' + file.substring(0, file.length() - 6)));
                }
            }
        } else {
            throw new ClassNotFoundException(
                    pckgname + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    Class<?>[] classesA = new Class[classes.size()];
    classes.toArray(classesA);
    return classesA;
}

From source file:com.catalyst.sonar.score.batch.util.FileInstaller.java

/**
 * Copies a directory from a {@link JarURLConnection} to a destination
 * Directory outside the jar.//from  www  .  j a v a 2 s.  co m
 * 
 * @param destDir
 * @param jarConnection
 * @return true if copy is successful, false otherwise.
 * @throws IOException
 */
public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection)
        throws IOException {
    logger.debug("copyJarResourcesRecursively()");
    boolean success = true;
    final JarFile jarFile = jarConnection.getJarFile();

    for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
        final JarEntry entry = e.nextElement();
        if (entry.getName().startsWith(jarConnection.getEntryName())) {
            final String filename = StringUtils.removeStart(entry.getName(), //
                    jarConnection.getEntryName());

            final File f = new File(destDir, filename);
            if (!entry.isDirectory()) {
                final InputStream entryInputStream = jarFile.getInputStream(entry);
                if (!FileInstaller.copyStream(entryInputStream, f)) {
                    success = false;
                    logger.debug("returning " + success);
                    return success;
                }
                entryInputStream.close();
            } else {
                if (!FileInstaller.ensureDirectoryExists(f)) {
                    logger.debug("throwing an IOException");
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    logger.debug("returning " + success);
    return success;
}

From source file:info.magnolia.cms.util.ClasspathResourcesUtil.java

/**
 * Load resources from jars or directories
 *
 * @param resources found resources will be added to this collection
 * @param jarOrDir  a File, can be a jar or a directory
 * @param filter    used to filter resources
 *//*from   ww w  . ja  v a 2  s . c  o  m*/
private static void collectFiles(Collection resources, File jarOrDir, Filter filter) {

    if (!jarOrDir.exists()) {
        log.warn("missing file: {}", jarOrDir.getAbsolutePath());
        return;
    }

    if (jarOrDir.isDirectory()) {
        if (log.isDebugEnabled())
            log.debug("looking in dir {}", jarOrDir.getAbsolutePath());

        Collection files = FileUtils.listFiles(jarOrDir, new TrueFileFilter() {
        }, new TrueFileFilter() {
        });
        for (Iterator iter = files.iterator(); iter.hasNext();) {
            File file = (File) iter.next();
            String name = StringUtils.substringAfter(file.getPath(), jarOrDir.getPath());

            // please, be kind to Windows!!!
            name = StringUtils.replace(name, "\\", "/");
            if (!name.startsWith("/")) {
                name = "/" + name;
            }

            if (filter.accept(name)) {
                resources.add(name);
            }
        }
    } else if (jarOrDir.getName().endsWith(".jar")) {
        if (log.isDebugEnabled())
            log.debug("looking in jar {}", jarOrDir.getAbsolutePath());
        JarFile jar;
        try {
            jar = new JarFile(jarOrDir);
        } catch (IOException e) {
            log.error("IOException opening file {}, skipping", jarOrDir.getAbsolutePath());
            return;
        }
        for (Enumeration em = jar.entries(); em.hasMoreElements();) {
            JarEntry entry = (JarEntry) em.nextElement();
            if (!entry.isDirectory()) {
                if (filter.accept("/" + entry.getName())) {
                    resources.add("/" + entry.getName());
                }
            }
        }
    } else {
        if (log.isDebugEnabled())
            log.debug("Unknown (not jar) file in classpath: {}, skipping.", jarOrDir.getName());
    }

}

From source file:ezbake.deployer.utilities.VersionHelper.java

private static String getVersionFromPomProperties(File artifact) throws IOException {
    List<JarEntry> pomPropertiesFiles = new ArrayList<>();
    String versionNumber = null;//from  ww w .  jav a2  s  .  co  m
    try (JarFile jar = new JarFile(artifact)) {
        JarEntry entry;
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            entry = entries.nextElement();
            if (!entry.isDirectory() && entry.getName().endsWith("pom.properties")) {
                pomPropertiesFiles.add(entry);
            }
        }

        if (pomPropertiesFiles.size() == 1) {
            Properties pomProperties = new Properties();
            pomProperties.load(jar.getInputStream(pomPropertiesFiles.get(0)));
            versionNumber = pomProperties.getProperty("version", null);
        } else {
            logger.debug("Found {} pom.properties files. Cannot use that for version",
                    pomPropertiesFiles.size());
        }
    }
    return versionNumber;
}