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:JarUtils.java

/**
 * Add jar contents to the deployment archive under the given prefix
 *///from ww  w .  ja v  a 2 s .  c o m
public static String[] addJar(JarOutputStream outputStream, String prefix, File jar) throws IOException {

    ArrayList tmp = new ArrayList();
    FileInputStream fis = new FileInputStream(jar);
    JarInputStream jis = new JarInputStream(fis);
    JarEntry entry = jis.getNextJarEntry();
    while (entry != null) {
        if (entry.isDirectory() == false) {
            String entryName = prefix + entry.getName();
            tmp.add(entryName);
            addJarEntry(outputStream, entryName, jis);
        }
        entry = jis.getNextJarEntry();
    }
    jis.close();
    String[] names = new String[tmp.size()];
    tmp.toArray(names);
    return names;
}

From source file:net.lightbody.bmp.proxy.jetty.util.JarResource.java

public static void extract(Resource resource, File directory, boolean deleteOnExit) throws IOException {
    if (log.isDebugEnabled())
        log.debug("Extract " + resource + " to " + directory);
    JarInputStream jin = new JarInputStream(resource.getInputStream());
    JarEntry entry = null;//from  ww w. ja va2 s .  c  o  m
    while ((entry = jin.getNextJarEntry()) != null) {
        File file = new File(directory, entry.getName());
        if (entry.isDirectory()) {
            // Make directory
            if (!file.exists())
                file.mkdirs();
        } else {
            // make directory (some jars don't list dirs)
            File dir = new File(file.getParent());
            if (!dir.exists())
                dir.mkdirs();

            // Make file
            FileOutputStream fout = null;
            try {
                fout = new FileOutputStream(file);
                IO.copy(jin, fout);
            } finally {
                IO.close(fout);
            }

            // touch the file.
            if (entry.getTime() >= 0)
                file.setLastModified(entry.getTime());
        }
        if (deleteOnExit)
            file.deleteOnExit();
    }
}

From source file:org.talend.components.marketo.MarketoRuntimeInfoTest.java

static List<URL> extractDependencyFromStream(DependenciesReader dependenciesReader, String depTxtPath,
        JarInputStream jarInputStream) throws IOException {
    JarEntry nextJarEntry = jarInputStream.getNextJarEntry();
    while (nextJarEntry != null) {
        if (depTxtPath.equals(nextJarEntry.getName())) {// we got it so parse it.
            Set<String> dependencies = dependenciesReader.parseDependencies(jarInputStream);
            // convert the string to URL
            List<URL> result = new ArrayList<>(dependencies.size());
            for (String urlString : dependencies) {
                result.add(new URL(urlString));
                System.out.println("new URL(\"" + urlString + "\"),//");
            }/*from   w w  w.ja  va  2 s  . c o  m*/
            return result;
        }
        nextJarEntry = jarInputStream.getNextJarEntry();
    }
    throw new ComponentException(ComponentsApiErrorCode.COMPUTE_DEPENDENCIES_FAILED,
            ExceptionContext.withBuilder().put("path", depTxtPath).build());
}

From source file:com.streamsets.datacollector.cluster.TestTarFileCreator.java

private static void readJar(TarInputStream tis) throws IOException {
    TarEntry fileEntry = readFile(tis);//from   w  w w. j a v a  2 s. c om
    byte[] buffer = new byte[8192 * 8];
    int read = IOUtils.read(tis, buffer);
    JarInputStream jar = new JarInputStream(new ByteArrayInputStream(buffer, 0, read));
    JarEntry entry = jar.getNextJarEntry();
    Assert.assertNotNull(Utils.format("Read {} bytes and found a null entry", read), entry);
    Assert.assertEquals("sample.txt", entry.getName());
    read = IOUtils.read(jar, buffer);
    Assert.assertEquals(FilenameUtils.getBaseName(fileEntry.getName()),
            new String(buffer, 0, read, StandardCharsets.UTF_8));
}

From source file:com.katsu.dwm.reflection.JarUtils.java

/**
 * Return as stream a resource in a jar//w w  w.  j a  v a  2 s .  c  o m
 * @param jar
 * @param resource 
 */
public static InputStream getResourceAsStreamFromJar(File jar, String resource) {
    JarInputStream jis = null;
    try {
        jis = new JarInputStream(new FileInputStream(jar));
        JarEntry je;
        while ((je = jis.getNextJarEntry()) != null) {
            logger.trace(jar.getName() + " " + je.getName());
            if (je.getName().equals(resource)) {
                return jis;
            }
        }
    } catch (Exception ex) {
        logger.error(ex + " " + jar.getPath());
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }
    return null;
}

