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:org.openmrs.module.moduledistro.api.impl.ModuleDistroServiceImpl.java

/**
  * Populates the moduleId, moduleVersion, action, and skipVersion fields on candidate
  * //from w ww  .  j a  v a 2 s. co  m
  * @param candidate
 * @throws IOException
 *
 * @should read the id and version from config.xml 
  */
public void populateFields(UploadedModule candidate) throws IOException {
    JarFile jar = new JarFile(candidate.getData());
    ZipEntry entry = jar.getEntry("config.xml");
    if (entry == null) {
        throw new IOException("Cannot find config.xml");
    }
    StringWriter sw = new StringWriter();
    IOUtils.copy(jar.getInputStream(entry), sw);
    String configXml = sw.toString();

    String moduleId = null;
    {
        Matcher matcher = Pattern.compile("<id>(.+?)</id>").matcher(configXml);
        if (!matcher.find())
            throw new IOException("Cannot find <id>...</id> in config.xml");
        moduleId = matcher.group(1).trim();
    }

    String moduleVersion = null;
    {
        Matcher matcher = Pattern.compile("<version>(.+?)</version>").matcher(configXml);
        if (!matcher.find())
            throw new IOException("Cannot find <version>...</version> in config.xml");
        moduleVersion = matcher.group(1).trim();
    }

    candidate.setModuleId(moduleId);
    candidate.setModuleVersion(moduleVersion);

    Module existing = ModuleFactory.getModuleById(candidate.getModuleId());
    if (existing == null) {
        candidate.setAction(Action.INSTALL);
        return;
    } else { // there's an existing module
        candidate.setExisting(existing);

        if (shouldInstallNewVersion(candidate.getModuleVersion(), existing.getVersion())) {
            candidate.setAction(Action.UPGRADE);
        } else {
            candidate.setAction(Action.SKIP);
            candidate.setSkipReason(
                    "an equivalent or newer version is already installed: (" + existing.getVersion() + ")");
        }

        // if the module is up-to-date, but not running, we need to start it 
        if (!existing.isStarted() && candidate.getAction().equals(Action.SKIP)) {
            candidate.setAction(Action.START);
        }
    }

}

From source file:org.rhq.enterprise.server.core.AgentManagerBean.java

@ExcludeDefaultInterceptors
public File getAgentUpdateVersionFile() throws Exception {
    File agentDownloadDir = getAgentDownloadDir();
    File versionFile = new File(agentDownloadDir, "rhq-server-agent-versions.properties");
    if (!versionFile.exists()) {
        // we do not have the version properties file yet, let's extract some info and create one
        StringBuilder serverVersionInfo = new StringBuilder();

        // first, get the server version info (by asking our server for the info)
        CoreServerMBean coreServer = LookupUtil.getCoreServer();
        serverVersionInfo.append(RHQ_SERVER_VERSION + '=').append(coreServer.getVersion()).append('\n');
        serverVersionInfo.append(RHQ_SERVER_BUILD_NUMBER + '=').append(coreServer.getBuildNumber())
                .append('\n');

        // calculate the MD5 of the agent update binary file
        File binaryFile = getAgentUpdateBinaryFile();
        String md5Property = RHQ_AGENT_LATEST_MD5 + '=' + MessageDigestGenerator.getDigestString(binaryFile)
                + '\n';

        // second, get the agent version info (by peeking into the agent update binary jar)
        JarFile binaryJarFile = new JarFile(binaryFile);
        try {//from  w w  w. jav  a  2 s  .com
            JarEntry binaryJarFileEntry = binaryJarFile.getJarEntry("rhq-agent-update-version.properties");
            InputStream binaryJarFileEntryStream = binaryJarFile.getInputStream(binaryJarFileEntry);

            // now write the server and agent version info in our internal version file our servlet will use
            FileOutputStream versionFileOutputStream = new FileOutputStream(versionFile);
            try {
                versionFileOutputStream.write(serverVersionInfo.toString().getBytes());
                versionFileOutputStream.write(md5Property.getBytes());
                StreamUtil.copy(binaryJarFileEntryStream, versionFileOutputStream, false);
            } finally {
                try {
                    versionFileOutputStream.close();
                } catch (Exception e) {
                }
                try {
                    binaryJarFileEntryStream.close();
                } catch (Exception e) {
                }
            }
        } finally {
            binaryJarFile.close();
        }
    }

    return versionFile;
}

From source file:org.ut.biolab.medsavant.client.plugin.AppController.java

