Example usage for java.util.jar JarInputStream getNextJarEntry

List of usage examples for java.util.jar JarInputStream getNextJarEntry

Introduction

In this page you can find the example usage for java.util.jar JarInputStream getNextJarEntry.

Prototype

public JarEntry getNextJarEntry() throws IOException 

Source Link

Document

Reads the next JAR file entry and positions the stream at the beginning of the entry data.

Usage

From source file:com.ecyrd.jspwiki.ui.TemplateManager.java

/**
 * List all installed i18n language properties
 * //from  www  .jav a 2 s . c  om
 * @param pageContext
 * @return map of installed Languages (with help of Juan Pablo Santos Rodriguez)
 * @since 2.7.x
 */
public Map listLanguages(PageContext pageContext) {
    LinkedHashMap<String, String> resultMap = new LinkedHashMap<String, String>();

    String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString();
    JarInputStream jarStream = null;

    try {
        JarEntry entry;
        InputStream inputStream = pageContext.getServletContext().getResourceAsStream(I18NRESOURCE_PATH);
        jarStream = new JarInputStream(inputStream);

        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();

            if (!entry.isDirectory() && name.startsWith(I18NRESOURCE_PREFIX)
                    && name.endsWith(I18NRESOURCE_SUFFIX)) {
                name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX));

                Locale locale = new Locale(name.substring(0, 2),
                        ((name.indexOf("_") == -1) ? "" : name.substring(3, 5)));

                String defaultLanguage = "";

                if (clientLanguage.startsWith(name)) {
                    defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE);
                }

                resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage);
            }
        }
    } catch (IOException ioe) {
        if (log.isDebugEnabled())
            log.debug("Could not search jar file '" + I18NRESOURCE_PATH
                    + "'for properties files due to an IOException: \n" + ioe.getMessage());
    } finally {
        if (jarStream != null) {
            try {
                jarStream.close();
            } catch (IOException e) {
            }
        }
    }

    return resultMap;
}

From source file:cn.com.ebmp.freesql.io.ResolverUtil.java

/**
 * List the names of the entries in the given {@link JarInputStream} that
 * begin with the specified {@code path}. Entries will match with or
 * without a leading slash./*from   w  ww  .  ja va2 s  . com*/
 * 
 * @param jar
 *            The JAR input stream
 * @param path
 *            The leading path to match
 * @return The names of all the matching entries
 * @throws IOException
 */
protected List<String> listClassResources(JarInputStream jar, String path) throws IOException {
    // Include the leading and trailing slash when matching names
    if (!path.startsWith("/"))
        path = "/" + path;
    if (!path.endsWith("/"))
        path = path + "/";

    // Iterate over the entries and collect those that begin with the
    // requested path
    List<String> resources = new ArrayList<String>();
    for (JarEntry entry; (entry = jar.getNextJarEntry()) != null;) {
        if (!entry.isDirectory()) {
            // Add leading slash if it's missing
            String name = entry.getName();
            if (!name.startsWith("/"))
                name = "/" + name;

            // Check file name
            if (name.endsWith(".class") && name.startsWith(path)) {
                log.debug("Found class file: " + name);
                resources.add(name.substring(1)); // Trim leading slash
            }
        }
    }
    return resources;
}

From source file:com.amalto.core.jobox.watch.JoboxListener.java