From source file:org.apache.cloudstack.framework.serializer.OnwireClassRegistry.java

static Set<Class<?>> getFromJARFile(String jar, String packageName) throws IOException, ClassNotFoundException {
    Set<Class<?>> classes = new HashSet<Class<?>>();
    JarInputStream jarFile = new JarInputStream(new FileInputStream(jar));
    JarEntry jarEntry;/*from   ww w.  j a va  2 s. com*/
    do {
        jarEntry = jarFile.getNextJarEntry();
        if (jarEntry != null) {
            String className = jarEntry.getName();
            if (className.endsWith(".class")) {
                className = stripFilenameExtension(className);
                if (className.startsWith(packageName)) {
                    try {
                        Class<?> clz = Class.forName(className.replace('/', '.'));
                        classes.add(clz);
                    } catch (ClassNotFoundException | NoClassDefFoundError e) {
                        s_logger.warn("Unable to load class from jar file", e);
                    }
                }
            }
        }
    } while (jarEntry != null);

    IOUtils.closeQuietly(jarFile);
    return classes;
}

From source file:com.fengduo.bee.commons.core.lang.ClassLoaderUtils.java

public static List<String> getClassNamesInPackage(String jarName, String packageName) throws IOException {
    JarInputStream jarFile = new JarInputStream(new FileInputStream(jarName));
    packageName = packageName.replace(".", "/");
    List<String> classes = new ArrayList<String>();

    try {/*from   ww  w . java  2 s  .  c  o m*/
        for (JarEntry jarEntry; (jarEntry = jarFile.getNextJarEntry()) != null;) {
            if ((jarEntry.getName().startsWith(packageName)) && (jarEntry.getName().endsWith(".class"))) {
                classes.add(jarEntry.getName().replace("/", ".").replaceAll(".class", ""));
            }
        }
    } finally {
        jarFile.close();
    }
    return classes;
}

From source file:org.vafer.jdependency.utils.DependencyUtils.java

public static Set<String> getDependenciesOfJar(final InputStream pInputStream) throws IOException {
    final JarInputStream inputStream = new JarInputStream(pInputStream);
    final NullOutputStream nullStream = new NullOutputStream();
    final Set<String> dependencies = new HashSet<String>();
    try {/*from  ww  w  . java2 s.  c o m*/
        while (true) {
            final JarEntry entry = inputStream.getNextJarEntry();

            if (entry == null) {
                break;
            }

            if (entry.isDirectory()) {
                // ignore directory entries
                IOUtils.copy(inputStream, nullStream);
                continue;
            }

            final String name = entry.getName();

            if (name.endsWith(".class")) {
                final DependenciesClassAdapter v = new DependenciesClassAdapter();
                new ClassReader(inputStream).accept(v, 0);
                dependencies.addAll(v.getDependencies());
            } else {
                IOUtils.copy(inputStream, nullStream);
            }
        }
    } finally {
        inputStream.close();
    }

    return dependencies;
}

From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.JarUtils.java

/**
 * Dumps the entries of a jar and return them as a String. This method can
 * be memory expensive depending on the jar size.
 * /*from  ww  w  .  j  ava 2s .  com*/
 * @param jis
 * @return
 * @throws Exception
 */
public static String dumpJarContent(JarInputStream jis) {
    StringBuilder buffer = new StringBuilder();

    try {
        JarEntry entry;
        while ((entry = jis.getNextJarEntry()) != null) {
            buffer.append(entry.getName());
            buffer.append("\n");
        }
    } catch (IOException ioException) {
        buffer.append("reading from stream failed");
    } finally {
        closeStream(jis);
    }

    return buffer.toString();
}

From source file:org.sherlok.utils.BundleCreatorUtil.java

