Example usage for java.util.jar JarInputStream JarInputStream

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

Introduction

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

Prototype

public JarInputStream(InputStream in) throws IOException 

Source Link

Document

Creates a new JarInputStream and reads the optional manifest.

Usage

From source file:org.bimserver.plugins.classloaders.FileJarClassLoader.java

private void loadEmbeddedJarFileSystems(Path path) {
    try {// w w  w .j  a  v  a 2  s.c o m
        if (Files.isDirectory(path)) {
            for (Path subPath : PathUtils.list(path)) {
                loadEmbeddedJarFileSystems(subPath);
            }
        } else {
            // This is annoying, but we are caching the contents of JAR files within JAR files in memory, could not get the JarFileSystem to work with jar:jar:file URI's
            // Also there is a problem with not being able to change position within a file, at least in the JarFileSystem
            // It looks like there are 2 other solutions to this problem:
            // - Copy the embedded JAR files to a tmp directory, and load from there with a JarFileSystem wrapper (at some stage we were doing this for all JAR contents, 
            // resulted in 50.000 files, which was annoying, but a few JAR files probably won't hurt
            // - Don't allow plugins to have embedded JAR's, could force them to extract all dependencies...
            //
            if (path.getFileName().toString().toLowerCase().endsWith(".jar")) {
                JarInputStream jarInputStream = new JarInputStream(Files.newInputStream(path));
                try {
                    JarEntry jarEntry = jarInputStream.getNextJarEntry();
                    while (jarEntry != null) {
                        jarContent.put(jarEntry.getName(), IOUtils.toByteArray(jarInputStream));
                        jarEntry = jarInputStream.getNextJarEntry();
                    }
                } finally {
                    jarInputStream.close();
                }
            }
        }
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}

From source file:com.izforge.izpack.compiler.helper.CompilerHelper.java

/**
 * Returns a list which contains the pathes of all files which are included in the given url.
 * This method expects as the url param a jar.
 *
 * @param url url of the jar file//from   w  w w. jav a  2s. co m
 * @return full qualified paths of the contained files
 * @throws IOException if the jar cannot be read
 */
public List<String> getContainedFilePaths(URL url) throws IOException {
    JarInputStream jis = new JarInputStream(url.openStream());
    ZipEntry zentry;
    ArrayList<String> fullNames = new ArrayList<String>();
    while ((zentry = jis.getNextEntry()) != null) {
        String name = zentry.getName();
        // Add only files, no directory entries.
        if (!zentry.isDirectory()) {
            fullNames.add(name);
        }
    }
    jis.close();
    return (fullNames);
}

From source file:org.drools.guvnor.server.contenthandler.ModelContentHandler.java

private Set<String> getImportsFromJar(AssetItem assetItem) throws IOException {

    Set<String> imports = new HashSet<String>();
    Map<String, String> nonCollidingImports = new HashMap<String, String>();
    String assetPackageName = assetItem.getModuleName();

    //Setup class-loader to check for class visibility
    JarInputStream cljis = new JarInputStream(assetItem.getBinaryContentAttachment());
    List<JarInputStream> jarInputStreams = new ArrayList<JarInputStream>();
    jarInputStreams.add(cljis);/* w  w  w  .  j  a v a 2s .  c  o m*/
    ClassLoaderBuilder clb = new ClassLoaderBuilder(jarInputStreams);
    ClassLoader cl = clb.buildClassLoader();

    //Reset stream to read classes
    JarInputStream jis = new JarInputStream(assetItem.getBinaryContentAttachment());
    JarEntry entry = null;

    //Get Class names from JAR, only the first occurrence of a given Class leaf name will be inserted. Thus 
    //"org.apache.commons.lang.NumberUtils" will be imported but "org.apache.commons.lang.math.NumberUtils"
    //will not, assuming it follows later in the JAR structure.
    while ((entry = jis.getNextJarEntry()) != null) {
        if (!entry.isDirectory()) {
            if (entry.getName().endsWith(".class") && !entry.getName().endsWith("package-info.class")) {
                final String fullyQualifiedName = convertPathToName(entry.getName());
                final String fullyQualifiedClassName = convertPathToClassName(entry.getName());
                if (isClassVisible(cl, fullyQualifiedClassName, assetPackageName)) {
                    String leafName = getLeafName(fullyQualifiedName);
                    if (!nonCollidingImports.containsKey(leafName)) {
                        nonCollidingImports.put(leafName, fullyQualifiedName);
                    }
                }
            }
        }
    }

    //Build list of imports
    for (String value : nonCollidingImports.values()) {
        String line = "import " + value;
        imports.add(line);
    }

    return imports;
}

From source file:org.apache.geode.internal.DeployedJar.java

/**
 * Peek into the JAR data and make sure that it is valid JAR content.
 *
 * @param inputStream InputStream containing data to be validated.
 * @return True if the data has JAR content, false otherwise
 *///from  ww w  . java  2  s.  c  o m
private static boolean hasValidJarContent(final InputStream inputStream) {
    JarInputStream jarInputStream = null;
    boolean valid = false;

    try {
        jarInputStream = new JarInputStream(inputStream);
        valid = jarInputStream.getNextJarEntry() != null;
    } catch (IOException ignore) {
        // Ignore this exception and just return false
    } finally {
        try {
            jarInputStream.close();
        } catch (IOException ignored) {
            // Ignore this exception and just return result
        }
    }

    return valid;
}

From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java

private static boolean isLegacyJar(Resource jar) throws IOException {
    JarInputStream jis = new JarInputStream(jar.getInputStream());
    JarEntry entry = null;// w  w  w. j ava  2 s. c o m
    try {
        while ((entry = jis.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (name.startsWith("lib/") //|| name.startsWith("classes/")
            ) {
                return true;
            }
        }
    } finally {
        IOUtils.closeStream(jis);
    }
    return false;
}

From source file:org.apache.hadoop.util.TestJarFinder.java

@Test
public void testNoManifest() throws Exception {
    File dir = GenericTestUtils.getTestDir(TestJarFinder.class.getName() + "-testNoManifest");
    delete(dir);//from w w w.  j a v a2 s  .c  o  m
    dir.mkdirs();
    File propsFile = new File(dir, "props.properties");
    Writer writer = new FileWriter(propsFile);
    new Properties().store(writer, "");
    writer.close();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream zos = new JarOutputStream(baos);
    JarFinder.jarDir(dir, "", zos);
    JarInputStream jis = new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
    Assert.assertNotNull(jis.getManifest());
    jis.close();
}

From source file:com.liferay.ide.project.core.modules.ServiceWrapperCommand.java

private Map<String, String[]> _getDynamicServiceWrapper() throws IOException {
    PortalRuntime portalRuntime = (PortalRuntime) _server.getRuntime().loadAdapter(PortalRuntime.class, null);

    IPath bundleLibPath = portalRuntime.getAppServerLibGlobalDir();
    IPath bundleServerPath = portalRuntime.getAppServerDir();

    Map<String, String[]> map = new LinkedHashMap<>();

    List<File> libFiles;

    File portalkernelJar = null;// w w w. j  a  v  a 2 s  .  c  o m

    try {
        libFiles = FileListing.getFileListing(new File(bundleLibPath.toOSString()));

        for (File lib : libFiles) {
            if (FileUtil.exists(lib) && lib.getName().endsWith("portal-kernel.jar")) {
                portalkernelJar = lib;

                break;
            }
        }

        libFiles = FileListing.getFileListing(new File(bundleServerPath.append("../osgi").toOSString()));

        libFiles.add(portalkernelJar);

        if (ListUtil.isNotEmpty(libFiles)) {
            for (File lib : libFiles) {
                if (lib.getName().endsWith(".lpkg")) {
                    try (JarFile jar = new JarFile(lib)) {
                        Enumeration<JarEntry> enu = jar.entries();

                        while (enu.hasMoreElements()) {
                            try {
                                JarEntry entry = enu.nextElement();

                                String name = entry.getName();

                                if (name.contains(".api-")) {
                                    JarEntry jarentry = jar.getJarEntry(name);

                                    try (InputStream inputStream = jar.getInputStream(jarentry);
                                            JarInputStream jarInputStream = new JarInputStream(inputStream)) {
                                        JarEntry nextJarEntry;

                                        while ((nextJarEntry = jarInputStream.getNextJarEntry()) != null) {
                                            String entryName = nextJarEntry.getName();

                                            _getServiceWrapperList(map, entryName, jarInputStream);
                                        }
                                    }
                                }
                            } catch (Exception e) {
                            }
                        }
                    }
                } else if (lib.getName().endsWith("api.jar") || lib.getName().equals("portal-kernel.jar")) {

                    try (JarFile jar = new JarFile(lib);
                            InputStream inputStream = Files.newInputStream(lib.toPath());
                            JarInputStream jarinput = new JarInputStream(inputStream)) {

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

                        while (enu.hasMoreElements()) {
                            JarEntry entry = enu.nextElement();

                            String name = entry.getName();

                            _getServiceWrapperList(map, name, jarinput);
                        }
                    } catch (IOException ioe) {
                    }
                }
            }
        }
    } catch (FileNotFoundException fnfe) {
    }

    return map;
}

From source file:org.n52.ifgicopter.spf.common.PluginRegistry.java

/**
 * @param jar//w  ww  .  j  ava 2  s.  c om
 *        the jar
 * @return list of fqcn
 */
private List<String> listClasses(File jar) throws IOException {
    ArrayList<String> result = new ArrayList<String>();

    JarInputStream jis = new JarInputStream(new FileInputStream(jar));
    JarEntry je;

    while (jis.available() > 0) {
        je = jis.getNextJarEntry();

        if (je != null) {
            if (je.getName().endsWith(".class")) {
                result.add(je.getName().replaceAll("/", "\\.").substring(0, je.getName().indexOf(".class")));
            }
        }
    }

    return result;
}

From source file:com.photon.phresco.service.util.ServerUtil.java

/**
 * Validate the given jar is valid maven jar
 * /*from   ww w .  j  a v a 2 s. c o  m*/
 * @return
 * @throws PhrescoException
 */
public static boolean validateMavenJar(InputStream inputJar) throws PhrescoException {
    boolean returnValue = false;
    try {
        jarInputStream = new JarInputStream(inputJar);
        JarEntry nextJarEntry = jarInputStream.getNextJarEntry();
        while ((nextJarEntry = jarInputStream.getNextJarEntry()) != null) {
            if (nextJarEntry.getName().contains("pom.xml")) {
                returnValue = true;
                break;
            }
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }

    return returnValue;
}

From source file:com.destroystokyo.paperclip.Paperclip.java

static void run(final String[] args) {
    try {/*ww  w  .  j a v  a2  s  .  c  o  m*/
        digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        System.err.println("Could not create hashing instance");
        e.printStackTrace();
        System.exit(1);
    }

    final PatchData patchInfo;
    try (final InputStream is = getConfig()) {
        patchInfo = PatchData.parse(is);
    } catch (final IllegalArgumentException e) {
        System.err.println("Invalid patch file");
        e.printStackTrace();
        System.exit(1);
        return;
    } catch (final IOException e) {
        System.err.println("Error reading patch file");
        e.printStackTrace();
        System.exit(1);
        return;
    }

    final File vanillaJar = new File(cache, "mojang_" + patchInfo.getVersion() + ".jar");
    paperJar = new File(cache, "patched_" + patchInfo.getVersion() + ".jar");

    final boolean vanillaValid;
    final boolean paperValid;
    try {
        vanillaValid = checkJar(vanillaJar, patchInfo.getOriginalHash());
        paperValid = checkJar(paperJar, patchInfo.getPatchedHash());
    } catch (final IOException e) {
        System.err.println("Error reading jar");
        e.printStackTrace();
        System.exit(1);
        return;
    }

    if (!paperValid) {
        if (!vanillaValid) {
            System.out.println("Downloading original jar...");
            //noinspection ResultOfMethodCallIgnored
            cache.mkdirs();
            //noinspection ResultOfMethodCallIgnored
            vanillaJar.delete();

            try (final InputStream stream = patchInfo.getOriginalUrl().openStream()) {
                final ReadableByteChannel rbc = Channels.newChannel(stream);
                try (final FileOutputStream fos = new FileOutputStream(vanillaJar)) {
                    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                }
            } catch (final IOException e) {
                System.err.println("Error downloading original jar");
                e.printStackTrace();
                System.exit(1);
            }

            // Only continue from here if the downloaded jar is correct
            try {
                if (!checkJar(vanillaJar, patchInfo.getOriginalHash())) {
                    System.err.println("Invalid original jar, quitting.");
                    System.exit(1);
                }
            } catch (final IOException e) {
                System.err.println("Error reading jar");
                e.printStackTrace();
                System.exit(1);
            }
        }

        if (paperJar.exists()) {
            if (!paperJar.delete()) {
                System.err.println("Error deleting invalid jar");
                System.exit(1);
            }
        }

        System.out.println("Patching original jar...");
        final byte[] vanillaJarBytes;
        final byte[] patch;
        try {
            vanillaJarBytes = getBytes(vanillaJar);
            patch = Utils.readFully(patchInfo.getPatchFile().openStream());
        } catch (final IOException e) {
            System.err.println("Error patching original jar");
            e.printStackTrace();
            System.exit(1);
            return;
        }

        // Patch the jar to create the final jar to run
        try (final FileOutputStream jarOutput = new FileOutputStream(paperJar)) {
            Patch.patch(vanillaJarBytes, patch, jarOutput);
        } catch (final CompressorException | InvalidHeaderException | IOException e) {
            System.err.println("Error patching origin jar");
            e.printStackTrace();
            System.exit(1);
        }
    }

    // Exit if user has set `paperclip.patchonly` system property to `true`
    if (Boolean.getBoolean("paperclip.patchonly")) {
        System.exit(0);
    }

    // Get main class info from jar
    final String main;
    try (final FileInputStream fs = new FileInputStream(paperJar);
            final JarInputStream js = new JarInputStream(fs)) {
        main = js.getManifest().getMainAttributes().getValue("Main-Class");
    } catch (final IOException e) {
        System.err.println("Error reading from patched jar");
        e.printStackTrace();
        System.exit(1);
        return;
    }

    // Run the jar
    Utils.invoke(main, args);
}