Example usage for java.util.jar JarFile getInputStream

List of usage examples for java.util.jar JarFile getInputStream

Introduction

In this page you can find the example usage for java.util.jar JarFile getInputStream.

Prototype

public synchronized InputStream getInputStream(ZipEntry ze) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:net.ymate.framework.unpack.Unpackers.java

private boolean __unpack(JarFile jarFile, String prefixPath) throws Exception {
    boolean _results = false;
    Enumeration<JarEntry> _entriesEnum = jarFile.entries();
    for (; _entriesEnum.hasMoreElements();) {
        JarEntry _entry = _entriesEnum.nextElement();
        if (StringUtils.startsWith(_entry.getName(), prefixPath)) {
            if (!_entry.isDirectory()) {
                _LOG.info("Synchronizing resource file: " + _entry.getName());
                //
                String _entryName = StringUtils.substringAfter(_entry.getName(), prefixPath);
                File _targetFile = new File(RuntimeUtils.getRootPath(false), _entryName);
                _targetFile.getParentFile().mkdirs();
                IOUtils.copyLarge(jarFile.getInputStream(_entry), new FileOutputStream(_targetFile));
                _results = true;//from   w ww  .j  a va2 s. c  om
            }
        }
    }
    return _results;
}

From source file:mobac.mapsources.loader.MapPackManager.java

/**
 * Verifies the class file signatures of the specified map pack
 * //www . j  a va  2 s  . c  o m
 * @param mapPackFile
 * @throws IOException
 * @throws CertificateException
 */
public void testMapPack(File mapPackFile) throws IOException, CertificateException {
    String fileName = mapPackFile.getName();
    JarFile jf = new JarFile(mapPackFile, true);
    try {
        Enumeration<JarEntry> it = jf.entries();
        while (it.hasMoreElements()) {
            JarEntry entry = it.nextElement();
            // We verify only class files
            if (!entry.getName().endsWith(".class"))
                continue; // directory or other entry
            // Get the input stream (triggers) the signature verification for the specific class
            Utilities.readFully(jf.getInputStream(entry));
            if (entry.getCodeSigners() == null)
                throw new CertificateException("Unsigned class file found: " + entry.getName());
            CodeSigner signer = entry.getCodeSigners()[0];
            List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates();
            if (cp.size() > 1)
                throw new CertificateException("Signature certificate not accepted: "
                        + "certificate path contains more than one certificate");
            // Compare the used certificate with the mapPack certificate
            if (!mapPackCert.equals(cp.get(0)))
                throw new CertificateException(
                        "Signature certificate not accepted: " + "not the MapPack signer certificate");
        }
        Manifest mf = jf.getManifest();
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackVersion");
        if (mpv == null)
            throw new IOException("MapPackVersion info missing!");
        int mapPackVersion = Integer.parseInt(mpv);
        if (requiredMapPackVersion != mapPackVersion)
            throw new IOException("This pack \"" + fileName + "\" is not compatible with this MOBAC version.");
        ZipEntry entry = jf.getEntry("META-INF/services/mobac.program.interfaces.MapSource");
        if (entry == null)
            throw new IOException("MapSources services list is missing in file " + fileName);
    } finally {
        jf.close();
    }

}

From source file:org.kantega.revoc.source.MavenSourceArtifactSourceSource.java

