Example usage for java.util.jar JarInputStream getNextJarEntry

List of usage examples for java.util.jar JarInputStream getNextJarEntry

Introduction

In this page you can find the example usage for java.util.jar JarInputStream getNextJarEntry.

Prototype

public JarEntry getNextJarEntry() throws IOException 

Source Link

Document

Reads the next JAR file entry and positions the stream at the beginning of the entry data.

Usage

From source file:org.apache.camel.impl.DefaultPackageScanClassResolver.java

/**
 * Finds matching classes within a jar files that contains a folder
 * structure matching the package structure. If the File is not a JarFile or
 * does not exist a warning will be logged, but no error will be raised.
 *
 * @param test    a Test used to filter the classes that are discovered
 * @param parent  the parent package under which classes must be in order to
 *                be considered// ww  w.  ja va  2s .com
 * @param stream  the inputstream of the jar file to be examined for classes
 * @param urlPath the url of the jar file to be examined for classes
 */
private void loadImplementationsInJar(PackageScanFilter test, String parent, InputStream stream, String urlPath,
        Set<Class<?>> classes) {
    JarInputStream jarStream = null;
    try {
        jarStream = new JarInputStream(stream);

        JarEntry entry;
        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (name != null) {
                name = name.trim();
                if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) {
                    addIfMatching(test, name, classes);
                }
            }
        }
    } catch (IOException ioe) {
        log.warn("Cannot search jar file '" + urlPath + "' for classes matching criteria: " + test
                + " due to an IOException: " + ioe.getMessage(), ioe);
    } finally {
        IOHelper.close(jarStream, urlPath, log);
    }
}

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 . java  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:org.echocat.nodoodle.transport.HandlerUnpacker.java

protected SplitResult splitMultipleJarIntoJars(InputStream inputStream, File targetDirectory)
        throws IOException {
    if (inputStream == null) {
        throw new NullPointerException();
    }/*w ww  .j a v  a  2 s . c om*/
    if (targetDirectory == null) {
        throw new NullPointerException();
    }
    final Collection<File> jarFiles = new ArrayList<File>();
    final File mainJarFile = getMainJarFile(targetDirectory);
    jarFiles.add(mainJarFile);
    final JarInputStream jarInput = new JarInputStream(inputStream);
    final Manifest manifest = jarInput.getManifest();
    final FileOutputStream mainJarFileStream = new FileOutputStream(mainJarFile);
    try {
        final JarOutputStream jarOutput = new JarOutputStream(mainJarFileStream, manifest);
        try {
            JarEntry entry = jarInput.getNextJarEntry();
            while (entry != null) {
                final String entryName = entry.getName();
                if (!entry.isDirectory() && entryName.startsWith("lib/")) {
                    final File targetFile = new File(targetDirectory, entryName);
                    if (!targetFile.getParentFile().mkdirs()) {
                        throw new IOException("Could not create parent directory of " + targetFile + ".");
                    }
                    final OutputStream outputStream = new FileOutputStream(targetFile);
                    try {
                        IOUtils.copy(jarInput, outputStream);
                    } finally {
                        IOUtils.closeQuietly(outputStream);
                    }
                    jarFiles.add(targetFile);
                } else {
                    if (entryName.startsWith(TransportConstants.CLASSES_PREFIX)
                            && entryName.length() > TransportConstants.CLASSES_PREFIX.length()) {
                        try {
                            ZIP_ENTRY_NAME_FIELD.set(entry, entryName.substring(CLASSES_PREFIX.length()));
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException("Could not set " + ZIP_ENTRY_NAME_FIELD + ".", e);
                        }
                    }
                    jarOutput.putNextEntry(entry);
                    IOUtils.copy(jarInput, jarOutput);
                    jarOutput.closeEntry();
                }
                entry = jarInput.getNextJarEntry();
            }
        } finally {
            IOUtils.closeQuietly(jarOutput);
        }
    } finally {
        IOUtils.closeQuietly(mainJarFileStream);
    }
    return new SplitResult(Collections.unmodifiableCollection(jarFiles), manifest);
}

From source file:co.cask.cdap.internal.app.runtime.spark.SparkRuntimeService.java

/**
 * Updates the dependency jar packaged by the {@link ApplicationBundler#createBundle(Location, Iterable,
 * Iterable)} by moving the things inside classes, lib, resources a level up as expected by spark.
 *
 * @param dependencyJar {@link Location} of the job jar to be updated
 * @param context       {@link BasicSparkContext} of this job
 *///from w  ww  .  ja  v  a2s.  co m
