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

public static String readAll(URL url) throws IOException {
    Reader reader = null;//from   w  ww . ja  v a  2 s  . c  om
    JarFile jarFile = null;
    try {
        if (url.getProtocol().equalsIgnoreCase("jar")) {
            // url.openStream() locks the jar file and does not release the lock even after the stream is closed.
            // This problem is avoided by using JarFile APIs.
            File file = new File(url.getFile().substring(5, url.getFile().indexOf("!/")));
            String path = url.getFile().substring(url.getFile().indexOf("!/") + 2);
            jarFile = new JarFile(file);
            JarEntry jarEntry = jarFile.getJarEntry(path);
            if (jarEntry != null) {
                reader = new InputStreamReader(jarFile.getInputStream(jarEntry));
            } else {
                throw new FileNotFoundException("JarEntry " + path + " not found in " + file);
            }
        } else {
            reader = new InputStreamReader(url.openStream());
        }
        char[] buffer = new char[4000];
        StringBuffer out = new StringBuffer();
        for (int count = reader.read(buffer); count >= 0; count = reader.read(buffer)) {
            out.append(buffer, 0, count);
        }
        return out.toString();
    } finally {
        close(reader);
        close(jarFile);
    }
}

From source file:eu.stratosphere.yarn.Client.java

private File generateDefaultConf(Path localJarPath) throws IOException, FileNotFoundException {
    JarFile jar = null;
    try {// www.  j  a  va2 s  . co  m
        jar = new JarFile(localJarPath.toUri().getPath());
    } catch (FileNotFoundException fne) {
        LOG.fatal("Unable to access jar file. Specify jar file or configuration file.", fne);
        System.exit(1);
    }
    InputStream confStream = jar.getInputStream(jar.getEntry("stratosphere-conf.yaml"));

    if (confStream == null) {
        LOG.warn("Given jar file does not contain yaml conf.");
        confStream = this.getClass().getResourceAsStream("stratosphere-conf.yaml");
        if (confStream == null) {
            throw new RuntimeException("Unable to find stratosphere-conf in jar file");
        }
    }
    File outFile = new File("stratosphere-conf.yaml");
    if (outFile.exists()) {
        throw new RuntimeException("File unexpectedly exists");
    }
    FileOutputStream outputStream = new FileOutputStream(outFile);
    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = confStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }
    confStream.close();
    outputStream.close();
    jar.close();
    return outFile;
}

From source file:org.compass.core.config.binding.AbstractInputStreamMappingBinding.java

public boolean addJar(File jar) throws ConfigurationException, MappingException {
    final JarFile jarFile;
    try {//  w  w w.j a  va2 s .c om
        jarFile = new JarFile(jar);
    } catch (IOException ioe) {
        throw new ConfigurationException("Could not configure datastore from jar [" + jar.getName() + "]", ioe);
    }

    boolean addedAtLeastOne = false;
    Enumeration jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) jarEntries.nextElement();
        for (String suffix : getSuffixes()) {
            if (ze.getName().endsWith(suffix)) {
                try {
                    boolean retVal = internalAddInputStream(jarFile.getInputStream(ze), ze.getName(), true);
                    if (retVal) {
                        addedAtLeastOne = true;
                    }
                } catch (ConfigurationException me) {
                    throw me;
                } catch (Exception e) {
                    throw new ConfigurationException(
                            "Could not configure datastore from jar [" + jar.getAbsolutePath() + "]", e);
                }
            }
        }
    }
    return addedAtLeastOne;
}

From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java

/**
 * Gets the EAR descriptor from the {@link JarFile}.
 * /*from www . j av  a2  s.c om*/
 * @param earFile The EAR to get the descriptor from.
 * @return The descriptor DOM for the EAR.
 * @throws IOException If there is any problem reading the descriptor from the EAR.
 */