public void contextChanged(String jobFile, String context) {
    File entity = new File(jobFile);
    String sourcePath = jobFile;//from   w  ww.j a va2s.  co m
    int dotMark = jobFile.lastIndexOf("."); //$NON-NLS-1$
    int separateMark = jobFile.lastIndexOf(File.separatorChar);
    if (dotMark != -1) {
        sourcePath = System.getProperty("java.io.tmpdir") + File.separatorChar //$NON-NLS-1$
                + jobFile.substring(separateMark, dotMark);
    }
    try {
        JoboxUtil.extract(jobFile, System.getProperty("java.io.tmpdir") + File.separatorChar); //$NON-NLS-1$
    } catch (Exception e1) {
        LOGGER.error("Extraction exception occurred.", e1);
        return;
    }
    List<File> resultList = new ArrayList<File>();
    JoboxUtil.findFirstFile(null, new File(sourcePath), "classpath.jar", resultList); //$NON-NLS-1$
    if (!resultList.isEmpty()) {
        JarInputStream jarIn = null;
        JarOutputStream jarOut = null;
        try {
            JarFile jarFile = new JarFile(resultList.get(0));
            Manifest mf = jarFile.getManifest();
            jarIn = new JarInputStream(new FileInputStream(resultList.get(0)));
            Manifest newManifest = jarIn.getManifest();
            if (newManifest == null) {
                newManifest = new Manifest();
            }
            newManifest.getMainAttributes().putAll(mf.getMainAttributes());
            newManifest.getMainAttributes().putValue("activeContext", context); //$NON-NLS-1$
            jarOut = new JarOutputStream(new FileOutputStream(resultList.get(0)), newManifest);
            byte[] buf = new byte[4096];
            JarEntry entry;
            while ((entry = jarIn.getNextJarEntry()) != null) {
                if ("META-INF/MANIFEST.MF".equals(entry.getName())) { //$NON-NLS-1$
                    continue;
                }
                jarOut.putNextEntry(entry);
                int read;
                while ((read = jarIn.read(buf)) != -1) {
                    jarOut.write(buf, 0, read);
                }
                jarOut.closeEntry();
            }
        } catch (Exception e) {
            LOGGER.error("Extraction exception occurred.", e);
        } finally {
            IOUtils.closeQuietly(jarIn);
            IOUtils.closeQuietly(jarOut);
        }
        // re-zip file
        if (entity.getName().endsWith(".zip")) { //$NON-NLS-1$
            File sourceFile = new File(sourcePath);
            try {
                JoboxUtil.zip(sourceFile, jobFile);
            } catch (Exception e) {
                LOGGER.error("Zip exception occurred.", e);
            }
        }
    }
}

From source file:spring.osgi.io.OsgiBundleResourcePatternResolver.java

/**
 * Checks the jar entries from the Bundle-Classpath for the given pattern.
 *
 * @param list    paths//w ww.j a  v a  2  s . c o  m
 * @param url     url
 * @param pattern pattern
 */
private void findBundleClassPathMatchingJarEntries(List<String> list, URL url, String pattern)
        throws IOException {
    // get the stream to the resource and read it as a jar
    JarInputStream jis = new JarInputStream(url.openStream());
    Set<String> result = new LinkedHashSet<>(8);

    boolean patternWithFolderSlash = pattern.startsWith(FOLDER_SEPARATOR);

    // parse the jar and do pattern matching
    try {
        while (jis.available() > 0) {
            JarEntry jarEntry = jis.getNextJarEntry();
            // if the jar has ended, the entry can be null (on Sun JDK at least)
            if (jarEntry != null) {
                String entryPath = jarEntry.getName();

                // check if leading "/" is needed or not (it depends how the jar was created)
                if (entryPath.startsWith(FOLDER_SEPARATOR)) {
                    if (!patternWithFolderSlash) {
                        entryPath = entryPath.substring(FOLDER_SEPARATOR.length());
                    }
                } else {
                    if (patternWithFolderSlash) {
                        entryPath = FOLDER_SEPARATOR.concat(entryPath);
                    }
                }
                if (getPathMatcher().match(pattern, entryPath)) {
                    result.add(entryPath);
                }
            }
        }
    } finally {
        try {
            jis.close();
        } catch (IOException io) {
            // ignore it - nothing we can't do about it
        }
    }

    if (logger.isTraceEnabled())
        logger.trace("Found in nested jar [" + url + "] matching entries " + result);

    list.addAll(result);
}

From source file:org.eclipse.gemini.blueprint.io.OsgiBundleResourcePatternResolver.java