public AppDescriptor getDescriptorFromFile(File f) throws PluginVersionException {
    XMLStreamReader reader;/*from  w w w.  j  ava2s  .  c  o  m*/

    try {
        JarFile jar = new JarFile(f);
        ZipEntry entry = jar.getEntry("plugin.xml");
        if (entry != null) {
            InputStream entryStream = jar.getInputStream(entry);
            reader = XMLInputFactory.newInstance().createXMLStreamReader(entryStream);
            String className = null;
            String id = null;
            String version = null;
            String sdkVersion = null;
            String name = null;
            String category = AppDescriptor.Category.UTILITY.toString();
            String currentElement = null;
            String currentText = "";
            do {
                switch (reader.next()) {
                case XMLStreamConstants.START_ELEMENT:
                    switch (readElement(reader)) {
                    case PLUGIN:
                        className = readAttribute(reader, AppDescriptor.PluginXMLAttribute.CLASS);

                        //category can be specified as an attribute or <property>.
                        category = readAttribute(reader, AppDescriptor.PluginXMLAttribute.CATEGORY);
                        break;

                    case ATTRIBUTE:
                        if ("sdk-version".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.ID))) {
                            sdkVersion = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                        }
                        break;

                    case PARAMETER:
                        if ("name".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.ID))) {
                            name = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                        }
                        break;

                    case PROPERTY:
                        if ("name".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            name = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (name == null) {
                                currentElement = "name";
                            }
                        }

                        if ("version".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            version = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (version == null) {
                                currentElement = "version";
                            }
                        }

                        if ("sdk-version"
                                .equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            sdkVersion = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (sdkVersion == null) {
                                currentElement = "sdk-version";
                            }
                        }

                        if ("category".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            category = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (category == null) {
                                currentElement = "category";
                            }
                        }

                        break;
                    }
                    break;

                case XMLStreamConstants.CHARACTERS:
                    if (reader.isWhiteSpace()) {
                        break;
                    } else if (currentElement != null) {
                        currentText += reader.getText().trim().replace("\t", "");
                    }
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    if (readElement(reader) == AppDescriptor.PluginXMLElement.PROPERTY) {
                        if (currentElement != null && currentText.length() > 0) {
                            if (currentElement.equals("name")) {
                                name = currentText;
                            } else if (currentElement.equals("sdk-version")) {
                                sdkVersion = currentText;
                            } else if (currentElement.equals("category")) {
                                category = currentText;
                            } else if (currentElement.equals("version")) {
                                version = currentText;
                            }
                        }
                        currentText = "";
                        currentElement = null;
                    }
                    break;

                case XMLStreamConstants.END_DOCUMENT:
                    reader.close();
                    reader = null;
                    break;
                }
            } while (reader != null);

            System.out.println(className + " " + name + " " + version);

            if (className != null && name != null && version != null) {
                return new AppDescriptor(className, version, name, sdkVersion, category, f);
            }
        }
    } catch (Exception x) {
        LOG.error("Error parsing plugin.xml from " + f.getAbsolutePath() + ": " + x);
    }
    throw new PluginVersionException(f.getName() + " did not contain a valid plugin");
}

From source file:com.infosupport.ellison.core.archive.ApplicationArchive.java