protected Document getDescriptorDom(final JarFile earFile) throws MojoFailureException {
    final ZipEntry descriptorEntry = earFile.getEntry(DESCRIPTOR_PATH);
    if (descriptorEntry == null) {
        throw new IllegalArgumentException(
                "JarFile '" + earFile + "' does not contain a descriptor at '" + DESCRIPTOR_PATH + "'");
    }

    InputStream descriptorStream = null;
    try {
        descriptorStream = earFile.getInputStream(descriptorEntry);

        final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();

        final DocumentBuilder docBuilder;
        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException pce) {
            throw new RuntimeException("Failed to create DocumentBuilder to parse EAR descriptor.", pce);
        }

        docBuilder.setEntityResolver(new ClasspathEntityResolver(this.getLogger()));

        final Document descriptorDom;
        try {
            descriptorDom = docBuilder.parse(descriptorStream);
            return descriptorDom;
        } catch (SAXException e) {
            throw new MojoFailureException(
                    "Failed to parse descriptor '" + DESCRIPTOR_PATH + "' from EAR '" + earFile.getName() + "'",
                    e);
        }
    } catch (IOException e) {
        throw new MojoFailureException(
                "Failed to read descriptor '" + DESCRIPTOR_PATH + "' from EAR '" + earFile.getName() + "'", e);
    } finally {
        IOUtils.closeQuietly(descriptorStream);
    }
}

From source file:org.spout.api.plugin.CommonPluginLoader.java

/**
 * @param file Plugin file object//from  w  w w . j  a v a  2  s . co  m
 * @return The current plugin's description element.
 *
 * @throws InvalidPluginException
 * @throws InvalidDescriptionFileException
 */
protected synchronized PluginDescriptionFile getDescription(File file)
        throws InvalidPluginException, InvalidDescriptionFileException {
    if (!file.exists()) {
        throw new InvalidPluginException(file.getName() + " does not exist!");
    }

    PluginDescriptionFile description = null;
    JarFile jar = null;
    InputStream in = null;
    try {
        // Spout plugin properties file
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry(YAML_SPOUT);

        // Fallback plugin properties file
        if (entry == null) {
            entry = jar.getJarEntry(YAML_OTHER);
        }

        if (entry == null) {
            throw new InvalidPluginException("Jar has no properties.yml or plugin.yml!");
        }

        in = jar.getInputStream(entry);
        description = new PluginDescriptionFile(in);
    } catch (IOException e) {
        throw new InvalidPluginException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                engine.getLogger().log(Level.WARNING, "Problem closing input stream", e);
            }
        }
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                engine.getLogger().log(Level.WARNING, "Problem closing jar input stream", e);
            }
        }
    }
    return description;
}

From source file:ffx.FFXClassLoader.java

/**
 * {@inheritDoc}//ww  w. j  a v a2s . c  o m
 *
 * Finds and defines the given class among the extension JARs given in
 * constructor, then among resources.
 */
@Override
protected Class findClass(String name) throws ClassNotFoundException {

    /*
     if (name.startsWith("com.jogamp")) {
     System.out.println(" Class requested:" + name);
     } */
    if (!extensionsLoaded) {
        loadExtensions();
    }

    // Build class file from its name
    String classFile = name.replace('.', '/') + ".class";
    InputStream classInputStream = null;
    if (extensionJars != null) {
        for (JarFile extensionJar : extensionJars) {
            JarEntry jarEntry = extensionJar.getJarEntry(classFile);
            if (jarEntry != null) {
                try {
                    classInputStream = extensionJar.getInputStream(jarEntry);
                } catch (IOException ex) {
                    throw new ClassNotFoundException("Couldn't read class " + name, ex);
                }
            }
        }
    }

    // If it's not an extension class, search if its an application
    // class that can be read from resources
    if (classInputStream == null) {
        URL url = getResource(classFile);
        if (url == null) {
            throw new ClassNotFoundException("Class " + name);
        }
        try {
            classInputStream = url.openStream();
        } catch (IOException ex) {
            throw new ClassNotFoundException("Couldn't read class " + name, ex);
        }
    }

    ByteArrayOutputStream out = null;
    BufferedInputStream in = null;
    try {
        // Read class input content to a byte array
        out = new ByteArrayOutputStream();
        in = new BufferedInputStream(classInputStream);
        byte[] buffer = new byte[8192];
        int size;
        while ((size = in.read(buffer)) != -1) {
            out.write(buffer, 0, size);
        }
        // Define class
        return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain);
    } catch (IOException ex) {
        throw new ClassNotFoundException("Class " + name, ex);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            throw new ClassNotFoundException("Class " + name, e);
        }

    }
}

From source file:net.minecraftforge.fml.common.asm.FMLSanityChecker.java

