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:com.flexive.testRunner.FxTestRunnerThread.java

/**
 * {@inheritDoc}//from  ww w. j  ava  2  s  . c o m
 */
@Override
public void run() {
    synchronized (lock) {
        if (testInProgress)
            return;
        testInProgress = true;
    }
    try {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        URL jar = cl.getResource("lib/flexive-tests.jar");

        //build a list of all test classes
        List<Class> testClasses = new ArrayList<Class>(100);
        try {
            JarInputStream jin = new JarInputStream(jar.openStream());
            while (jin.available() != 0) {
                JarEntry je = jin.getNextJarEntry();
                if (je == null)
                    continue;

                final String name = je.getName();
                //only classes, no inner classes, abstract or mock classes
                if (name.endsWith(".class") && !(name.indexOf('$') > 0) && !(name.indexOf("Abstract") > 0)
                        && !(name.indexOf("Mock") > 0)) {
                    boolean ignore = false;
                    //check ignore package
                    for (String pkg : FxTestRunner.ignorePackages)
                        if (name.indexOf(pkg) > 0) {
                            ignore = true;
                            break;
                        }
                    if (ignore)
                        continue;
                    final String className = name.substring(name.lastIndexOf('/') + 1);
                    //check ignore classes
                    for (String cls : FxTestRunner.ignoreTests)
                        if (className.indexOf(cls) > 0) {
                            ignore = true;
                            break;
                        }
                    if (ignore)
                        continue;
                    final String fqn = name.replaceAll("\\/", ".").substring(0, name.lastIndexOf('.'));
                    try {
                        testClasses.add(Class.forName(fqn));
                    } catch (ClassNotFoundException e) {
                        LOG.error("Could not find test class: " + fqn);
                    }
                }
            }
        } catch (IOException e) {
            LOG.error(e);
        }
        TestNG testng = new TestNG();
        testng.setTestClasses(testClasses.toArray(new Class[testClasses.size()]));
        // skip.ear groups have to be excluded, else tests that include these will be skipped as well (like ContainerBootstrap which is needed)
        testng.setExcludedGroups("skip.ear");
        System.setProperty("flexive.tests.ear", "1");
        TestListenerAdapter tla = new TestListenerAdapter();
        testng.addListener(tla);

        if (callback != null) {
            FxTestRunnerListener trl = new FxTestRunnerListener(callback);
            testng.addListener(trl);
        }

        testng.setThreadCount(4);
        testng.setVerbose(0);
        testng.setDefaultSuiteName("EARTestSuite");
        testng.setOutputDirectory(outputPath);
        if (callback != null)
            callback.resetTestInfo();
        try {
            testng.run();
        } catch (Exception e) {
            LOG.error(e);
            new FxFacesMsgErr("TestRunner.err.testNG", e.getMessage()).addToContext();
        }
        if (callback != null) {
            callback.setRunning(false);
            callback.setResultsAvailable(true);
        }
    } finally {
        synchronized (lock) {
            testInProgress = false;
        }
    }
}

From source file:bs.java

