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.sling.tooling.support.install.impl.InstallServlet.java

private void installBasedOnUploadedJar(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    InstallationResult result = null;//  www . j av  a2  s  .c o m

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // try to hold even largish bundles in memory to potentially improve performance
        factory.setSizeThreshold(UPLOAD_IN_MEMORY_SIZE_THRESHOLD);

        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);

        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(req);
        if (items.size() != 1) {
            logAndWriteError(
                    "Found " + items.size() + " items to process, but only updating 1 bundle is supported",
                    resp);
            return;
        }

        FileItem item = items.get(0);

        JarInputStream jar = null;
        InputStream rawInput = null;
        try {
            jar = new JarInputStream(item.getInputStream());
            Manifest manifest = jar.getManifest();
            if (manifest == null) {
                logAndWriteError("Uploaded jar file does not contain a manifest", resp);
                return;
            }

            final String symbolicName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);

            if (symbolicName == null) {
                logAndWriteError("Manifest does not have a " + Constants.BUNDLE_SYMBOLICNAME, resp);
                return;
            }

            final String version = manifest.getMainAttributes().getValue(Constants.BUNDLE_VERSION);

            // the JarInputStream is used only for validation, we need a fresh input stream for updating
            rawInput = item.getInputStream();

            Bundle found = getBundle(symbolicName);
            try {
                installOrUpdateBundle(found, rawInput, "inputstream:" + symbolicName + "-" + version + ".jar");

                result = new InstallationResult(true, null);
                resp.setStatus(200);
                result.render(resp.getWriter());
                return;
            } catch (BundleException e) {
                logAndWriteError("Unable to install/update bundle " + symbolicName, e, resp);
                return;
            }
        } finally {
            IOUtils.closeQuietly(jar);
            IOUtils.closeQuietly(rawInput);
        }

    } catch (FileUploadException e) {
        logAndWriteError("Failed parsing uploaded bundle", e, resp);
        return;
    }
}

From source file:org.teavm.classlib.impl.report.JCLComparisonBuilder.java

private List<JCLPackage> buildModel() throws IOException {
    Map<String, JCLPackage> packageMap = new HashMap<>();
    URL url = classLoader.getResource("java/lang/Object" + CLASS_SUFFIX);
    String path = url.toString();
    if (!path.startsWith(JAR_PREFIX) || !path.endsWith(JAR_SUFFIX)) {
        throw new RuntimeException("Can't find JCL classes");
    }//from   ww w  .j  a va  2 s  .c  o  m
    ClasspathClassHolderSource classSource = new ClasspathClassHolderSource(classLoader);
    path = path.substring(JAR_PREFIX.length(), path.length() - JAR_SUFFIX.length());
    File outDir = new File(outputDirectory).getParentFile();
    if (!outDir.exists()) {
        outDir.mkdirs();
    }
    path = URLDecoder.decode(path, "UTF-8");
    try (JarInputStream jar = new JarInputStream(new FileInputStream(path))) {
        visitor = new JCLComparisonVisitor(classSource, packageMap);
        while (true) {
            JarEntry entry = jar.getNextJarEntry();
            if (entry == null) {
                break;
            }
            if (validateName(entry.getName())) {
                compareClass(jar);
            }
            jar.closeEntry();
        }
    }
    return new ArrayList<>(packageMap.values());
}

From source file:org.apache.hadoop.hbase.ClassFinder.java

private Set<Class<?>> findClassesFromJar(String jarFileName, String packageName, boolean proceedOnExceptions)
        throws IOException, ClassNotFoundException, LinkageError {
    JarInputStream jarFile = null;
    try {/*w w w .ja  v  a  2s  .  com*/
        jarFile = new JarInputStream(new FileInputStream(jarFileName));
    } catch (IOException ioEx) {
        LOG.warn("Failed to look for classes in " + jarFileName + ": " + ioEx);
        throw ioEx;
    }

    Set<Class<?>> classes = new HashSet<Class<?>>();
    JarEntry entry = null;
    try {
        while (true) {
            try {
                entry = jarFile.getNextJarEntry();
            } catch (IOException ioEx) {
                if (!proceedOnExceptions) {
                    throw ioEx;
                }
                LOG.warn("Failed to get next entry from " + jarFileName + ": " + ioEx);
                break;
            }
            if (entry == null) {
                break; // loop termination condition
            }

            String className = entry.getName();
            if (!className.endsWith(CLASS_EXT)) {
                continue;
            }
            int ix = className.lastIndexOf('/');
            String fileName = (ix >= 0) ? className.substring(ix + 1) : className;
            if (null != this.fileNameFilter && !this.fileNameFilter.isCandidateFile(fileName, className)) {
                continue;
            }
            className = className.substring(0, className.length() - CLASS_EXT.length()).replace('/', '.');
            if (!className.startsWith(packageName)) {
                continue;
            }
            Class<?> c = makeClass(className, proceedOnExceptions);
            if (c != null) {
                if (!classes.add(c)) {
                    LOG.warn("Ignoring duplicate class " + className);
                }
            }
        }
        return classes;
    } finally {
        jarFile.close();
    }
}