@Override
public Void call() throws Exception {
    CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
    boolean goodFML = false;
    boolean fmlIsJar = false;
    if (codeSource.getLocation().getProtocol().equals("jar")) {
        fmlIsJar = true;/*from w ww. j  a v a  2  s . c  o  m*/
        Certificate[] certificates = codeSource.getCertificates();
        if (certificates != null) {

            for (Certificate cert : certificates) {
                String fingerprint = CertificateHelper.getFingerprint(cert);
                if (fingerprint.equals(FMLFINGERPRINT)) {
                    FMLRelaunchLog.info("Found valid fingerprint for FML. Certificate fingerprint %s",
                            fingerprint);
                    goodFML = true;
                } else if (fingerprint.equals(FORGEFINGERPRINT)) {
                    FMLRelaunchLog.info(
                            "Found valid fingerprint for Minecraft Forge. Certificate fingerprint %s",
                            fingerprint);
                    goodFML = true;
                } else {
                    FMLRelaunchLog.severe("Found invalid fingerprint for FML: %s", fingerprint);
                }
            }
        }
    } else {
        goodFML = true;
    }
    // Server is not signed, so assume it's good - a deobf env is dev time so it's good too
    boolean goodMC = FMLLaunchHandler.side() == Side.SERVER || !liveEnv;
    int certCount = 0;
    try {
        Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever", false, cl);
        codeSource = cbr.getProtectionDomain().getCodeSource();
    } catch (Exception e) {
        // Probably a development environment, or the server (the server is not signed)
        goodMC = true;
    }
    JarFile mcJarFile = null;
    if (fmlIsJar && !goodMC && codeSource.getLocation().getProtocol().equals("jar")) {
        try {
            String mcPath = codeSource.getLocation().getPath().substring(5);
            mcPath = mcPath.substring(0, mcPath.lastIndexOf('!'));
            mcPath = URLDecoder.decode(mcPath, Charsets.UTF_8.name());
            mcJarFile = new JarFile(mcPath, true);
            mcJarFile.getManifest();
            JarEntry cbrEntry = mcJarFile.getJarEntry("net/minecraft/client/ClientBrandRetriever.class");
            InputStream mcJarFileInputStream = mcJarFile.getInputStream(cbrEntry);
            try {
                ByteStreams.toByteArray(mcJarFileInputStream);
            } finally {
                IOUtils.closeQuietly(mcJarFileInputStream);
            }
            Certificate[] certificates = cbrEntry.getCertificates();
            certCount = certificates != null ? certificates.length : 0;
            if (certificates != null) {

                for (Certificate cert : certificates) {
                    String fingerprint = CertificateHelper.getFingerprint(cert);
                    if (fingerprint.equals(MCFINGERPRINT)) {
                        FMLRelaunchLog.info("Found valid fingerprint for Minecraft. Certificate fingerprint %s",
                                fingerprint);
                        goodMC = true;
                    }
                }
            }
        } catch (Throwable e) {
            FMLRelaunchLog.log(Level.ERROR, e,
                    "A critical error occurred trying to read the minecraft jar file");
        } finally {
            Java6Utils.closeZipQuietly(mcJarFile);
        }
    } else {
        goodMC = true;
    }
    if (!goodMC) {
        FMLRelaunchLog.severe(
                "The minecraft jar %s appears to be corrupt! There has been CRITICAL TAMPERING WITH MINECRAFT, it is highly unlikely minecraft will work! STOP NOW, get a clean copy and try again!",
                codeSource.getLocation().getFile());
        if (!Boolean.parseBoolean(System.getProperty("fml.ignoreInvalidMinecraftCertificates", "false"))) {
            FMLRelaunchLog.severe(
                    "For your safety, FML will not launch minecraft. You will need to fetch a clean version of the minecraft jar file");
            FMLRelaunchLog.severe(
                    "Technical information: The class net.minecraft.client.ClientBrandRetriever should have been associated with the minecraft jar file, "
                            + "and should have returned us a valid, intact minecraft jar location. This did not work. Either you have modified the minecraft jar file (if so "
                            + "run the forge installer again), or you are using a base editing jar that is changing this class (and likely others too). If you REALLY "
                            + "want to run minecraft in this configuration, add the flag -Dfml.ignoreInvalidMinecraftCertificates=true to the 'JVM settings' in your launcher profile.");
            FMLCommonHandler.instance().exitJava(1, false);
        } else {
            FMLRelaunchLog.severe(
                    "FML has been ordered to ignore the invalid or missing minecraft certificate. This is very likely to cause a problem!");
            FMLRelaunchLog.severe(
                    "Technical information: ClientBrandRetriever was at %s, there were %d certificates for it",
                    codeSource.getLocation(), certCount);
        }
    }
    if (!goodFML) {
        FMLRelaunchLog.severe("FML appears to be missing any signature data. This is not a good thing");
    }
    return null;
}