public String[] getSource(String className, ClassLoader classLoader) {

    URL resource = classLoader.getResource(className + ".class");

    String filePath = getFilePath(resource);

    if (filePath == null) {
        return null;
    }/*from w w  w  .jav a  2  s  . co  m*/

    try {

        MavenSourceInfo info;

        synchronized (mavenInfoMap) {

            if (!mavenInfoMap.containsKey(filePath)) {
                mavenInfoMap.put(filePath, parseInfo(filePath, resource));
            }
            info = mavenInfoMap.get(filePath);
        }

        JarFile sourceFile;
        synchronized (sourceFileMap) {
            if (!sourceFileMap.containsKey(filePath)) {
                sourceFileMap.put(filePath, getSourceFile(filePath, info));
            }
            sourceFile = sourceFileMap.get(filePath);
        }

        if (sourceFile == null) {
            return null;
        }
        String sourcePath = className.replace('.', '/') + ".java";
        ZipEntry entry = sourceFile.getEntry(sourcePath);
        if (entry == null) {
            return null;
        }
        InputStream inputStream = sourceFile.getInputStream(entry);
        List<String> lines = IOUtils.readLines(inputStream);
        return lines.toArray(new String[lines.size()]);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:osmcd.mapsources.loader.MapPackManager.java

/**
 * Verifies the class file signatures of the specified map pack
 * /*from www.  j  a v a 2s.  c  o  m*/
 * @param mapPackFile
 * @throws IOException
 * @throws CertificateException
 */
public void testMapPack(File mapPackFile) throws IOException, CertificateException {
    String fileName = mapPackFile.getName();
    JarFile jf = new JarFile(mapPackFile, true);
    try {
        Enumeration<JarEntry> it = jf.entries();
        while (it.hasMoreElements()) {
            JarEntry entry = it.nextElement();
            // We verify only class files
            if (!entry.getName().endsWith(".class"))
                continue; // directory or other entry
            // Get the input stream (triggers) the signature verification for the specific class
            Utilities.readFully(jf.getInputStream(entry));
            if (entry.getCodeSigners() == null)
                throw new CertificateException("Unsigned class file found: " + entry.getName());
            CodeSigner signer = entry.getCodeSigners()[0];
            List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates();
            if (cp.size() > 1)
                throw new CertificateException("Signature certificate not accepted: "
                        + "certificate path contains more than one certificate");
            // Compare the used certificate with the mapPack certificate
            if (!mapPackCert.equals(cp.get(0)))
                throw new CertificateException(
                        "Signature certificate not accepted: " + "not the MapPack signer certificate");
        }
        Manifest mf = jf.getManifest();
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackVersion");
        if (mpv == null)
            throw new IOException("MapPackVersion info missing!");
        int mapPackVersion = Integer.parseInt(mpv);
        if (requiredMapPackVersion != mapPackVersion)
            throw new IOException("This pack \"" + fileName + "\" is not compatible with this OSMCB version.");
        ZipEntry entry = jf.getEntry("META-INF/services/osmcd.program.interfaces.MapSource");
        if (entry == null)
            throw new IOException("MapSources services list is missing in file " + fileName);
    } finally {
        jf.close();
    }

}

From source file:com.taobao.android.builder.tools.multidex.mutli.JarRefactor.java

private Collection<File> generateFirstDexJar(List<String> mainDexList, Collection<File> files)
        throws IOException {

    List<File> jarList = new ArrayList<>();
    List<File> folderList = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            folderList.add(file);//from  w  w w .jav  a 2s .c o m
        } else {
            jarList.add(file);
        }
    }

    File dir = new File(appVariantContext.getScope().getGlobalScope().getIntermediatesDir(),
            "fastmultidex/" + appVariantContext.getVariantName());
    FileUtils.deleteDirectory(dir);
    dir.mkdirs();

    if (!folderList.isEmpty()) {
        File mergedJar = new File(dir, "jarmerging/combined.jar");
        mergedJar.getParentFile().mkdirs();
        mergedJar.delete();
        mergedJar.createNewFile();
        JarMerger jarMerger = new JarMerger(mergedJar.toPath());
        for (File folder : folderList) {
            jarMerger.addDirectory(folder.toPath());
        }
        jarMerger.close();
        if (mergedJar.length() > 0) {
            jarList.add(mergedJar);
        }
    }

    List<File> result = new ArrayList<>();
    File maindexJar = new File(dir, DexMerger.FASTMAINDEX_JAR + ".jar");

    JarOutputStream mainJarOuputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(maindexJar)));

    //First order
    Collections.sort(jarList, new NameComparator());

    for (File jar : jarList) {
        File outJar = new File(dir, FileNameUtils.getUniqueJarName(jar) + ".jar");

        result.add(outJar);
        JarFile jarFile = new JarFile(jar);
        JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));
        Enumeration<JarEntry> jarFileEntries = jarFile.entries();

        List<String> pathList = new ArrayList<>();
        while (jarFileEntries.hasMoreElements()) {
            JarEntry ze = jarFileEntries.nextElement();
            String pathName = ze.getName();
            if (mainDexList.contains(pathName)) {
                copyStream(jarFile.getInputStream(ze), mainJarOuputStream, ze, pathName);
                pathList.add(pathName);
            }
        }

        if (!pathList.isEmpty()) {
            jarFileEntries = jarFile.entries();
            while (jarFileEntries.hasMoreElements()) {
                JarEntry ze = jarFileEntries.nextElement();
                String pathName = ze.getName();
                if (!pathList.contains(pathName)) {
                    copyStream(jarFile.getInputStream(ze), jos, ze, pathName);
                }
            }
        }

        jarFile.close();
        IOUtils.closeQuietly(jos);

        if (pathList.isEmpty()) {
            FileUtils.copyFile(jar, outJar);
        }
        if (!appVariantContext.getAtlasExtension().getTBuildConfig().isFastProguard() && files.size() == 1) {
            JarUtils.splitMainJar(result, outJar, 1, MAX_CLASSES);
        }
    }

    IOUtils.closeQuietly(mainJarOuputStream);

    Collections.sort(result, new NameComparator());

    result.add(0, maindexJar);

    return result;
}