private static void createBundle(Set<BundleDef> bundleDefs) throws Exception {

    // create fake POM from bundles and copy it
    String fakePom = MavenPom.writePom(bundleDefs, "BundleCreator", System.currentTimeMillis() + "");// must be unique
    Artifact rootArtifact = new DefaultArtifact(fakePom);
    LOG.trace("* rootArtifact: '{}'", rootArtifact);

    // add remote repository urls
    RepositorySystem system = AetherResolver.newRepositorySystem();
    RepositorySystemSession session = AetherResolver.newRepositorySystemSession(system,
            AetherResolver.LOCAL_REPO_PATH);
    Map<String, String> repositoriesDefs = map();
    for (BundleDef b : bundleDefs) {
        b.validate(b.getId());//from   w  ww . j av  a  2  s.c o m
        for (Entry<String, String> id_url : b.getRepositories().entrySet()) {
            repositoriesDefs.put(id_url.getKey(), id_url.getValue());
        }
    }
    List<RemoteRepository> repos = AetherResolver.newRepositories(system, session, repositoriesDefs);

    // solve dependencies
    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(new Dependency(rootArtifact, ""));
    collectRequest
            .setRepositories(AetherResolver.newRepositories(system, session, new HashMap<String, String>()));
    CollectResult collectResult = system.collectDependencies(session, collectRequest);
    collectResult.getRoot().accept(new AetherResolver.ConsoleDependencyGraphDumper());
    PreorderNodeListGenerator p = new PreorderNodeListGenerator();
    collectResult.getRoot().accept(p);

    // now do the real fetching, and add jars to classpath
    List<Artifact> resolvedArtifacts = list();
    for (Dependency dependency : p.getDependencies(true)) {
        Artifact resolvedArtifact = system
                .resolveArtifact(session, new ArtifactRequest(dependency.getArtifact(), repos, ""))
                .getArtifact();
        resolvedArtifacts.add(resolvedArtifact);
        File jar = resolvedArtifact.getFile();

        // add this jar to the classpath
        ClassPathHack.addFile(jar);
        LOG.trace("* resolved artifact '{}', added to classpath: '{}'", resolvedArtifact,
                jar.getAbsolutePath());
    }

    BundleDef createdBundle = new BundleDef();
    createdBundle.setVersion("TODO!");
    createdBundle.setName("TODO!");
    for (BundleDef bundleDef : bundleDefs) {
        for (BundleDependency dep : bundleDef.getDependencies()) {
            createdBundle.addDependency(dep);
        }
    }

    for (Artifact a : resolvedArtifacts) {

        // only consider artifacts that were included in the initial bundle
        boolean found = false;
        for (BundleDef bundleDef : bundleDefs) {
            for (BundleDependency dep : bundleDef.getDependencies()) {
                if (a.getArtifactId().equals(dep.getArtifactId())) {
                    found = true;
                    break;
                }
            }
        }

        if (found) {

            JarInputStream is = new JarInputStream(new FileInputStream(a.getFile()));
            JarEntry entry;
            while ((entry = is.getNextJarEntry()) != null) {
                if (entry.getName().endsWith(".class")) {

                    try {
                        Class<?> clazz = Class.forName(entry.getName().replace('/', '.').replace(".class", ""));

                        // scan for all uimafit AnnotationEngines
                        if (JCasAnnotator_ImplBase.class.isAssignableFrom(clazz)) {
                            LOG.debug("AnnotationEngine: {}", clazz.getSimpleName());

                            final EngineDef engine = new EngineDef().setClassz(clazz.getName())
                                    .setName(clazz.getSimpleName()).setBundle(createdBundle);
                            createdBundle.addEngine(engine);
                            LOG.debug("{}", engine);

                            ReflectionUtils.doWithFields(clazz, new FieldCallback() {
                                public void doWith(final Field f)
                                        throws IllegalArgumentException, IllegalAccessException {

                                    ConfigurationParameter c = f.getAnnotation(ConfigurationParameter.class);
                                    if (c != null) {
                                        LOG.debug("* param: {} {} {} {}", new Object[] { c.name(),
                                                c.defaultValue(), c.mandatory(), f.getType() });

                                        String deflt = c.mandatory() ? "TODO" : "IS OPTIONAL";

                                        String value = c.defaultValue()[0]
                                                .equals(ConfigurationParameter.NO_DEFAULT_VALUE) ? deflt
                                                        : c.defaultValue()[0].toString();
                                        engine.addParameter(c.name(), list(value));
                                    }
                                }
                            });
                        }
                    } catch (Throwable e) {
                        System.err.println("something wrong with class " + entry.getName() + " " + e);
                    }
                }
            }
            is.close();
        }
    }

    // delete fake pom
    deleteDirectory(new File(LOCAL_REPO_PATH + "/org/sherlok/BundleCreator"));

    System.out.println(FileBased.writeAsString(createdBundle));
}