private Location updateDependencyJar(Location dependencyJar, BasicSparkContext context) throws IOException {

    final String[] prefixToStrip = { ApplicationBundler.SUBDIR_CLASSES, ApplicationBundler.SUBDIR_LIB,
            ApplicationBundler.SUBDIR_RESOURCES };

    Id.Program programId = context.getProgram().getId();

    Location updatedJar = locationFactory.create(String.format("%s.%s.%s.%s.%s.jar",
            ProgramType.SPARK.name().toLowerCase(), programId.getAccountId(), programId.getApplicationId(),
            programId.getId(), context.getRunId().getId()));

    // Creates Manifest
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(ManifestFields.MANIFEST_VERSION, "1.0");
    JarOutputStream jarOutput = new JarOutputStream(updatedJar.getOutputStream(), manifest);

    try {
        JarInputStream jarInput = new JarInputStream(dependencyJar.getInputStream());

        try {
            JarEntry jarEntry = jarInput.getNextJarEntry();

            while (jarEntry != null) {
                boolean isDir = jarEntry.isDirectory();
                String entryName = jarEntry.getName();
                String newEntryName = entryName;

                for (String prefix : prefixToStrip) {
                    if (entryName.startsWith(prefix) && !entryName.equals(prefix)) {
                        newEntryName = entryName.substring(prefix.length());
                    }
                }

                jarEntry = new JarEntry(newEntryName);
                jarOutput.putNextEntry(jarEntry);
                if (!isDir) {
                    ByteStreams.copy(jarInput, jarOutput);
                }
                jarEntry = jarInput.getNextJarEntry();
            }
        } finally {
            jarInput.close();
            Locations.deleteQuietly(dependencyJar);
        }
    } finally {
        jarOutput.close();
    }
    return updatedJar;
}

From source file:com.ottogroup.bi.spqr.repository.CachedComponentClassLoader.java

/**
 * Initializes the class loader by pointing it to folder holding managed JAR files
 * @param componentFolder/* w  w w .ja v a  2s. c  o  m*/
 * @throws IOException
 * @throws RequiredInputMissingException
 */
public void initialize(final String componentFolder) throws IOException, RequiredInputMissingException {

    ///////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(componentFolder))
        throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'");

    File folder = new File(componentFolder);
    if (!folder.isDirectory())
        throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder");

    File[] jarFiles = folder.listFiles();
    if (jarFiles == null || jarFiles.length < 1)
        throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'");
    //
    ///////////////////////////////////////////////////////////////////

    logger.info("Initializing component classloader [folder=" + componentFolder + "]");

    // step through jar files, ensure it is a file and iterate through its contents
    for (File jarFile : jarFiles) {
        if (jarFile.isFile()) {

            JarInputStream jarInputStream = null;
            try {

                jarInputStream = new JarInputStream(new FileInputStream(jarFile));
                JarEntry jarEntry = null;
                while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
                    String jarEntryName = jarEntry.getName();
                    // if the current file references a class implementation, replace slashes by dots, strip 
                    // away the class suffix and add a reference to the classes-2-jar mapping 
                    if (StringUtils.endsWith(jarEntryName, ".class")) {
                        jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                        this.byteCode.put(jarEntryName, loadBytes(jarInputStream));
                    } else {
                        // ...and add a mapping for resource to jar file as well
                        this.resources.put(jarEntryName, loadBytes(jarInputStream));
                    }
                }
            } catch (Exception e) {
                logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                        + e.getMessage());
            } finally {
                try {
                    jarInputStream.close();
                } catch (Exception e) {
                    logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                            + e.getMessage());
                }
            }
        }
    }

    logger.info("Analyzing " + this.byteCode.size() + " classes for component annotation");

    // load classes from jars marked component files and extract the deployment descriptors
    for (String cjf : this.byteCode.keySet()) {

        try {
            Class<?> c = loadClass(cjf);
            Annotation spqrComponentAnnotation = getSPQRComponentAnnotation(c);
            if (spqrComponentAnnotation != null) {

                Method spqrAnnotationTypeMethod = spqrComponentAnnotation.getClass()
                        .getMethod(ANNOTATION_TYPE_METHOD, (Class[]) null);
                Method spqrAnnotationNameMethod = spqrComponentAnnotation.getClass()
                        .getMethod(ANNOTATION_NAME_METHOD, (Class[]) null);
                Method spqrAnnotationVersionMethod = spqrComponentAnnotation.getClass()
                        .getMethod(ANNOTATION_VERSION_METHOD, (Class[]) null);
                Method spqrAnnotationDescriptionMethod = spqrComponentAnnotation.getClass()
                        .getMethod(ANNOTATION_DESCRIPTION_METHOD, (Class[]) null);

                @SuppressWarnings("unchecked")
                Enum<MicroPipelineComponentType> o = (Enum<MicroPipelineComponentType>) spqrAnnotationTypeMethod
                        .invoke(spqrComponentAnnotation, (Object[]) null);
                final MicroPipelineComponentType componentType = Enum.valueOf(MicroPipelineComponentType.class,
                        o.name());
                final String componentName = (String) spqrAnnotationNameMethod.invoke(spqrComponentAnnotation,
                        (Object[]) null);
                final String componentVersion = (String) spqrAnnotationVersionMethod
                        .invoke(spqrComponentAnnotation, (Object[]) null);
                final String componentDescription = (String) spqrAnnotationDescriptionMethod
                        .invoke(spqrComponentAnnotation, (Object[]) null);

                this.managedComponents.put(getManagedComponentKey(componentName, componentVersion),
                        new ComponentDescriptor(c.getName(), componentType, componentName, componentVersion,
                                componentDescription));
                logger.info("pipeline component found [type=" + componentType + ", name=" + componentName
                        + ", version=" + componentVersion + "]");
                ;
            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error("Failed to load class '" + cjf + "'. Error: " + e.getMessage());
        }
    }
}