private static void loadable(String filename) {
    File file = new File(filename);

    JarInputStream is;//  w  w  w .  jav a2  s . com
    try {
        ClassLoader loader = URLClassLoader.newInstance(new URL[] { file.toURI().toURL() });
        is = new JarInputStream(new FileInputStream(file));
        JarEntry entry;
        while ((entry = is.getNextJarEntry()) != null) {
            if (entry.getName().endsWith(".class") && !entry.getName().contains("/")) {
                Class<?> cls = Class.forName(FilenameUtils.removeExtension(entry.getName()), false, loader);
                for (Class<?> i : cls.getInterfaces()) {
                    if (i.equals(Loadable.class)) {
                        Loadable l = (Loadable) cls.newInstance();
                        Bs.addModule(l);
                    }
                }
            }
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:org.chtijbug.drools.platform.runtime.utils.Xsd2JarTransformerTestCase.java

@Test
public void should_get_all_expected_entries_from_generated_jar_file() throws IOException {
    Xsd2JarTransformer toTest = new Xsd2JarTransformer();

    URL xsdFile = this.getClass().getResource("/model.xsd");

    InputStream modelJarStream = toTest.transformXsd2Jar("org.pymma.drools", new File(xsdFile.getFile()));

    File modelJarFile = File.createTempFile("model", ".jar");
    IOUtils.copy(modelJarStream, FileUtils.openOutputStream(modelJarFile));

    JarInputStream inputStream = new JarInputStream(FileUtils.openInputStream(modelJarFile));
    assertThat(inputStream.getManifest()).isNotNull();

    List<ZipEntry> allJarEntries = new ArrayList<ZipEntry>();

    ZipEntry entry;/* ww w .  jav  a  2  s  .c o  m*/
    while ((entry = inputStream.getNextEntry()) != null)
        allJarEntries.add(entry);

    assertThat(allJarEntries).hasSize(5);
}

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

/**
 * Read the manifest for a given stream. The stream will be wrapped in a
 * JarInputStream and closed after the manifest was read.
 * // w w  w  . j av a 2  s.  co m
 * @param stream
 * @return
 */
public static Manifest getManifest(InputStream stream) {
    JarInputStream myStream = null;
    try {
        myStream = new JarInputStream(stream);
        return myStream.getManifest();
    } catch (IOException ioex) {
        // just ignore it
    } finally {
        closeStream(myStream);
    }

    // return (man != null ? man : new Manifest());
    return null;
}

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

private void loadSubJars(byte[] byteArray) {
    try {//w w  w  .  j  a v a 2s  .  co  m
        JarInputStream jarInputStream = new JarInputStream(new ByteArrayInputStream(byteArray));
        JarEntry entry = jarInputStream.getNextJarEntry();
        while (entry != null) {
            addDataToMap(jarInputStream, entry);
            entry = jarInputStream.getNextJarEntry();
        }
        jarInputStream.close();
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}

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

@Test
public void testExistingManifest() throws Exception {
    File dir = GenericTestUtils.getTestDir(TestJarFinder.class.getName() + "-testExistingManifest");
    delete(dir);/*from w ww .j  a  va 2  s . c o  m*/
    dir.mkdirs();

    File metaInfDir = new File(dir, "META-INF");
    metaInfDir.mkdirs();
    File manifestFile = new File(metaInfDir, "MANIFEST.MF");
    Manifest manifest = new Manifest();
    OutputStream os = new FileOutputStream(manifestFile);
    manifest.write(os);
    os.close();

    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:org.jahia.utils.maven.plugin.support.MavenAetherHelperUtils.java

public static Set<PackageInfo> getJarPackages(File jarFile, boolean optionalJar, String version,
        ParsingContext parsingContext, Log log) {
    JarInputStream jarInputStream = null;
    Set<PackageInfo> packageInfos = new LinkedHashSet<PackageInfo>();
    if (jarFile == null) {
        log.warn("File is null !");
        return packageInfos;
    }/*from   www.java 2  s . co m*/
    if (!jarFile.exists()) {
        log.warn("File " + jarFile + " does not exist !");
        return packageInfos;
    }
    log.debug("Scanning JAR " + jarFile + "...");
    try {
        jarInputStream = new JarInputStream(new FileInputStream(jarFile));
        JarEntry jarEntry = null;
        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
            String jarPackageName = jarEntry.getName().replaceAll("/", ".");
            if (jarPackageName.endsWith(".")) {
                jarPackageName = jarPackageName.substring(0, jarPackageName.length() - 1);
            }
            if (jarPackageName.startsWith("META-INF") || jarPackageName.startsWith("WEB-INF")
                    || jarPackageName.startsWith("OSGI-INF")) {
                continue;
            }
            packageInfos.addAll(PackageUtils.getPackagesFromClass(jarPackageName, optionalJar, version,
                    jarFile.getCanonicalPath(), parsingContext));
        }
    } catch (IOException e) {
        log.error(e);
        ;
    } finally {
        IOUtils.closeQuietly(jarInputStream);
    }
    return packageInfos;
}

From source file:com.threecrickets.jygments.grammar.Lexer.java

public static Lexer getForFileName(String fileName) throws ResolutionException {
    if (lexerMap.isEmpty()) {
        try {/*from   ww w  .java 2s.  co m*/
            File jarFile = new File(Jygments.class.getProtectionDomain().getCodeSource().getLocation().toURI());
            JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile));
            try {
                for (JarEntry jarEntry = jarInputStream
                        .getNextJarEntry(); jarEntry != null; jarEntry = jarInputStream.getNextJarEntry()) {
                    if (jarEntry.getName().endsWith(".json")) {
                        String lexerName = jarEntry.getName();
                        // strip off the .json
                        lexerName = lexerName.substring(0, lexerName.length() - 5);
                        Lexer lexer = Lexer.getByFullName(lexerName);
                        for (String filename : lexer.filenames)
                            if (filename.startsWith("*."))
                                lexerMap.put(filename.substring(filename.lastIndexOf('.')), lexer);
                    }
                }
            } finally {
                jarInputStream.close();
            }
        } catch (URISyntaxException x) {
            throw new ResolutionException(x);
        } catch (FileNotFoundException x) {
            throw new ResolutionException(x);
        } catch (IOException x) {
            throw new ResolutionException(x);
        }
    }

    return lexerMap.get(fileName.substring(fileName.lastIndexOf('.')));
}

From source file:streaming.common.HdfsClassLoader.java

/**
 * Search for the class in the configured jar file stored in HDFS.
 *
 * {@inheritDoc}/*  ww  w  . ja v  a2 s .  c om*/
 */
@Override
public Class findClass(String className) throws ClassNotFoundException {
    String classPath = convertNameToPath(className);
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Searching for class %s (%s) in path %s", className, classPath, this.jar));
    }
    FileSystem fs = null;
    JarInputStream jarIn = null;
    try {
        fs = this.jar.getFileSystem(this.configuration);
        jarIn = new JarInputStream(fs.open(this.jar));
        JarEntry currentEntry = null;
        while ((currentEntry = jarIn.getNextJarEntry()) != null) {
            if (LOG.isTraceEnabled()) {
                LOG.trace(String.format("Comparing %s to entry %s", classPath, currentEntry.getName()));
            }
            if (currentEntry.getName().equals(classPath)) {
                byte[] classBytes = readEntry(jarIn);
                return defineClass(className, classBytes, 0, classBytes.length);
            }
        }
    } catch (IOException ioe) {
        throw new ClassNotFoundException("Unable to find " + className + " in path " + this.jar, ioe);
    } finally {
        closeQuietly(jarIn);
        // While you would think it would be prudent to close the filesystem that you opened,
        // it turns out that this filesystem is shared with HBase, so when you close this one,
        // it becomes closed for HBase, too.  Therefore, there is no call to closeQuietly(fs);
    }
    throw new ClassNotFoundException("Unable to find " + className + " in path " + this.jar);
}

From source file:lineage2.gameserver.scripts.Scripts.java

/**
 * Method load.//from w  w w  .  j a  va  2s  .  co m
 */
private void load() {
    _log.info("Scripts: Loading...");

    List<Class<?>> classes = new ArrayList<>();

    boolean result = false;

    File f = new File("../libs/lineage2-scripts.jar");
    if (f.exists()) {
        JarInputStream stream = null;
        try {
            stream = new JarInputStream(new FileInputStream(f));
            JarEntry entry = null;
            while ((entry = stream.getNextJarEntry()) != null) {
                if (entry.getName().contains(ClassUtils.INNER_CLASS_SEPARATOR)
                        || !entry.getName().endsWith(".class")) {
                    continue;
                }

                String name = entry.getName().replace(".class", "").replace("/", ".");

                Class<?> clazz = Class.forName(name);
                if (Modifier.isAbstract(clazz.getModifiers())) {
                    continue;
                }
                classes.add(clazz);
            }
            result = true;
        } catch (Exception e) {
            _log.error("Fail to load scripts.jar!", e);
            classes.clear();
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    if (!result) {
        result = load(classes, "");
    }

    if (!result) {
        _log.error("Scripts: Failed loading scripts!");
        Runtime.getRuntime().exit(0);
        return;
    }

    _log.info("Scripts: Loaded " + classes.size() + " classes.");

    Class<?> clazz;
    for (int i = 0; i < classes.size(); i++) {
        clazz = classes.get(i);
        _classes.put(clazz.getName(), clazz);
    }
}