From source file:com.geewhiz.pacify.TestArchive.java

@Test
public void checkJarWhereTheSourceIsntAJarPerDefinition() throws ArchiveException, IOException {
    LoggingUtils.setLogLevel(logger, Level.ERROR);

    String testFolder = "testArchive/correct/jarWhereSourceIsntAJarPerDefinition";

    File testResourceFolder = new File("src/test/resources/", testFolder);
    File targetResourceFolder = new File("target/test-resources/", testFolder);

    LinkedHashSet<Defect> defects = createPrepareValidateAndReplace(testFolder,
            createPropertyResolveManager(propertiesToUseWhileResolving));

    Assert.assertEquals("We shouldnt get any defects.", 0, defects.size());

    JarInputStream in = new JarInputStream(
            new FileInputStream(new File(testResourceFolder, "package/archive.jar")));
    JarInputStream out = new JarInputStream(
            new FileInputStream(new File(targetResourceFolder, "package/archive.jar")));

    Assert.assertNull("SRC jar should be a jar which is packed via zip, so the first entry isn't the manifest.",
            in.getManifest());/*from  ww w  .ja  va  2  s  .  c o  m*/
    Assert.assertNotNull("RESULT jar should contain the manifest as first entry", out.getManifest());

    in.close();
    out.close();

    checkIfResultIsAsExpected(testFolder);
}

From source file:org.openspaces.maven.plugin.CreatePUProjectMojo.java

/**
 * Extracts the project files to the project directory.
 *///from w  w  w  .  j av  a 2  s . c o  m
private void extract(URL url) throws Exception {
    packageDirs = packageName.replaceAll("\\.", "/");
    String puTemplate = DIR_TEMPLATES + "/" + template + "/";
    int length = puTemplate.length() - 1;
    BufferedInputStream bis = new BufferedInputStream(url.openStream());
    JarInputStream jis = new JarInputStream(bis);
    JarEntry je;
    byte[] buf = new byte[1024];
    int n;
    while ((je = jis.getNextJarEntry()) != null) {
        String jarEntryName = je.getName();
        PluginLog.getLog().debug("JAR entry: " + jarEntryName);
        if (je.isDirectory() || !jarEntryName.startsWith(puTemplate)) {
            continue;
        }
        String targetFileName = projectDir + jarEntryName.substring(length);

        // convert the ${gsGroupPath} to directory
        targetFileName = StringUtils.replace(targetFileName, FILTER_GROUP_PATH, packageDirs);
        PluginLog.getLog().debug("Extracting entry " + jarEntryName + " to " + targetFileName);

        // read the bytes to the buffer
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        while ((n = jis.read(buf, 0, 1024)) > -1) {
            byteStream.write(buf, 0, n);
        }

        // replace property references with the syntax ${property_name}
        // to their respective property values.
        String data = byteStream.toString();
        data = StringUtils.replace(data, FILTER_GROUP_ID, packageName);
        data = StringUtils.replace(data, FILTER_ARTIFACT_ID, projectDir.getName());
        data = StringUtils.replace(data, FILTER_GROUP_PATH, packageDirs);

        // write the entire converted file content to the destination file.
        File f = new File(targetFileName);
        File dir = f.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }
        FileWriter writer = new FileWriter(f);
        writer.write(data);
        jis.closeEntry();
        writer.close();
    }
    jis.close();
}

From source file:org.talend.components.api.component.runtime.JarRuntimeInfoTest.java