From source file:org.apache.geode.internal.DeployedJar.java

/**
 * Scan the JAR file and attempt to register any function classes found.
 *//*from  ww w  . j  ava 2  s .  co m*/

public synchronized void registerFunctions() throws ClassNotFoundException {
    final boolean isDebugEnabled = logger.isDebugEnabled();
    if (isDebugEnabled) {
        logger.debug("Registering functions with DeployedJar: {}", this);
    }

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.getJarContent());

    JarInputStream jarInputStream = null;
    try {
        Collection<String> functionClasses = findFunctionsInThisJar();

        jarInputStream = new JarInputStream(byteArrayInputStream);
        JarEntry jarEntry = jarInputStream.getNextJarEntry();

        while (jarEntry != null) {
            if (jarEntry.getName().endsWith(".class")) {
                final String className = PATTERN_SLASH.matcher(jarEntry.getName()).replaceAll("\\.")
                        .substring(0, jarEntry.getName().length() - 6);

                if (functionClasses.contains(className)) {
                    if (isDebugEnabled) {
                        logger.debug("Attempting to load class: {}, from JAR file: {}", jarEntry.getName(),
                                this.file.getAbsolutePath());
                    }
                    try {
                        Class<?> clazz = ClassPathLoader.getLatest().forName(className);
                        Collection<Function> registerableFunctions = getRegisterableFunctionsFromClass(clazz);
                        for (Function function : registerableFunctions) {
                            FunctionService.registerFunction(function);
                            if (isDebugEnabled) {
                                logger.debug("Registering function class: {}, from JAR file: {}", className,
                                        this.file.getAbsolutePath());
                            }
                            this.registeredFunctions.add(function);
                        }
                    } catch (ClassNotFoundException | NoClassDefFoundError cnfex) {
                        logger.error("Unable to load all classes from JAR file: {}",
                                this.file.getAbsolutePath(), cnfex);
                        throw cnfex;
                    }
                } else {
                    if (isDebugEnabled) {
                        logger.debug("No functions found in class: {}, from JAR file: {}", jarEntry.getName(),
                                this.file.getAbsolutePath());
                    }
                }
            }
            jarEntry = jarInputStream.getNextJarEntry();
        }
    } catch (IOException ioex) {
        logger.error("Exception when trying to read class from ByteArrayInputStream", ioex);
    } finally {
        if (jarInputStream != null) {
            try {
                jarInputStream.close();
            } catch (IOException ioex) {
                logger.error("Exception attempting to close JAR input stream", ioex);
            }
        }
    }
}

From source file:org.apache.maven.plugin.javadoc.JavadocUtil.java

/**
 * @param jarFile not null/*from w  w  w  .  jav a2 s  . c o  m*/
 * @return all class names from the given jar file.
 * @throws IOException if any or if the jarFile is null or doesn't exist.
 */
private static List<String> getClassNamesFromJar(File jarFile) throws IOException {
    if (jarFile == null || !jarFile.exists() || !jarFile.isFile()) {
        throw new IOException("The jar '" + jarFile + "' doesn't exist or is not a file.");
    }

    List<String> classes = new ArrayList<String>();
    JarInputStream jarStream = null;

    try {
        jarStream = new JarInputStream(new FileInputStream(jarFile));
        JarEntry jarEntry = jarStream.getNextJarEntry();
        while (jarEntry != null) {
            if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) {
                String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf("."));

                classes.add(name.replaceAll("/", "\\."));
            }

            jarStream.closeEntry();
            jarEntry = jarStream.getNextJarEntry();
        }
    } finally {
        IOUtil.close(jarStream);
    }

    return classes;
}

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.j  a  v  a2s .  c om
        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.ottogroup.bi.asap.repository.ComponentClassloader.java