From source file:com.panet.imeta.job.JobEntryLoader.java

/**
 * Search through all jarfiles in all steps and try to find a certain file
 * in it.//from   ww  w  . ja va2s. c  o  m
 * 
 * @param filename
 * @return an inputstream for the given file.
 */
public InputStream getInputStreamForFile(String filename) {
    JobPlugin[] jobplugins = getJobEntriesWithType(JobPlugin.TYPE_PLUGIN);
    for (JobPlugin jobPlugin : jobplugins) {
        try {
            String[] jarfiles = jobPlugin.getJarfiles();
            if (jarfiles != null) {
                for (int j = 0; j < jarfiles.length; j++) {
                    JarFile jarFile = new JarFile(jarfiles[j]);
                    JarEntry jarEntry;
                    if (filename.startsWith("/")) {
                        jarEntry = jarFile.getJarEntry(filename.substring(1));
                    } else {
                        jarEntry = jarFile.getJarEntry(filename);
                    }
                    if (jarEntry != null) {
                        InputStream inputStream = jarFile.getInputStream(jarEntry);
                        if (inputStream != null) {
                            return inputStream;
                        }
                    }
                }
            }
        } catch (Exception e) {
            // Just look for the next one...
        }
    }
    return null;
}

From source file:org.lilyproject.runtime.source.JarModuleSource.java

public List<SpringConfigEntry> getSpringConfigs(Mode mode) {
    Pattern modeSpecificSpringPattern = Pattern.compile("LILY-INF/spring/" + mode.getName() + "/[^/]*\\.xml");
    List<SpringConfigEntry> result = new ArrayList<SpringConfigEntry>();
    final JarFile jarFile = this.jarFile;

    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        final JarEntry jarEntry = jarEntries.nextElement();
        final String name = jarEntry.getName();

        Matcher matcher1 = SPRING_COMMON_CONF_PATTERN.matcher(name);
        Matcher matcher2 = modeSpecificSpringPattern.matcher(name);
        if (matcher1.matches() || matcher2.matches()) {
            result.add(new SpringConfigEntry() {
                public String getLocation() {
                    return name;
                }/*  www . j a v a  2  s  . c  om*/

                public InputStream getStream() throws IOException {
                    return jarFile.getInputStream(jarEntry);
                }
            });
        }
    }

    return result;
}

From source file:com.github.ithildir.liferay.mobile.go.GoSDKBuilder.java