/**
 * Checks the jar entries from the Bundle-Classpath for the given pattern.
 * /*  w  w  w. ja v a 2  s. co  m*/
 * @param list
 * @param ur
 */
private void findBundleClassPathMatchingJarEntries(List<String> list, URL url, String pattern)
        throws IOException {
    // get the stream to the resource and read it as a jar
    JarInputStream jis = new JarInputStream(url.openStream());
    Set<String> result = new LinkedHashSet<String>(8);

    boolean patternWithFolderSlash = pattern.startsWith(FOLDER_SEPARATOR);

    // parse the jar and do pattern matching
    try {
        while (jis.available() > 0) {
            JarEntry jarEntry = jis.getNextJarEntry();
            // if the jar has ended, the entry can be null (on Sun JDK at least)
            if (jarEntry != null) {
                String entryPath = jarEntry.getName();

                // check if leading "/" is needed or not (it depends how the jar was created)
                if (entryPath.startsWith(FOLDER_SEPARATOR)) {
                    if (!patternWithFolderSlash) {
                        entryPath = entryPath.substring(FOLDER_SEPARATOR.length());
                    }
                } else {
                    if (patternWithFolderSlash) {
                        entryPath = FOLDER_SEPARATOR.concat(entryPath);
                    }
                }
                if (getPathMatcher().match(pattern, entryPath)) {
                    result.add(entryPath);
                }
            }
        }
    } finally {
        try {
            jis.close();
        } catch (IOException io) {
            // ignore it - nothing we can't do about it
        }
    }

    if (logger.isTraceEnabled())
        logger.trace("Found in nested jar [" + url + "] matching entries " + result);

    list.addAll(result);
}

From source file:org.schemaspy.Config.java

public static Set<String> getBuiltInDatabaseTypes(String loadedFromJar) {
    Set<String> databaseTypes = new TreeSet<>();
    JarInputStream jar = null;

    try {/*  w ww .j av  a  2s . c  o  m*/
        jar = new JarInputStream(new FileInputStream(loadedFromJar));
        JarEntry entry;

        while ((entry = jar.getNextJarEntry()) != null) {
            String entryName = entry.getName();
            if (entryName.indexOf("types") != -1) {
                int dotPropsIndex = entryName.indexOf(".properties");
                if (dotPropsIndex != -1)
                    databaseTypes.add(entryName.substring(0, dotPropsIndex));
            }
        }
    } catch (IOException exc) {
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ignore) {
            }
        }
    }

    return databaseTypes;
}

From source file:org.eclipse.wb.internal.core.editor.palette.dialogs.ImportArchiveDialog.java

private List<PaletteElementInfo> extractElementsFromJarByManifest(JarInputStream jarStream) throws Exception {
    List<PaletteElementInfo> elements = Lists.newArrayList();
    Manifest manifest = jarStream.getManifest();
    // check manifest, if null find it
    if (manifest == null) {
        try {// ww  w  .  jav  a 2  s .  c om
            while (true) {
                JarEntry entry = jarStream.getNextJarEntry();
                if (entry == null) {
                    break;
                }
                if (JarFile.MANIFEST_NAME.equalsIgnoreCase(entry.getName())) {
                    // read manifest data
                    byte[] buffer = IOUtils.toByteArray(jarStream);
                    jarStream.closeEntry();
                    // create manifest
                    manifest = new Manifest(new ByteArrayInputStream(buffer));
                    break;
                }
            }
        } catch (Throwable e) {
            DesignerPlugin.log(e);
            manifest = null;
        }
    }
    if (manifest != null) {
        // extract all "Java-Bean: True" classes
        for (Iterator<Map.Entry<String, Attributes>> I = manifest.getEntries().entrySet().iterator(); I
                .hasNext();) {
            Map.Entry<String, Attributes> mapElement = I.next();
            Attributes attributes = mapElement.getValue();
            if (JAVA_BEAN_VALUE.equalsIgnoreCase(attributes.getValue(JAVA_BEAN_KEY))) {
                String beanClass = mapElement.getKey();
                if (beanClass == null || beanClass.length() <= JAVA_BEAN_CLASS_SUFFIX.length()) {
                    continue;
                }
                // convert 'aaa/bbb/ccc.class' to 'aaa.bbb.ccc'
                PaletteElementInfo element = new PaletteElementInfo();
                element.className = StringUtils.substringBeforeLast(beanClass, JAVA_BEAN_CLASS_SUFFIX)
                        .replace('/', '.');
                element.name = CodeUtils.getShortClass(element.className);
                elements.add(element);
            }
        }
    }
    return elements;
}

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;//  w w w. jav  a2  s  .c  om
    while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
        if (jarEntry.isDirectory()) {
            continue;
        }
        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.paniclauncher.workers.InstanceInstaller.java

