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:org.owasp.dependencycheck.analyzer.JarAnalyzer.java

/**
 * Cycles through an enumeration of JarEntries, contained within the
 * dependency, and returns a list of the class names. This does not include
 * core Java package names (i.e. java.* or javax.*).
 *
 * @param dependency the dependency being analyzed
 * @return an list of fully qualified class names
 *//* w  w w. ja v a  2  s  .c o m*/
private List<ClassNameInformation> collectClassNames(Dependency dependency) {
    final List<ClassNameInformation> classNames = new ArrayList<ClassNameInformation>();
    JarFile jar = null;
    try {
        jar = new JarFile(dependency.getActualFilePath());
        final Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            final String name = entry.getName().toLowerCase();
            //no longer stripping "|com\\.sun" - there are some com.sun jar files with CVEs.
            if (name.endsWith(".class") && !name.matches("^javax?\\..*$")) {
                final ClassNameInformation className = new ClassNameInformation(
                        name.substring(0, name.length() - 6));
                classNames.add(className);
            }
        }
    } catch (IOException ex) {
        LOGGER.warn("Unable to open jar file '{}'.", dependency.getFileName());
        LOGGER.debug("", ex);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ex) {
                LOGGER.trace("", ex);
            }
        }
    }
    return classNames;
}

From source file:com.rapidminer.tools.Tools.java

public static void findImplementationsInJar(ClassLoader loader, JarFile jar, Class<?> superClass,
        List<String> implementations) {
    Enumeration<JarEntry> e = jar.entries();
    while (e.hasMoreElements()) {
        JarEntry entry = e.nextElement();
        String name = entry.getName();
        int dotClass = name.lastIndexOf(".class");
        if (dotClass < 0) {
            continue;
        }//from ww w. j ava2 s.c  om
        name = name.substring(0, dotClass);
        name = name.replaceAll("/", "\\.");
        try {
            Class<?> c = loader.loadClass(name);
            if (superClass.isAssignableFrom(c)) {
                if (!java.lang.reflect.Modifier.isAbstract(c.getModifiers())) {
                    implementations.add(name);
                }
            }
        } catch (Throwable t) {
        }
    }
}

From source file:org.jsweet.transpiler.candies.CandiesProcessor.java

private void extractCandy( //
        CandyDescriptor descriptor, //
        JarFile jarFile, //
        File javaOutputDirectory, //
        File tsDefOutputDirectory, //
        File jsOutputDirectory, //
        Predicate<String> isTsDefToBeExtracted) {
    logger.info("extract candy: " + jarFile.getName() + " javaOutputDirectory=" + javaOutputDirectory
            + " tsDefOutputDirectory=" + tsDefOutputDirectory + " jsOutputDir=" + jsOutputDirectory);

    jarFile.stream().filter(entry -> entry.getName().endsWith(".d.ts")
            && (entry.getName().startsWith("src/") || entry.getName().startsWith("META-INF/resources/"))) //
            .forEach(entry -> {// w  w  w  . j  av  a2 s.  c  o  m

                File out;
                if (entry.getName().endsWith(".java")) {
                    // RP: this looks like dead code...
                    out = new File(javaOutputDirectory + "/" + entry.getName().substring(4));
                } else if (entry.getName().endsWith(".d.ts")) {
                    if (isTsDefToBeExtracted != null && !isTsDefToBeExtracted.test(entry.getName())) {
                        return;
                    }
                    out = new File(tsDefOutputDirectory + "/" + entry.getName());
                } else {
                    out = null;
                }
                extractEntry(jarFile, entry, out);
            });

    for (String jsFilePath : descriptor.jsFilesPaths) {
        JarEntry entry = jarFile.getJarEntry(jsFilePath);
        String relativeJsPath = jsFilePath.substring(descriptor.jsDirPath.length());

        File out = new File(jsOutputDirectory, relativeJsPath);
        extractEntry(jarFile, entry, out);
    }
}

From source file:org.artifactory.repo.db.DbStoringRepoMixin.java

private void validateArtifactIfRequired(MutableVfsFile mutableFile, RepoPath repoPath)
        throws RepoRejectException {
    String pathId = repoPath.getId();
    InputStream jarStream = mutableFile.getStream();
    try {/*  w  ww  . j a v a  2s  .  co m*/
        log.info("Validating the content of '{}'.", pathId);
        JarInputStream jarInputStream = new JarInputStream(jarStream, true);
        JarEntry entry = jarInputStream.getNextJarEntry();

        if (entry == null) {
            if (jarInputStream.getManifest() != null) {
                log.trace("Found manifest validating the content of '{}'.", pathId);
                return;
            }
            throw new IllegalStateException("Could not find entries within the archive.");
        }
        do {
            log.trace("Found the entry '{}' validating the content of '{}'.", entry.getName(), pathId);
        } while ((jarInputStream.available() == 1) && (entry = jarInputStream.getNextJarEntry()) != null);

        log.info("Finished validating the content of '{}'.", pathId);
    } catch (Exception e) {
        String message = String.format("Failed to validate the content of '%s': %s", pathId, e.getMessage());
        if (log.isDebugEnabled()) {
            log.debug(message, e);
        } else {
            log.error(message);
        }
        throw new RepoRejectException(message, HttpStatus.SC_CONFLICT);
    } finally {
        IOUtils.closeQuietly(jarStream);
    }
}

