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:com.flexive.shared.FxDropApplication.java

/**
 * Load text resources packaged with the drop.
 *
 * @param pathPrefix    a path prefix (e.g. "scripts/")
 * @return              a map of filename (relative to the drop application package) -> file contents
 * @throws java.io.IOException  on I/O errors
 * @since 3.1/*ww  w. j a  v a2 s .co m*/
 */
public Map<String, String> loadTextResources(String pathPrefix) throws IOException {
    if (pathPrefix == null) {
        pathPrefix = "";
    } else if (pathPrefix.startsWith("/")) {
        pathPrefix = pathPrefix.substring(1);
    }
    if (isJarProtocol) {
        // read directly from jar file

        final Map<String, String> result = Maps.newHashMap();
        final JarInputStream stream = getJarStream();
        try {
            JarEntry entry;
            while ((entry = stream.getNextJarEntry()) != null) {

                if (!entry.isDirectory() && entry.getName().startsWith(pathPrefix)) {
                    try {
                        result.put(entry.getName(), FxSharedUtils.readFromJarEntry(stream, entry));
                    } catch (Exception e) {
                        if (LOG.isTraceEnabled()) {
                            LOG.trace(
                                    "Failed to read text JAR entry " + entry.getName() + ": " + e.getMessage(),
                                    e);
                        }
                        // ignore, continue reading
                    }

                }
            }
            return result;
        } finally {
            FxSharedUtils.close(stream);
        }
    } else {
        // read from filesystem

        final List<File> files = FxFileUtils.listRecursive(new File(resourceURL + File.separator + pathPrefix));
        final Map<String, String> result = Maps.newHashMapWithExpectedSize(files.size());
        for (File file : files) {
            try {
                result.put(StringUtils.replace(file.getPath(), resourceURL + File.separator, ""),
                        FxSharedUtils.loadFile(file));
            } catch (Exception e) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Failed to read text file " + file.getPath() + ": " + e.getMessage(), e);
                }
            }
        }
        return result;
    }
}

From source file:org.echocat.nodoodle.transport.HandlerUnpacker.java

protected SplitResult splitMultipleJarIntoJars(InputStream inputStream, File targetDirectory)
        throws IOException {
    if (inputStream == null) {
        throw new NullPointerException();
    }/* w ww  . j av a 2s  .  co  m*/
    if (targetDirectory == null) {
        throw new NullPointerException();
    }
    final Collection<File> jarFiles = new ArrayList<File>();
    final File mainJarFile = getMainJarFile(targetDirectory);
    jarFiles.add(mainJarFile);
    final JarInputStream jarInput = new JarInputStream(inputStream);
    final Manifest manifest = jarInput.getManifest();
    final FileOutputStream mainJarFileStream = new FileOutputStream(mainJarFile);
    try {
        final JarOutputStream jarOutput = new JarOutputStream(mainJarFileStream, manifest);
        try {
            JarEntry entry = jarInput.getNextJarEntry();
            while (entry != null) {
                final String entryName = entry.getName();
                if (!entry.isDirectory() && entryName.startsWith("lib/")) {
                    final File targetFile = new File(targetDirectory, entryName);
                    if (!targetFile.getParentFile().mkdirs()) {
                        throw new IOException("Could not create parent directory of " + targetFile + ".");
                    }
                    final OutputStream outputStream = new FileOutputStream(targetFile);
                    try {
                        IOUtils.copy(jarInput, outputStream);
                    } finally {
                        IOUtils.closeQuietly(outputStream);
                    }
                    jarFiles.add(targetFile);
                } else {
                    if (entryName.startsWith(TransportConstants.CLASSES_PREFIX)
                            && entryName.length() > TransportConstants.CLASSES_PREFIX.length()) {
                        try {
                            ZIP_ENTRY_NAME_FIELD.set(entry, entryName.substring(CLASSES_PREFIX.length()));
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException("Could not set " + ZIP_ENTRY_NAME_FIELD + ".", e);
                        }
                    }
                    jarOutput.putNextEntry(entry);
                    IOUtils.copy(jarInput, jarOutput);
                    jarOutput.closeEntry();
                }
                entry = jarInput.getNextJarEntry();
            }
        } finally {
            IOUtils.closeQuietly(jarOutput);
        }
    } finally {
        IOUtils.closeQuietly(mainJarFileStream);
    }
    return new SplitResult(Collections.unmodifiableCollection(jarFiles), manifest);
}

From source file:org.dbmaintain.script.repository.impl.ArchiveScriptLocation.java