/**
 * Test method for/*from  w  w w  .j  a  v a 2 s . c  o  m*/
 * {@link org.talend.components.api.component.runtime.JarRuntimeInfo#extracDependencyFromStream(org.talend.components.api.component.runtime.DependenciesReader, java.lang.String, java.util.jar.JarInputStream)}
 * .
 * 
 * @throws IOException
 * @throws MalformedURLException
 */
@Test
public void testExtracDependencyFromStream() throws MalformedURLException, IOException {
    MavenResolver mavenResolver = MavenResolvers.createMavenResolver(null, "foo");
    File jarWithDeps = mavenResolver.resolve("mvn:org.talend.components/components-api-full-example/0.1.0");
    try (JarInputStream jis = new JarInputStream(new FileInputStream(jarWithDeps))) {
        List<URL> dependencyFromStream = JarRuntimeInfo.extracDependencyFromStream(new DependenciesReader(null),
                DependenciesReader.computeDependenciesFilePath("org.talend.components",
                        "components-full-example"),
                jis);
        checkFullExampleDependencies(dependencyFromStream);

    }
}

From source file:org.pentaho.osgi.platform.webjars.WebjarsURLConnectionTest.java

@Test
public void testClosingStream() throws IOException {
    WebjarsURLConnection connection = new WebjarsURLConnection(
            new URL("mvn:org.webjars/angular-dateparser/1.0.9"));
    connection.connect();/*  w w w  .  j  a  va2  s.  co m*/

    InputStream inputStream = connection.getInputStream();
    JarInputStream jar = new JarInputStream(inputStream);
    jar.getManifest();
    jar.close();
    try {
        connection.transform_thread.get();
    } catch (Exception exception) {
        fail("Thread failed to execute transform() method: " + exception.getMessage());
    }
}

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

private static void readJar(TarInputStream tis) throws IOException {
    TarEntry fileEntry = readFile(tis);// w w w  .  j a va  2s  .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.ottogroup.bi.asap.repository.ComponentClassloader.java

/**
 * Find class inside managed jars or hand over the parent
 * @see java.lang.ClassLoader#findClass(java.lang.String)
 *//*  w  w w.jav a 2 s .c o m*/
protected Class<?> findClass(String name) throws ClassNotFoundException {

    // find in already loaded classes to make things shorter
    Class<?> clazz = findLoadedClass(name);
    if (clazz != null)
        return clazz;

    // check if the class searched for is contained inside managed jars,
    // otherwise hand over the request to the parent class loader
    String jarFileName = this.classesJarMapping.get(name);
    if (StringUtils.isBlank(jarFileName)) {
        super.findClass(name);
    }

    // try to find class inside jar the class name is associated with
    JarInputStream jarInput = null;
    try {
        // open a stream on jar which contains the class
        jarInput = new JarInputStream(new FileInputStream(jarFileName));
        // ... and iterate through all entries
        JarEntry jarEntry = null;
        while ((jarEntry = jarInput.getNextJarEntry()) != null) {

            // extract the name of the jar entry and check if it has suffix '.class' and thus contains
            // the search for implementation
            String entryFileName = jarEntry.getName();
            if (entryFileName.endsWith(".class")) {

                // replace slashes by dots, remove suffix and compare the result with the searched for class name 
                entryFileName = entryFileName.substring(0, entryFileName.length() - 6).replace('/', '.');
                if (name.equalsIgnoreCase(entryFileName)) {

                    // load bytes from jar entry and define a class over it
                    byte[] data = loadBytes(jarInput);
                    if (data != null) {
                        return defineClass(name, data, 0, data.length);
                    }

                    // if the jar entry does not contain any data, throw an exception
                    throw new ClassNotFoundException("Class '" + name + "' not found");
                }
            }
        }
    } catch (IOException e) {
        // if any io error occurs: throw an exception
        throw new ClassNotFoundException("Class '" + name + "' not found");
    } finally {
        try {
            jarInput.close();
        } catch (IOException e) {
            logger.error("Failed to close open JAR file '" + jarFileName + "'. Error: " + e.getMessage());
        }
    }

    // if no such class exists, throw an exception
    throw new ClassNotFoundException("Class [" + name + "] not found");

}

From source file:com.izforge.izpack.installer.unpacker.Pack200FileUnpackerTest.java

/**
 * Returns a file from a jar as a byte array.
 *
 * @param file the jar file//from w  w w .j  ava 2  s. c  om
 * @param name the entry name
 * @return the file content
 * @throws IOException for any I/O error
 */
private byte[] getEntry(File file, String name) throws IOException {
    JarInputStream stream = new JarInputStream(new FileInputStream(file));
    try {
        JarEntry entry;
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        while ((entry = stream.getNextJarEntry()) != null) {
            if (entry.getName().endsWith(name)) {
                IOUtils.copy(stream, bytes);
                return bytes.toByteArray();
            }
        }
        fail("Entry not found: " + name);
    } finally {
        stream.close();
    }
    return null;
}