public void deleteMetaInf() {
    File inputFile = getMinecraftJar();
    File outputTmpFile = new File(App.settings.getTempDir(), pack.getSafeName() + "-minecraft.jar");
    try {/* ww w  .  ja v a 2  s .c o  m*/
        JarInputStream input = new JarInputStream(new FileInputStream(inputFile));
        JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile));
        JarEntry entry;

        while ((entry = input.getNextJarEntry()) != null) {
            if (entry.getName().contains("META-INF")) {
                continue;
            }
            output.putNextEntry(entry);
            byte buffer[] = new byte[1024];
            int amo;
            while ((amo = input.read(buffer, 0, 1024)) != -1) {
                output.write(buffer, 0, amo);
            }
            output.closeEntry();
        }

        input.close();
        output.close();

        inputFile.delete();
        outputTmpFile.renameTo(inputFile);
    } catch (IOException e) {
        App.settings.getConsole().logStackTrace(e);
    }
}

From source file:com.flexive.shared.FxSharedUtils.java

/**
 * This method returns all entries in a JarInputStream for a given search pattern within the jar as a Map
 * having the filename as the key and the file content as its respective value (String).
 * The boolean flag "isFile" marks the search pattern as a file, otherwise the pattern will be treated as
 * a path to be found in the jarStream//  w  ww .j  a  va2s.  c  o m
 * A successful search either returns a map of all entries for a given path or a map of all entries for a given file
 * (again, depending on the "isFile" flag).
 * Null will be returned if no occurrences of the search pattern were found.
 *
 * @param jarStream     the given JarInputStream
 * @param searchPattern the pattern to be examined as a String
 * @param isFile        if true, the searchPattern is treated as a file name, if false, the searchPattern will be treated as a path
 * @return Returns all entries found for the given search pattern as a Map<String, String>, or null if no matches were found
 * @throws IOException on I/O errors
 */
public static Map<String, String> getContentsFromJarStream(JarInputStream jarStream, String searchPattern,
        boolean isFile) throws IOException {
    Map<String, String> jarContents = new HashMap<String, String>();
    int found = 0;
    try {
        if (jarStream != null) {
            JarEntry entry;
            while ((entry = jarStream.getNextJarEntry()) != null) {
                if (isFile) {
                    if (!entry.isDirectory() && entry.getName().endsWith(searchPattern)) {
                        final String name = entry.getName().substring(entry.getName().lastIndexOf("/") + 1);
                        jarContents.put(name, readFromJarEntry(jarStream, entry));
                        found++;
                    }
                } else {
                    if (!entry.isDirectory() && entry.getName().startsWith(searchPattern)) {
                        jarContents.put(entry.getName(), readFromJarEntry(jarStream, entry));
                        found++;
                    }
                }
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found " + found + " entries in the JarInputStream for the pattern " + searchPattern);
            }
        }
    } finally {
        if (jarStream != null) {
            try {
                jarStream.close();
            } catch (IOException e) {
                LOG.warn("Failed to close stream: " + e.getMessage(), e);
            }
        } else {
            LOG.warn("JarInputStream parameter was null, no search performed");
        }
    }

    return jarContents.isEmpty() ? null : jarContents;
}