protected void copyJarResource(JarURLConnection jarConnection, File destinationDir) throws IOException {

    String jarConnectionEntryName = jarConnection.getEntryName();
    JarFile jarFile = jarConnection.getJarFile();

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

    while (enu.hasMoreElements()) {
        JarEntry jarEntry = enu.nextElement();
        String jarEntryName = jarEntry.getName();

        if (jarEntryName.startsWith(jarConnectionEntryName)) {
            String fileName = jarEntryName;

            if (fileName.startsWith(jarConnectionEntryName)) {
                fileName = fileName.substring(jarConnectionEntryName.length());
            }/*from ww w  .j  a  va  2  s .c om*/

            File file = new File(destinationDir, fileName);

            if (jarEntry.isDirectory()) {
                file.mkdirs();
            } else {
                InputStream is = null;

                try {
                    is = jarFile.getInputStream(jarEntry);

                    FileUtils.copyInputStreamToFile(is, file);
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }
        }
    }
}

From source file:org.xwiki.webjars.internal.FilesystemResourceReferenceSerializer.java

private void copyResourceFromJAR(String resourcePrefix, String resourceName, String targetPrefix,
        FilesystemExportContext exportContext) throws IOException {
    // Note that we cannot use ClassLoader.getResource() to access the resource since the resourcePath may point
    // to a directory inside the JAR, and in this case we need to copy all resources inside that directory in the
    // JAR!/* w  w  w . j  av a2 s .  co  m*/

    String resourcePath = String.format("%s/%s", resourcePrefix, resourceName);
    JarFile jar = new JarFile(getJARFile(resourcePath));
    for (Enumeration<JarEntry> enumeration = jar.entries(); enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();
        if (entry.getName().startsWith(resourcePath) && !entry.isDirectory()) {
            // Copy the resource!
            // TODO: Won't this cause collisions if the same resource is available on several subwikis for example?
            String targetPath = targetPrefix + entry.getName().substring(resourcePrefix.length());
            File targetLocation = new File(exportContext.getExportDir(), targetPath);
            if (!targetLocation.exists()) {
                targetLocation.getParentFile().mkdirs();
                FileOutputStream fos = new FileOutputStream(targetLocation);
                InputStream is = jar.getInputStream(entry);
                IOUtils.copy(is, fos);
                fos.close();
                is.close();
            }
        }
    }
    jar.close();
}

From source file:streamflow.service.FrameworkService.java

public FrameworkConfig processFrameworkConfig(File tempFrameworkFile) {
    FrameworkConfig frameworkConfig = null;

    try {//from w ww  .j  a va  2 s  . c o  m
        JarFile frameworkJarFile = new JarFile(tempFrameworkFile.getAbsoluteFile());

        JarEntry frameworkYamlEntry = frameworkJarFile.getJarEntry("STREAMFLOW-INF/framework.yml");

        JarEntry frameworkJsonEntry = frameworkJarFile.getJarEntry("STREAMFLOW-INF/framework.json");

        if (frameworkYamlEntry != null) {
            String frameworkYaml = IOUtils.toString(frameworkJarFile.getInputStream(frameworkYamlEntry));

            // Attempt to deserialize the inbuilt streams-framework.json 
            frameworkConfig = yamlMapper.readValue(frameworkYaml, FrameworkConfig.class);
        } else if (frameworkJsonEntry != null) {
            String frameworkJson = IOUtils.toString(frameworkJarFile.getInputStream(frameworkJsonEntry));

            // Attempt to deserialize the inbuilt streams-framework.json 
            frameworkConfig = jsonMapper.readValue(frameworkJson, FrameworkConfig.class);
        } else {
            frameworkConfig = processFrameworkAnnotations(tempFrameworkFile);
            if (frameworkConfig == null) {
                throw new EntityInvalidException(
                        "The framework configuration file was not found in the framework jar");
            }
        }
    } catch (IOException ex) {
        LOG.error("Error while loaded the framework configuration: ", ex);

        throw new EntityInvalidException("Error while loading the framework configuration: " + ex.getMessage());
    }

    return frameworkConfig;
}