protected SortedSet<Script> loadScriptsFromJar(final JarFile jarFile, String subPath) {
    SortedSet<Script> scripts = new TreeSet<Script>();
    for (Enumeration<JarEntry> jarEntries = jarFile.entries(); jarEntries.hasMoreElements();) {
        final JarEntry jarEntry = jarEntries.nextElement();
        String fileName = jarEntry.getName();
        if (LOCATION_PROPERTIES_FILENAME.equals(fileName) || !isScriptFileName(fileName)) {
            continue;
        }//from  w  ww. j ava  2 s .  com

        String relativeScriptName = jarEntry.getName();
        if (subPath != null) {
            if (!fileName.startsWith(subPath)) {
                continue;
            }
            relativeScriptName = relativeScriptName.substring(subPath.length());
        }
        ScriptContentHandle scriptContentHandle = new ScriptContentHandle(scriptEncoding,
                ignoreCarriageReturnsWhenCalculatingCheckSum) {
            @Override
            protected InputStream getScriptInputStream() {
                try {
                    return jarFile.getInputStream(jarEntry);
                } catch (IOException e) {
                    throw new DbMaintainException("Error while reading jar entry " + jarEntry, e);
                }
            }
        };
        Long fileLastModifiedAt = jarEntry.getTime();
        Script script = scriptFactory.createScriptWithContent(relativeScriptName, fileLastModifiedAt,
                scriptContentHandle);
        scripts.add(script);
    }
    return scripts;
}

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 ww  w  .j av  a  2s.co  m
    }
}

From source file:io.squark.nestedjarclassloader.Module.java

private void addResource0(URL url) throws IOException {
    if (url.getPath().endsWith(".jar")) {
        if (logger != null)
            logger.debug("Adding jar " + url.getPath());
        InputStream urlStream = url.openStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(urlStream);
        JarInputStream jarInputStream = new JarInputStream(bufferedInputStream);
        JarEntry jarEntry;

        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
            if (resources.containsKey(jarEntry.getName())) {
                if (logger != null)
                    logger.trace("Already have resource " + jarEntry.getName()
                            + ". If different versions, unexpected behaviour " + "might occur. Available in "
                            + resources.get(jarEntry.getName()));
            }//www .j  a v a  2 s .c  om

            String spec;
            if (url.getProtocol().equals("jar")) {
                spec = url.getPath();
            } else {
                spec = url.getProtocol() + ":" + url.getPath();
            }
            URL contentUrl = new URL(null, "jar:" + spec + "!/" + jarEntry.getName(),
                    new NestedJarURLStreamHandler(false));
            resources.put(jarEntry.getName(), contentUrl);
            addClassIfClass(jarInputStream, jarEntry.getName());
            if (logger != null)
                logger.trace("Added resource " + jarEntry.getName() + " to ClassLoader");
            if (jarEntry.getName().endsWith(".jar")) {
                addResource0(contentUrl);
            }
        }
        jarInputStream.close();
        bufferedInputStream.close();
        urlStream.close();
    } else if (url.getPath().endsWith(".class")) {
        throw new IllegalStateException("Cannot add classes directly");
    } else {
        try {
            addDirectory(new File(url.toURI()));
        } catch (URISyntaxException e) {
            throw new IllegalStateException(e);
        }
    }
}

From source file:org.springframework.boot.gradle.tasks.bundling.AbstractBootArchiveTests.java

@Test
public void reproducibleOrderingCanBeEnabled() throws IOException {
    this.task.setMainClassName("com.example.Main");
    this.task.from(this.temp.newFile("bravo.txt"), this.temp.newFile("alpha.txt"),
            this.temp.newFile("charlie.txt"));
    this.task.setReproducibleFileOrder(true);
    this.task.execute();
    assertThat(this.task.getArchivePath()).exists();
    List<String> textFiles = new ArrayList<>();
    try (JarFile jarFile = new JarFile(this.task.getArchivePath())) {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().endsWith(".txt")) {
                textFiles.add(entry.getName());
            }//from   w w w  .ja  v a  2s . co m
        }
    }
    assertThat(textFiles).containsExactly("alpha.txt", "bravo.txt", "charlie.txt");
}

From source file:JarEntryOutputStream.java

/**
 * Returns a list of entries that are// www.  j  a  va 2 s .c o  m
 * immediately below the entry named by entryName in the jar's directory
 * structure.
 *
 * @param entryName the name of the directory entry name
 * @return List a list of java.util.jar.JarEntry objects that are
 * immediately below the entry named by entryName in the jar's directory
 * structure.
 */
