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.apache.pluto.util.assemble.ear.ComplexEarAssemblerTest.java

protected void validateEarAssembly(File earFile) throws Exception {
    assertTrue("EAR archive [" + earFile.getAbsolutePath() + "] cannot be found or cannot be read",
            earFile.exists() && earFile.canRead());

    PortletAppDescriptorService portletSvc = new PortletAppDescriptorServiceImpl();
    PortletApplicationDefinition portletApp = null;

    PlutoWebXmlRewriter webXmlRewriter = null;

    List<String> portletWarEntries = Arrays.asList(testWarEntryNames);
    List<String> unassembledWarEntries = Arrays.asList(unassembledWarEntryName);
    List<String> testPortlets = Arrays.asList(testPortletNames);

    int earEntryCount = 0;
    int totalWarEntryCount = 0;
    int portletWarEntryCount = 0;

    JarInputStream earIn = new JarInputStream(new FileInputStream(earFile));

    JarEntry earEntry;/*from  w w w  .ja  va 2 s  . c  o  m*/
    JarEntry warEntry;

    while ((earEntry = earIn.getNextJarEntry()) != null) {
        earEntryCount++;

        if (earEntry.getName().endsWith(".war")) {
            totalWarEntryCount++;
            JarInputStream warIn = new JarInputStream(earIn);

            while ((warEntry = warIn.getNextJarEntry()) != null) {
                if (Assembler.PORTLET_XML.equals(warEntry.getName())) {
                    portletApp = portletSvc.read("test", "/test",
                            new ByteArrayInputStream(IOUtils.toByteArray(warIn)));
                }
                if (Assembler.SERVLET_XML.equals(warEntry.getName())) {
                    webXmlRewriter = new PlutoWebXmlRewriter(
                            new ByteArrayInputStream(IOUtils.toByteArray(warIn)));
                }
            }

            if (portletWarEntries.contains(earEntry.getName())) {
                portletWarEntryCount++;
                assertNotNull("WAR archive did not contain a portlet.xml", portletApp);
                assertNotNull("WAR archive did not contain a servlet.xml", webXmlRewriter);
                assertTrue("WAR archive did not contain any servlets", webXmlRewriter.hasServlets());
                assertTrue("WAR archive did not contain any servlet mappings",
                        webXmlRewriter.hasServletMappings());
                assertTrue("WAR archive did not contain any portlets", portletApp.getPortlets().size() > 0);

                for (Iterator<? extends PortletDefinition> iter = portletApp.getPortlets().iterator(); iter
                        .hasNext();) {
                    PortletDefinition portlet = iter.next();
                    if (!testPortlets.contains(portlet.getPortletName())) {
                        fail("Unexpected test portlet name encountered: [" + portlet.getPortletName() + "]");
                    }
                    String servletClassName = webXmlRewriter.getServletClass(portlet.getPortletName());
                    assertNotNull("web.xml does not contain assembly for test portlet", servletClassName);
                    assertEquals("web.xml does not contain correct dispatch servet",
                            Assembler.DISPATCH_SERVLET_CLASS, servletClassName);
                }

            }

            webXmlRewriter = null;
            portletApp = null;

        }

    }

    assertTrue("EAR archive did not contain any entries", earEntryCount > 0);
    assertEquals("EAR archive did not contain the expected test war entries.", portletWarEntries.size(),
            portletWarEntryCount);
    assertEquals("WAR archive did not contain the correct number of entries",
            portletWarEntries.size() + unassembledWarEntries.size(), totalWarEntryCount);

}

From source file:org.vafer.jdependency.Clazzpath.java