From source file:org.wisdom.resources.WebJarDeployer.java

private FileWebJarLib expand(DetectedWebJar lib, JarFile jar) {
    File out = new File(cache, lib.id);
    Enumeration<? extends ZipEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (entry.getName().startsWith(WebJarController.WEBJAR_LOCATION) && !entry.isDirectory()) {
            // Compute destination.
            File output = new File(out, entry.getName().substring(WebJarController.WEBJAR_LOCATION.length()));
            InputStream stream = null;
            try {
                stream = jar.getInputStream(entry);
                boolean made = output.getParentFile().mkdirs();
                LOGGER.debug("{} directory created : {} ", output.getParentFile().getAbsolutePath(), made);
                FileUtils.copyInputStreamToFile(stream, output);
            } catch (IOException e) {
                LOGGER.error("Cannot unpack " + entry.getName() + " from " + lib.file.getName(), e);
                return null;
            } finally {
                IOUtils.closeQuietly(stream);
            }//from   ww w  .  j a  va  2  s  .co  m
        }
    }
    File root = new File(out, lib.name + "/" + lib.version);
    return new FileWebJarLib(lib.name, lib.version, root, lib.file.getName());
}

From source file:com.chiorichan.plugin.loader.JavaPluginLoader.java

public PluginDescriptionFile getPluginDescription(File file) throws InvalidDescriptionException {
    Validate.notNull(file, "File cannot be null");

    JarFile jar = null;
    InputStream stream = null;/* w w w . j  a  v a  2s .com*/

    try {
        jar = new JarFile(file);
        JarEntry entry = jar.getJarEntry("plugin.yaml");

        if (entry == null)
            entry = jar.getJarEntry("plugin.yml");

        if (entry == null) {
            throw new InvalidDescriptionException(
                    new FileNotFoundException("Jar does not contain plugin.yaml"));
        }

        stream = jar.getInputStream(entry);

        return new PluginDescriptionFile(stream);

    } catch (IOException ex) {
        throw new InvalidDescriptionException(ex);
    } catch (YAMLException ex) {
        throw new InvalidDescriptionException(ex);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
            }
        }
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:streamflow.service.FrameworkService.java

public String loadFrameworkComponentIcon(ComponentConfig componentConfig, File frameworkFile) {
    String iconId = null;/*from  w w w.  jav a2 s. com*/
    byte[] iconData = null;

    if (componentConfig.getIcon() != null) {
        try {
            JarFile frameworkJarFile = new JarFile(frameworkFile);

            JarEntry iconEntry = frameworkJarFile.getJarEntry(componentConfig.getIcon());
            if (iconEntry != null) {
                iconData = IOUtils.toByteArray(frameworkJarFile.getInputStream(iconEntry));
            }
        } catch (IOException ex) {
            LOG.error("Error occurred while loading the provided component icon: ", ex);
        }
    }

    if (iconData == null) {
        try {
            if (componentConfig.getType().equalsIgnoreCase(Component.STORM_SPOUT_TYPE)) {
                iconData = IOUtils.toByteArray(Thread.currentThread().getContextClassLoader()
                        .getResourceAsStream("icons/storm-spout.png"));
            } else if (componentConfig.getType().equalsIgnoreCase(Component.STORM_BOLT_TYPE)) {
                iconData = IOUtils.toByteArray(Thread.currentThread().getContextClassLoader()
                        .getResourceAsStream("icons/storm-bolt.png"));
            } else {
                iconData = IOUtils.toByteArray(Thread.currentThread().getContextClassLoader()
                        .getResourceAsStream("icons/storm-trident.png"));
            }
        } catch (IOException ex) {
            LOG.error("Error occurred while loading the default component icon: ", ex);
        }
    }

    if (iconData != null) {
        FileInfo iconFile = new FileInfo();
        iconFile.setFileName(iconFile.getFileName());
        iconFile.setFileType("image/png");
        iconFile.setFileSize(iconData.length);
        iconFile.setContentHash(DigestUtils.md5Hex(iconData));

        iconFile = fileService.saveFile(iconFile, iconData);

        iconId = iconFile.getId();
    }

    return iconId;
}