From source file:org.kitodo.serviceloader.KitodoServiceLoader.java

/**
 * Loads bean classes and registers them to the FacesContext. Afterwards
 * they can be used in all frontend files
 *//*from  w ww  . j a va 2  s .c  om*/
private void loadBeans() {
    Path moduleFolder = FileSystems.getDefault().getPath(modulePath);
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, JAR)) {

        for (Path f : stream) {
            try (JarFile jarFile = new JarFile(f.toString())) {

                if (hasFrontendFiles(jarFile)) {

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

                    URL[] urls = { new URL("jar:file:" + f.toString() + "!/") };
                    try (URLClassLoader cl = URLClassLoader.newInstance(urls)) {
                        while (e.hasMoreElements()) {
                            JarEntry je = e.nextElement();

                            /*
                             * IMPORTANT: Naming convention: the name of the
                             * java class has to be in upper camel case or
                             * "pascal case" and must be equal to the file
                             * name of the corresponding facelet file
                             * concatenated with the word "Form".
                             *
                             * Example: template filename "sample.xhtml" =>
                             * "SampleForm.java"
                             *
                             * That is the reason for the following check
                             * (e.g. whether the JarEntry name ends with
                             * "Form.class")
                             */
                            if (je.isDirectory() || !je.getName().endsWith("Form.class")) {
                                continue;
                            }

                            String className = je.getName().substring(0, je.getName().length() - 6);
                            className = className.replace('/', '.');
                            Class c = cl.loadClass(className);

                            String beanName = className.substring(className.lastIndexOf('.') + 1).trim();

                            FacesContext facesContext = FacesContext.getCurrentInstance();
                            HttpSession session = (HttpSession) facesContext.getExternalContext()
                                    .getSession(false);

                            session.getServletContext().setAttribute(beanName, c.newInstance());
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error(ERROR, e.getMessage());
    }
}

From source file:org.jahia.utils.maven.plugin.osgi.DependenciesMojo.java

protected int processJarInputStream(String jarFilePath, boolean externalDependency, String packageDirectory,
        String version, boolean optional, ParsingContext parsingContext, String logPrefix, int scanned,
        JarInputStream jarInputStream) throws IOException {
    JarEntry jarEntry;
    while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
        if (jarEntry.isDirectory()) {
            continue;
        }/*  ww w  .  j  a  v  a2s  . com*/
        String entryName = jarEntry.getName();

        if (entryName.startsWith(packageDirectory)) {
            String packageName = entryName.substring(packageDirectory.length());
            if (!packageName.contains("/.")) {
                processLocalPackageEntry(packageName, "/", jarFilePath, version, optional, parsingContext);
            }
        }

        if (excludeJarEntry(entryName)) {
            continue;
        }
        ByteArrayOutputStream entryOutputStream = new ByteArrayOutputStream();
        IOUtils.copy(jarInputStream, entryOutputStream);
        if (Parsers.getInstance().canParseForPhase(0, jarEntry.getName())) {
            getLog().debug(logPrefix + "  scanning JAR entry: " + jarEntry.getName());
            Parsers.getInstance().parse(0, jarEntry.getName(),
                    new ByteArrayInputStream(entryOutputStream.toByteArray()), jarFilePath, externalDependency,
                    optional, version, getLogger(), parsingContext);
            scanned++;
        }
        if (Parsers.getInstance().canParseForPhase(1, jarEntry.getName())) {
            getLog().debug(logPrefix + "  scanning JAR entry: " + jarEntry.getName());
            if (processNonTldFile(jarEntry.getName(), new ByteArrayInputStream(entryOutputStream.toByteArray()),
                    jarFilePath, optional, version, parsingContext)) {
                scanned++;
            }
        }
    }
    return scanned;
}

From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Adds an entry to the output jar, and write its content from the {@link InputStream}
 *
 * @param input The input stream from where to write the entry content.
 * @param entry the entry to write in the jar.
 * @throws IOException/*from  w  w w.  j a v a 2 s  .c o m*/
 */
private void writeEntry(InputStream input, JarEntry entry) throws IOException {
    // add the entry to the jar archive
    mOutputJar.putNextEntry(entry);

    // read the content of the entry from the input stream, and write it into the archive.
    int count;
    while ((count = input.read(mBuffer)) != -1) {
        mOutputJar.write(mBuffer, 0, count);

        // update the digest
        if (mMessageDigest != null) {
            mMessageDigest.update(mBuffer, 0, count);
        }
    }

    // close the entry for this file
    mOutputJar.closeEntry();

    if (mManifest != null) {
        // update the manifest for this entry.
        Attributes attr = mManifest.getAttributes(entry.getName());
        if (attr == null) {
            attr = new Attributes();
            mManifest.getEntries().put(entry.getName(), attr);
        }
        attr.putValue(DIGEST_ATTR, new String(Base64.encode(mMessageDigest.digest()), "ASCII"));
    }
}

From source file:org.kepler.kar.KARFile.java

/**
 * Constructor for creating a KARFile from an existing file.
 * //from ww w  . j a v a  2  s .co  m
 * @param f
 *            the file to create the KAR from
 * @throws IOException
 */
public KARFile(File f) throws IOException {
    super(f);
    if (isDebugging)
        log.debug("KARFile(" + f + ")");

    _fileOnDisk = f;

    initializeSupportedVersions();

    if (getManifest() == null) {
        throw new IOException("This KAR file does not contain a Manifest.");
    }

    String lsidStr = getManifest().getMainAttributes().getValue(LSID);
    if (isDebugging)
        log.debug(lsidStr);
    if (lsidStr == null) {
        throw new IOException("The KAR file does not contain an lsid attribute in the manifest");
    }
    if (!KeplerLSID.isKeplerLSIDFormat(lsidStr)) {
        throw new IOException("The LSID of the KAR file is not properly formatted.");
    }

    String version = getManifest().getMainAttributes().getValue(KAR_VERSION);
    if (version == null) {
        throw new IOException("The KAR file does not contain a KAR-Version attribute in the manifest.");
    }
    if (!_supportedVersions.contains(version)) {
        throw new IOException(version + " is not a supported KAR version.\n" + getSupportedVersionString());
    }

    Enumeration<JarEntry> karFileEnum = entries();
    while (karFileEnum.hasMoreElements()) {
        JarEntry entry = (JarEntry) karFileEnum.nextElement();
        KeplerLSID lsid = getEntryLSID(entry);
        String type = getEntryType(entry);
        if (lsid != null && type != null) {
            _lsidNames.put(lsid, entry.getName());
            _lsidTypes.put(lsid, type);
        }
    }

}

From source file:org.springfield.lou.application.ApplicationManager.java

private void processRemoteWar(File warfile, String wantedname, String datestring) {
    // lets first check some vitals to check what it is
    String warfilename = warfile.getName();
    if (warfilename.startsWith("smt_") && warfilename.endsWith("app.war")) {
        // ok so filename checks out is smt_[name]app.war format
        String appname = warfilename.substring(4, warfilename.length() - 7);
        if (wantedname.equals(appname)) {
            // ok found file is the wanted file
            // format "29-Aug-2013-16:55"
            System.out.println("NEW VERSION OF " + appname + " FOUND INSTALLING");

            String writedir = "/springfield/lou/apps/" + appname + "/" + datestring;

            // make all the dirs we need
            File md = new File(writedir);
            md.mkdirs();/*from w w w . j  av a 2 s. c  o  m*/
            md = new File(writedir + "/war");
            md.mkdirs();
            md = new File(writedir + "/jar");
            md.mkdirs();
            md = new File(writedir + "/components");
            md.mkdirs();
            md = new File(writedir + "/css");
            md.mkdirs();
            md = new File(writedir + "/libs");
            md.mkdirs();

            try {
                JarFile war = new JarFile(warfile);

                // ok lets first find the jar file !
                JarEntry entry = war.getJarEntry("WEB-INF/lib/smt_" + appname + "app.jar");
                if (entry != null) {
                    byte[] bytes = readJarEntryToBytes(war.getInputStream(entry));
                    writeBytesToFile(bytes, writedir + "/jar/smt_" + appname + "app.jar");
                }
                // unpack all in eddie dir
                Enumeration<JarEntry> iter = war.entries();
                while (iter.hasMoreElements()) {
                    JarEntry lentry = iter.nextElement();
                    //System.out.println("LI="+lentry.getName());
                    String lname = lentry.getName();
                    if (!lname.endsWith("/")) {
                        int pos = lname.indexOf("/" + appname + "/");
                        if (pos != -1) {
                            String nname = lname.substring(pos + appname.length() + 2);
                            String dname = nname.substring(0, nname.lastIndexOf('/'));
                            File de = new File(writedir + "/" + dname);
                            de.mkdirs();
                            byte[] bytes = readJarEntryToBytes(war.getInputStream(lentry));
                            writeBytesToFile(bytes, writedir + "/" + nname);
                        }
                    }
                }
                war.close();
                File ren = new File("/springfield/lou/uploaddir/" + warfilename);
                File nen = new File(writedir + "/war/smt_" + appname + "app.war");
                ren.renameTo(nen);

                // lets tell set the available variable to tell the others we have it.

                FsNode unode = Fs
                        .getNode("/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring);
                if (unode != null) {
                    String warlist = unode.getProperty("waravailableat");
                    if (warlist == null || warlist.equals("")) {
                        Fs.setProperty(
                                "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring,
                                "waravailableat", LazyHomer.myip);
                    } else {
                        Fs.setProperty(
                                "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring,
                                "waravailableat", warlist + "," + LazyHomer.myip);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}