public ClazzpathUnit addClazzpathUnit(final InputStream pInputStream, final String pId) throws IOException {
    final JarInputStream inputStream = new JarInputStream(pInputStream);
    try {// w  ww  . j a  v  a  2s  . co m
        final JarEntry[] entryHolder = new JarEntry[1];

        return addClazzpathUnit(new Iterable<Resource>() {

            public Iterator<Resource> iterator() {
                return new Iterator<Resource>() {

                    public boolean hasNext() {
                        try {
                            do {
                                entryHolder[0] = inputStream.getNextJarEntry();
                            } while (entryHolder[0] != null && !Resource.isValidName(entryHolder[0].getName()));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                        return entryHolder[0] != null;
                    }

                    public Resource next() {
                        return new Resource(entryHolder[0].getName()) {

                            @Override
                            InputStream getInputStream() {
                                return inputStream;
                            }
                        };
                    }

                    public void remove() {
                        throw new UnsupportedOperationException();
                    }

                };
            }
        }, pId, false);
    } finally {
        inputStream.close();
    }
}

From source file:org.apache.hadoop.hbase.mapreduce.hadoopbackport.TestJarFinder.java

@Test
public void testNoManifest() throws Exception {
    File dir = new File(System.getProperty("test.build.dir", "target/test-dir"),
            TestJarFinder.class.getName() + "-testNoManifest");
    delete(dir);/*ww  w. j av a  2  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.thoughtworks.go.domain.materials.tfs.TfsSDKCommandBuilder.java

private void explodeNatives() throws IOException {
    URL urlOfJar = getJarURL();/*from  w  w w.ja  va  2s.  com*/
    LOGGER.info("[TFS SDK] Exploding natives from {} to folder {}", urlOfJar.toString(),
            tempFolder.getAbsolutePath());
    JarInputStream jarStream = new JarInputStream(urlOfJar.openStream());
    JarEntry entry;
    while ((entry = jarStream.getNextJarEntry()) != null) {
        if (!entry.isDirectory() && entry.getName().startsWith("tfssdk/native/")) {
            File newFile = new File(tempFolder, entry.getName());
            newFile.getParentFile().mkdirs();
            LOGGER.info("[TFS SDK] Extract {} -> {}", entry.getName(), newFile);
            try (OutputStream fos = new FileOutputStream(newFile)) {
                IOUtils.copy(jarStream, fos);
            }
        }
    }
}

From source file:com.speed.ob.Obfuscator.java

public Obfuscator(final Config config) {
    transforms = new LinkedList<>();
    store = new ClassStore();
    this.config = config;
    //set up logging
    this.LOGGER = Logger.getLogger(this.getClass().getName());
    LOGGER.info("Ob2 is starting");
    String logLvl = config.get("Obfuscator.logging");
    String logDir = config.get("Obfuscator.log_dir");
    level = parseLevel(logLvl);//from  ww  w .j  av  a  2 s.  c o  m
    LOGGER.info("Logger level set to " + level.getName());
    Logger topLevel = Logger.getLogger("");
    topLevel.setLevel(level);
    File logs = new File(logDir);
    if (!logs.exists()) {
        if (!logs.mkdir())
            Logger.getLogger(this.getClass().getName()).warning("Could not create logging directory");
    }
    try {
        if (logs.exists()) {
            fHandler = new FileHandler(logs.getAbsolutePath() + File.separator + "ob%g.log");
            topLevel.addHandler(fHandler);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    for (Handler handler : topLevel.getHandlers()) {
        handler.setLevel(level);
    }
    //populate transforms
    LOGGER.info("Configuring Ob");
    LOGGER.fine("Parsing config");
    if (config.getBoolean("Obfuscator.all_transforms")) {
        LOGGER.fine("Adding all transforms");
        transforms.add(ClassNameTransform.class);
    } else {
        if (config.getBoolean("Obfuscator.classname_obfuscation")) {
            LOGGER.fine("Adding class name transform");
            transforms.add(ClassNameTransform.class);
        }
        if (config.getBoolean("Obfuscator.controlflow_obfuscation")) {
            LOGGER.fine("Control flow obfuscation not added, transform does not exist");
        }
        if (config.getBoolean("Obfuscator.string_obfuscation")) {
            LOGGER.fine("String obfuscation not added, transform does not exist");

        }
        if (config.getBoolean("Obfuscator.fieldname_transforms")) {
            LOGGER.fine("Field name obfuscation not added, transform does not exist");

        }
        if (config.getBoolean("Obfuscator.methodname_transforms")) {
            LOGGER.fine("Method name obfuscation not added, transform does not exist");

        }
    }
    LOGGER.info("Loaded " + transforms.size() + " transforms");
    String inputFile = config.get("Obfuscator.input");
    LOGGER.fine("Checking input file(s) and output directory");
    String outFile = config.get("Obfuscator.out_dir");
    out = new File(outFile);
    if (inputFile == null || inputFile.isEmpty()) {
        LOGGER.severe("Input file not specified in config");
        throw new RuntimeException("Input file not specified");
    } else {
        in = new File(inputFile);
        if (!in.exists()) {
            LOGGER.severe("Input file not found");
            throw new RuntimeException("Input file not found");
        }
        LOGGER.fine("Attempting to initialise classes");
        if (in.isDirectory()) {
            try {
                store.init(in.listFiles(), false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (in.getName().endsWith(".class")) {
            try {
                store.init(new File[] { in }, false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (in.getName().endsWith(".jar")) {
            try {
                JarInputStream in = new JarInputStream(new FileInputStream(this.in));
                store.init(in, out, this.in);
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LOGGER.info("Loaded " + store.nodes().size() + " classes");
    }
    if (!out.exists()) {
        LOGGER.fine("Attempting to make output directory");
        if (!out.mkdir()) {
            LOGGER.severe("Could not make output directory");
            throw new RuntimeException("Could not create output dir: " + out.getAbsolutePath());
        }
    } else if (!out.isDirectory()) {
        LOGGER.severe("Output directory is a file");
        throw new RuntimeException(out.getName() + " is not a directory, cannot output there");
    } else {
        if (!out.canWrite()) {
            LOGGER.severe("Cannot write to output directory");
            throw new RuntimeException("Cannot write to output dir: " + out.getAbsolutePath());
        }
    }

}

From source file:org.rhq.core.clientapi.descriptor.PluginTransformer.java

private String getVersionFromPluginJarManifest(URL pluginJarUrl) throws IOException {
    JarInputStream jarInputStream = new JarInputStream(pluginJarUrl.openStream());
    Manifest manifest = jarInputStream.getManifest();
    if (manifest == null) {
        // BZ 682116 (ips, 03/25/11): The manifest file is not in the standard place as the 2nd entry of the JAR,
        // but we want to be flexible and support JARs that have a manifest file somewhere else, so scan the entire
        // JAR for one.
        JarEntry jarEntry;/*from   w  ww . j a  v  a  2  s . co  m*/
        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
            if (JarFile.MANIFEST_NAME.equalsIgnoreCase(jarEntry.getName())) {
                manifest = new Manifest(jarInputStream);
                break;
            }
        }
    }
    try {
        jarInputStream.close();
    } catch (IOException e) {
        LOG.error("Failed to close plugin jar input stream for plugin jar [" + pluginJarUrl + "].", e);
    }
    if (manifest != null) {
        Attributes attributes = manifest.getMainAttributes();
        return attributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
    } else {
        return null;
    }
}

From source file:com.egreen.tesla.server.api.component.Component.java

private void init() throws FileNotFoundException, IOException, ConfigurationException {

    //Init url//from w  w w.j a v a 2s .com
    this.jarFile = new URL("jar", "", "file:" + file.getAbsolutePath() + "!/");

    final FileInputStream fileInputStream = new FileInputStream(file);
    JarInputStream jarFile = new JarInputStream(fileInputStream);
    JarFile jf = new JarFile(file);

    setConfiguraton(jf);//Configuration load

    jf.getEntry(TESLAR_WIDGET_MAINIFIESTXML);

    JarEntry jarEntry;

    while (true) {
        jarEntry = jarFile.getNextJarEntry();
        if (jarEntry == null) {
            break;
        }
        if (jarEntry.getName().endsWith(".class") && !jarEntry.getName().contains("$")) {
            final String JarNameClass = jarEntry.getName().replaceAll("/", "\\.");
            String className = JarNameClass.replace(".class", "");
            LOGGER.info(className);
            controllerClassMapper.put(className, className);

        } else if (jarEntry.getName().startsWith("webapp")) {
            final String JarNameClass = jarEntry.getName();
            LOGGER.info(JarNameClass);
            saveEntry(jf.getInputStream(jarEntry), JarNameClass);
        }
    }
}

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   w  w w.ja v a2 s  .  c o m*/
    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:se.crisp.codekvast.support.web.config.WebjarVersionFilter.java

private void analyzeJar(URL jarUrl, Pattern pattern) throws IOException {
    // Look for entries that match the pattern...
    JarInputStream inputStream = new JarInputStream(jarUrl.openStream());

    JarEntry jarEntry = inputStream.getNextJarEntry();
    while (jarEntry != null) {
        log.trace("Considering {}", jarEntry);

        Matcher matcher = pattern.matcher(jarEntry.getName());
        if (matcher.matches()) {
            String key = matcher.group(1);
            String value = matcher.group(2);
            versions.put(key, value);/* w  w w  .  j a  v  a2s  .c  om*/
            log.debug("{} is a webjar, adding {}={} to map", basename(jarUrl.getPath()), key, value);
            return;
        }
        jarEntry = inputStream.getNextJarEntry();
    }
}

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

/**
 * Validate the given jar is valid maven archetype jar
 * //from  ww  w. j a  v  a2s.c o m
 * @return
 * @throws PhrescoException
 */
public static boolean validateArchetypeJar(InputStream inputJar) throws PhrescoException {
    try {
        jarInputStream = new JarInputStream(inputJar);
        JarEntry nextJarEntry = jarInputStream.getNextJarEntry();
        while ((nextJarEntry = jarInputStream.getNextJarEntry()) != null) {
            if (nextJarEntry.getName().equals(ServerConstants.ARCHETYPE_METADATA_FILE)
                    || nextJarEntry.getName().equals(ServerConstants.ARCHETYPE_FILE)) {
                return true;
            }
        }
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return false;
}