/**
 * Initializes the class loader by pointing it to folder holding managed JAR files
 * @param componentFolder/*  w  w w. j  av a2  s.  c o  m*/
 * @param componentJarIdentifier file to search for in component JAR which identifies it as component JAR 
 * @throws IOException
 * @throws RequiredInputMissingException
 */
public void initialize(final String componentFolder, final String componentJarIdentifier)
        throws IOException, RequiredInputMissingException {

    ///////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(componentFolder))
        throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'");

    File folder = new File(componentFolder);
    if (!folder.isDirectory())
        throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder");

    File[] jarFiles = folder.listFiles();
    if (jarFiles == null || jarFiles.length < 1)
        throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'");
    //
    ///////////////////////////////////////////////////////////////////

    logger.info("Initializing component classloader [componentJarIdentifier=" + componentJarIdentifier
            + ", folder=" + componentFolder + "]");

    // step through jar files, ensure it is a file and iterate through its contents
    for (File jarFile : jarFiles) {
        if (jarFile.isFile()) {

            JarInputStream jarInputStream = null;
            try {
                jarInputStream = new JarInputStream(new FileInputStream(jarFile));
                JarEntry jarEntry = null;
                while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
                    String jarEntryName = jarEntry.getName();
                    // if the current file references a class implementation, replace slashes by dots, strip 
                    // away the class suffix and add a reference to the classes-2-jar mapping 
                    if (StringUtils.endsWith(jarEntryName, ".class")) {
                        jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                        this.classesJarMapping.put(jarEntryName, jarFile.getAbsolutePath());
                    } else {
                        // if the current file references a resource, check if it is the identifier file which
                        // marks this jar to contain component implementation                     
                        if (StringUtils.equalsIgnoreCase(jarEntryName, componentJarIdentifier))
                            this.componentJarFiles.add(jarFile.getAbsolutePath());
                        // ...and add a mapping for resource to jar file as well                     
                        this.resourcesJarMapping.put(jarEntryName, jarFile.getAbsolutePath());
                    }
                }
            } catch (Exception e) {
                logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                        + e.getMessage());
            } finally {
                try {
                    jarInputStream.close();
                } catch (Exception e) {
                    logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                            + e.getMessage());
                }
            }
        }
    }

    // load classes from jars marked component files and extract the deployment descriptors
    for (String cjf : this.componentJarFiles) {
        logger.info("Attempting to load pipeline components located in '" + cjf + "'");

        // open JAR file and iterate through it's contents
        JarInputStream jarInputStream = null;
        try {
            jarInputStream = new JarInputStream(new FileInputStream(cjf));
            JarEntry jarEntry = null;
            while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {

                // fetch name of current entry and ensure it is a class file
                String jarEntryName = jarEntry.getName();
                if (jarEntryName.endsWith(".class")) {
                    // replace slashes by dots and strip away '.class' suffix
                    jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                    Class<?> c = loadClass(jarEntryName);
                    AsapComponent pc = c.getAnnotation(AsapComponent.class);
                    if (pc != null) {
                        this.managedComponents.put(getManagedComponentKey(pc.name(), pc.version()),
                                new ComponentDescriptor(c.getName(), pc.type(), pc.name(), pc.version(),
                                        pc.description()));
                        logger.info("pipeline component found [type=" + pc.type() + ", name=" + pc.name()
                                + ", version=" + pc.version() + "]");
                        ;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Failed to read from JAR file '" + cjf + "'. Error: " + e.getMessage());
        } finally {
            try {
                jarInputStream.close();
            } catch (Exception e) {
                logger.error("Failed to close open JAR file '" + cjf + "'. Error: " + e.getMessage());
            }
        }
    }
}

From source file:org.apache.struts2.convention.DefaultClassFinder.java

private List<String> jar(JarInputStream jarStream) throws IOException {
    List<String> classNames = new ArrayList<>();

    JarEntry entry;//from w ww .j a v  a  2s.co m
    while ((entry = jarStream.getNextJarEntry()) != null) {
        if (entry.isDirectory() || !entry.getName().endsWith(".class")) {
            continue;
        }
        String className = entry.getName();
        className = className.replaceFirst(".class$", "");

        //war files are treated as .jar files, so takeout WEB-INF/classes
        className = StringUtils.removeStart(className, "WEB-INF/classes/");

        className = className.replace('/', '.');
        classNames.add(className);
    }

    return classNames;
}