/**
 * Extracts a single {@link JarEntry} into the {@code destination} directory.
 * <p/>/*  ww w  . j a v a  2 s. c o  m*/
 * If {@code jarEntry} represents a directory, then a new directory is created in {@code destination}. If it is a
 * file, its {@link InputStream} is opened, and its contents are then written in {@code destination}.
 *
 * @param destination
 *     the destination directory to unpack {@code jarEntry} into. This is the "root" directory where the entire
 *     archive is unpacked into, as each {@code JarEntry}'s name points to whatever directory it should in fact be
 *     in. See {@link File#File(java.io.File, String)} to see how this is achieved.
 * @param jar
 *     the archive from which the {@code jarEntry} originates
 * @param jarEntry
 *     the {@code JarEntry} to unpack
 *
 * @throws IOException
 *     if any IO error occurred while trying to unpack a file
 */
protected void unpackJarEntry(File destination, JarFile jar, JarEntry jarEntry) throws IOException {
    byte[] ioBuffer = new byte[Constants.UNPACK_BUFFER_SIZE];
    if (jarEntry.isDirectory()) {
        File newDir = new File(destination, jarEntry.getName());
        boolean dirCreated = newDir.mkdir();
        if (dirCreated) {
            newDir.deleteOnExit();
        }
    } else {
        File outFile = new File(destination, jarEntry.getName());
        outFile.deleteOnExit();

        try (InputStream jarEntryInputStream = jar.getInputStream(jarEntry);
                OutputStream jarEntryOutputStream = new FileOutputStream(outFile)) {
            for (int readBytes = jarEntryInputStream
                    .read(ioBuffer); readBytes != -1; readBytes = jarEntryInputStream.read(ioBuffer)) {
                jarEntryOutputStream.write(ioBuffer, 0, readBytes);
            }
        }
    }
}

From source file:com.netflix.nicobar.core.persistence.PathArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleDir = rootDir.resolve(moduleId.toString());
    if (Files.exists(moduleDir)) {
        FileUtils.deleteDirectory(moduleDir.toFile());
    }/*from   ww w. j  av a2 s. c o m*/
    JarFile jarFile;
    try {
        jarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    try {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            Path entryName = moduleDir.resolve(jarEntry.getName());
            if (jarEntry.isDirectory()) {
                Files.createDirectories(entryName);
            } else {
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                try {
                    Files.copy(inputStream, entryName);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(jarFile);
    }
    // write the module spec
    String serialized = moduleSpecSerializer.serialize(moduleSpec);
    Files.write(moduleDir.resolve(moduleSpecSerializer.getModuleSpecFileName()),
            serialized.getBytes(Charsets.UTF_8));

    // update the timestamp on the module directory to indicate that the module has been updated
    Files.setLastModifiedTime(moduleDir, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

From source file:org.apache.hadoop.hbase.util.CoprocessorClassLoader.java

private void init(Path path, String pathPrefix, Configuration conf) throws IOException {
    // Copy the jar to the local filesystem
    String parentDirStr = conf.get(LOCAL_DIR_KEY, DEFAULT_LOCAL_DIR) + TMP_JARS_DIR;
    synchronized (parentDirLockSet) {
        if (!parentDirLockSet.contains(parentDirStr)) {
            Path parentDir = new Path(parentDirStr);
            FileSystem fs = FileSystem.getLocal(conf);
            fs.delete(parentDir, true); // it's ok if the dir doesn't exist now
            parentDirLockSet.add(parentDirStr);
            if (!fs.mkdirs(parentDir) && !fs.getFileStatus(parentDir).isDirectory()) {
                throw new RuntimeException("Failed to create local dir " + parentDirStr
                        + ", CoprocessorClassLoader failed to init");
            }//from w  w  w .  j  av  a2  s.  c  om
        }
    }

    FileSystem fs = path.getFileSystem(conf);
    File dst = new File(parentDirStr,
            "." + pathPrefix + "." + path.getName() + "." + System.currentTimeMillis() + ".jar");
    fs.copyToLocalFile(path, new Path(dst.toString()));
    dst.deleteOnExit();

    addURL(dst.getCanonicalFile().toURI().toURL());

    JarFile jarFile = new JarFile(dst.toString());
    try {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            Matcher m = libJarPattern.matcher(entry.getName());
            if (m.matches()) {
                File file = new File(parentDirStr, "." + pathPrefix + "." + path.getName() + "."
                        + System.currentTimeMillis() + "." + m.group(1));
                IOUtils.copyBytes(jarFile.getInputStream(entry), new FileOutputStream(file), conf, true);
                file.deleteOnExit();
                addURL(file.toURI().toURL());
            }
        }
    } finally {
        jarFile.close();
    }
}

From source file:org.wso2.carbon.automation.test.utils.common.FileManager.java

public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory)
        throws IOException, URISyntaxException {
    File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI());
    File destinationFileDirectory = new File(destinationDirectory);
    JarFile jarFile = new JarFile(sourceFile);
    String fileName = jarFile.getName();
    String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
    File destinationFile = new File(destinationFileDirectory, fileNameLastPart);
    JarOutputStream jarOutputStream = null;
    try {/*from  w w  w.  j a v  a  2 s . c o m*/
        jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile));
        Enumeration<JarEntry> entries = jarFile.entries();
        InputStream inputStream = null;
        while (entries.hasMoreElements()) {
            try {
                JarEntry jarEntry = entries.nextElement();
                inputStream = jarFile.getInputStream(jarEntry);
                //jarOutputStream.putNextEntry(jarEntry);
                //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size
                jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName()));
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    jarOutputStream.write(buffer, 0, bytesRead);
                }
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                    jarOutputStream.flush();
                    jarOutputStream.closeEntry();
                }
            }
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}