public List listSubEntries(String entryName) {
    Enumeration entries = jar.entries();
    List subEntries = new ArrayList();

    while (entries.hasMoreElements()) {
        JarEntry nextEntry = (JarEntry) entries.nextElement();

        if (nextEntry.getName().startsWith(entryName)) {
            // the next entry name starts with the entryName so it
            // is a potential sub entry

            // tokenize the rest of the next entry name to see how
            // many tokens exist
            StringTokenizer tokenizer = new StringTokenizer(nextEntry.getName().substring(entryName.length()),
                    EnhancedJarFile.JAR_DELIMETER);

            if (tokenizer.countTokens() == 1) {
                // only 1 token exists, so it is a sub-entry
                subEntries.add(nextEntry);
            }
        }
    }

    return subEntries;
}

From source file:com.eucalyptus.simpleworkflow.common.client.WorkflowClientStandalone.java

private void handleClassFile(final File f, final JarEntry j) throws IOException, RuntimeException {
    final String classGuess = j.getName().replaceAll("/", ".").replaceAll("\\.class.{0,1}", "");
    try {/*from   w w w  .  ja  v  a 2s. c  o  m*/
        final Class candidate = ClassLoader.getSystemClassLoader().loadClass(classGuess);
        final Ats ats = Ats.inClassHierarchy(candidate);
        if ((this.allowedClassNames.isEmpty() || this.allowedClassNames.contains(candidate.getName())
                || this.allowedClassNames.contains(candidate.getCanonicalName())
                || this.allowedClassNames.contains(candidate.getSimpleName()))
                && (ats.has(Workflow.class) || ats.has(Activities.class))
                && !Modifier.isAbstract(candidate.getModifiers())
                && !Modifier.isInterface(candidate.getModifiers()) && !candidate.isLocalClass()
                && !candidate.isAnonymousClass()) {
            if (ats.has(Workflow.class)) {
                this.workflowClasses.add(candidate);
                LOG.debug("Discovered workflow implementation class: " + candidate.getName());
            } else {
                this.activityClasses.add(candidate);
                LOG.debug("Discovered activity implementation class: " + candidate.getName());
            }
        }
    } catch (final ClassNotFoundException e) {
        LOG.debug(e, e);
    }
}

From source file:net.ymate.platform.core.beans.impl.DefaultBeanLoader.java

private List<Class<?>> __doFindClassByJar(String packageName, JarFile jarFile, IBeanFilter filter)
        throws Exception {
    List<Class<?>> _returnValue = new ArrayList<Class<?>>();
    if (!__doCheckExculedFile(new File(jarFile.getName()).getName())) {
        Enumeration<JarEntry> _entriesEnum = jarFile.entries();
        for (; _entriesEnum.hasMoreElements();) {
            JarEntry _entry = _entriesEnum.nextElement();
            // ??? '/'  '.'?.class???'$'??
            String _className = _entry.getName().replaceAll("/", ".");
            if (_className.endsWith(".class") && _className.indexOf('$') < 0) {
                if (_className.startsWith(packageName)) {
                    _className = _className.substring(0, _className.lastIndexOf('.'));
                    Class<?> _class = __doLoadClass(_className);
                    __doAddClass(_returnValue, _class, filter);
                }/* ww w .j a  va  2 s . c om*/
            }
        }
    }
    return _returnValue;
}

From source file:org.apache.storm.localizer.LocallyCachedTopologyBlob.java

protected void extractDirFromJar(String jarpath, String dir, Path dest) throws IOException {
    LOG.debug("EXTRACTING {} from {} and placing it at {}", dir, jarpath, dest);
    try (JarFile jarFile = new JarFile(jarpath)) {
        String toRemove = dir + '/';
        Enumeration<JarEntry> jarEnums = jarFile.entries();
        while (jarEnums.hasMoreElements()) {
            JarEntry entry = jarEnums.nextElement();
            String name = entry.getName();
            if (!entry.isDirectory() && name.startsWith(toRemove)) {
                String shortenedName = name.replace(toRemove, "");
                Path aFile = dest.resolve(shortenedName);
                LOG.debug("EXTRACTING {} SHORTENED to {} into {}", name, shortenedName, aFile);
                fsOps.forceMkdir(aFile.getParent());
                try (FileOutputStream out = new FileOutputStream(aFile.toFile());
                        InputStream in = jarFile.getInputStream(entry)) {
                    IOUtils.copy(in, out);
                }/*from  w  ww  .  j a  v a 2 s .c  om*/
            }
        }
    }
}