From source file:org.wso2.carbon.integration.common.utils.FileManager.java

public void copyJarFile(String sourceFileLocationWithFileName, String destinationDirectory)
        throws URISyntaxException, IOException {
    File sourceFile = new File(getClass().getResource(sourceFileLocationWithFileName).toURI());
    File destinationFileDirectory = new File(destinationDirectory);
    JarOutputStream jarOutputStream = null;
    InputStream inputStream = null;

    try {//w ww  .ja v  a2s .co m
        JarFile jarFile = new JarFile(sourceFile);
        String fileName = jarFile.getName();
        String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
        File destinationFile = new File(destinationFileDirectory, fileNameLastPart);
        jarOutputStream = new JarOutputStream(new FileOutputStream(destinationFile));
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            try {
                JarEntry jarEntry = entries.nextElement();
                inputStream = jarFile.getInputStream(jarEntry);
                //jarOutputStream.putNextEntry(jarEntry);
                //create a new jarEntry to avoid ZipException: invalid jarEntry compressed size
                jarOutputStream.putNextEntry(new JarEntry(jarEntry.getName()));
                byte[] buffer = new byte[4096];
                int bytesRead = 0;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    jarOutputStream.write(buffer, 0, bytesRead);
                }
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        log.warn("Fail to close jarOutStream");
                    }
                }
                if (jarOutputStream != null) {
                    try {
                        jarOutputStream.flush();
                        jarOutputStream.closeEntry();
                    } catch (IOException e) {
                        log.warn("Error while closing jar out stream");
                    }
                }
                if (jarFile != null) {
                    try {
                        jarFile.close();
                    } catch (IOException e) {
                        log.warn("Error while closing jar file");
                    }
                }
            }
        }
    } finally {
        if (jarOutputStream != null) {
            try {
                jarOutputStream.close();
            } catch (IOException e) {
                log.warn("Fail to close jarOutStream");
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.warn("Error while closing input stream");
            }
        }
    }
}

From source file:com.eviware.soapui.DefaultSoapUICore.java

protected void initPlugins() {
    File[] pluginFiles = new File("plugins").listFiles();
    if (pluginFiles != null) {
        for (File pluginFile : pluginFiles) {
            if (!pluginFile.getName().toLowerCase().endsWith("-plugin.jar"))
                continue;

            try {
                log.info("Adding plugin from [" + pluginFile.getAbsolutePath() + "]");

                // add jar to our extension classLoader
                getExtensionClassLoader().addFile(pluginFile);
                JarFile jarFile = new JarFile(pluginFile);

                // look for factories
                JarEntry entry = jarFile.getJarEntry("META-INF/factories.xml");
                if (entry != null)
                    getFactoryRegistry().addConfig(jarFile.getInputStream(entry), extClassLoader);

                // look for listeners
                entry = jarFile.getJarEntry("META-INF/listeners.xml");
                if (entry != null)
                    getListenerRegistry().addConfig(jarFile.getInputStream(entry), extClassLoader);

                // look for actions
                entry = jarFile.getJarEntry("META-INF/actions.xml");
                if (entry != null)
                    getActionRegistry().addConfig(jarFile.getInputStream(entry), extClassLoader);

                // add jar to resource classloader so embedded images can be found with UISupport.loadImageIcon(..)
                UISupport.addResourceClassLoader(new URLClassLoader(new URL[] { pluginFile.toURI().toURL() }));
            } catch (Exception e) {
                SoapUI.logError(e);/*  ww  w  .  j a  v  a2 s  .  c o  m*/
            }
        }
    }
}

From source file:org.springframework.boot.loader.tools.JarWriter.java

void writeEntries(JarFile jarFile, EntryTransformer entryTransformer, UnpackHandler unpackHandler)
        throws IOException {
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarArchiveEntry entry = new JarArchiveEntry(entries.nextElement());
        setUpEntry(jarFile, entry);//from  www . j  av  a2 s. co  m
        try (ZipHeaderPeekInputStream inputStream = new ZipHeaderPeekInputStream(
                jarFile.getInputStream(entry))) {
            EntryWriter entryWriter = new InputStreamEntryWriter(inputStream, true);
            JarArchiveEntry transformedEntry = entryTransformer.transform(entry);
            if (transformedEntry != null) {
                writeEntry(transformedEntry, entryWriter, unpackHandler);
            }
        }
    }
}