Example usage for java.util.jar JarEntry getName

List of usage examples for java.util.jar JarEntry getName

Introduction

In this page you can find the example usage for java.util.jar JarEntry getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

From source file:org.ebayopensource.turmeric.eclipse.utils.classloader.SOAPluginClassLoader.java

/**
 * {@inheritDoc}/*from w  w  w  .j  ava 2s  .  co  m*/
 */
@Override
public URL findResource(String resourceName) {
    //logger.info("resource name in findresource is " + resourceName);
    try {
        URL retUrl = null;
        for (Bundle pluginBundle : pluginBundles) {
            retUrl = pluginBundle.getResource(resourceName);
            if (retUrl != null) {
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("found resource using bundle " + resourceName);
                }
                return retUrl;
            }
        }

    } catch (Exception exception) {
    }

    for (URL url : m_jarURLs) {

        try {
            File file = FileUtils.toFile(url);
            JarFile jarFile;
            jarFile = new JarFile(file);
            JarEntry jarEntry = jarFile.getJarEntry(resourceName);
            if (jarEntry != null) {
                SOAToolFileUrlHandler handler = new SOAToolFileUrlHandler(jarFile, jarEntry);
                URL retUrl = new URL("jar", "", -1,
                        new File(jarFile.getName()).toURI().toURL() + "!/" + jarEntry.getName(), handler);
                handler.setExpectedUrl(retUrl);
                return retUrl;

            }
        } catch (IOException e) {
            e.printStackTrace(); // KEEPME
        }

    }

    return super.findResource(resourceName);
}

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

/**
 * Write the required spring-boot-loader classes to the JAR.
 * @param loaderJarResourceName the name of the resource containing the loader classes
 * to be written//from  w  w  w  .  ja v  a 2s  .c o m
 * @throws IOException if the classes cannot be written
 */
@Override
public void writeLoaderClasses(String loaderJarResourceName) throws IOException {
    URL loaderJar = getClass().getClassLoader().getResource(loaderJarResourceName);
    try (JarInputStream inputStream = new JarInputStream(new BufferedInputStream(loaderJar.openStream()))) {
        JarEntry entry;
        while ((entry = inputStream.getNextJarEntry()) != null) {
            if (entry.getName().endsWith(".class")) {
                writeEntry(new JarArchiveEntry(entry), new InputStreamEntryWriter(inputStream, false));
            }
        }
    }
}

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//  w w w .j a v a  2s .  c o m
 * @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.apache.geode.internal.DeployedJar.java

/**
 * Scan the JAR file and attempt to register any function classes found.
 *//* w  w  w  . j a va2 s . c  o 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:de.tudarmstadt.ukp.dkpro.core.maltparser.MaltParser.java

private String getRealName(URL aUrl) throws IOException {
    JarEntry je = null;
    JarInputStream jis = null;/*from  w  ww .ja  v  a2  s. co  m*/

    try {
        jis = new JarInputStream(aUrl.openConnection().getInputStream());
        while ((je = jis.getNextJarEntry()) != null) {
            String entryName = je.getName();
            if (entryName.endsWith(".info")) {
                int indexUnderScore = entryName.lastIndexOf('_');
                int indexSeparator = entryName.lastIndexOf(File.separator);
                if (indexSeparator == -1) {
                    indexSeparator = entryName.lastIndexOf('/');
                }
                if (indexSeparator == -1) {
                    indexSeparator = entryName.lastIndexOf('\\');
                }
                int indexDot = entryName.lastIndexOf('.');
                if (indexUnderScore == -1 || indexDot == -1) {
                    throw new IllegalStateException(
                            "Could not find the configuration name and type from the URL '" + aUrl.toString()
                                    + "'. ");
                }

                return entryName.substring(indexSeparator + 1, indexUnderScore) + ".mco";
            }
        }

        throw new IllegalStateException(
                "Could not find the configuration name and type from the URL '" + aUrl.toString() + "'. ");
    } finally {
        IOUtils.closeQuietly(jis);
    }
}

From source file:nl.geodienstencentrum.maven.plugin.sass.AbstractSassMojo.java

/**
 * Extract the Bourbon assets to the build directory.
 * @param destinationDir directory for the Bourbon resources
 *//*ww  w  .j  ava  2s. co  m*/
private void extractBourbonResources(String destinationDir) {
    final Log log = this.getLog();
    try {
        File destDir = new File(destinationDir);
        if (destDir.isDirectory()) {
            // skip extracting Bourbon, as it seems to hav been done
            log.info("Bourbon resources seems to have been extracted before.");
            return;
        }
        log.info("Extracting Bourbon resources to: " + destinationDir);
        destDir.mkdirs();
        // find the jar with the Bourbon directory in the classloader
        URL urlJar = this.getClass().getClassLoader().getResource("scss-report.xsl");
        String resourceFilePath = urlJar.getFile();
        int index = resourceFilePath.indexOf("!");
        String jarFileURI = resourceFilePath.substring(0, index);
        File jarFile = new File(new URI(jarFileURI));
        JarFile jar = new JarFile(jarFile);

        // extract app/assets/stylesheets to destinationDir
        for (Enumeration<JarEntry> enums = jar.entries(); enums.hasMoreElements();) {
            JarEntry entry = enums.nextElement();

            if (entry.getName().contains("app/assets/stylesheets")) {
                // shorten the path a bit
                index = entry.getName().indexOf("app/assets/stylesheets");
                String fileName = destinationDir + File.separator + entry.getName().substring(index);

                File f = new File(fileName);
                if (fileName.endsWith("/")) {
                    f.mkdirs();
                } else {
                    FileOutputStream fos = new FileOutputStream(f);
                    try {
                        IOUtil.copy(jar.getInputStream(entry), fos);
                    } finally {
                        IOUtil.close(fos);
                    }
                }
            }
        }
    } catch (IOException | URISyntaxException ex) {
        log.error("Error extracting Bourbon resources.", ex);
    }
}

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/*from www  . jav a2 s  .  co  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.axis2.wsdl.util.WSDLWrapperReloadImpl.java

private static URL getURLFromJAR(URLClassLoader urlLoader, URL relativeURL) throws WSDLException {

    URL[] urlList = urlLoader.getURLs();

    if (urlList == null) {
        return null;
    }/*w  w w  .  j a va2 s  .  c  om*/

    for (int i = 0; i < urlList.length; i++) {
        URL url = urlList[i];

        if (url == null) {
            return null;
        }

        if ("file".equals(url.getProtocol())) {

            File f = new File(url.getPath());

            //If file is not of type directory then its a jar file
            if (f.exists() && !f.isDirectory()) {
                try {
                    JarFile jf = new JarFile(f);
                    Enumeration entries = jf.entries();
                    // read all entries in jar file and return the first 
                    // wsdl file that matches the relative path
                    while (entries.hasMoreElements()) {
                        JarEntry je = (JarEntry) entries.nextElement();
                        String name = je.getName();
                        if (name.endsWith(".wsdl")) {
                            String relativePath = relativeURL.getPath();
                            if (relativePath.endsWith(name)) {
                                String path = f.getAbsolutePath();

                                // This check is necessary because Unix/Linux file paths begin
                                // with a '/'. When adding the prefix 'jar:file:/' we may end
                                // up with '//' after the 'file:' part. This causes the URL 
                                // object to treat this like a remote resource
                                if (path != null && path.indexOf("/") == 0) {
                                    path = path.substring(1, path.length());
                                }

                                URL absoluteUrl = new URL("jar:file:/" + path + "!/" + je.getName());
                                return absoluteUrl;
                            }
                        }
                    }
                } catch (Exception e) {
                    WSDLException we = new WSDLException("WSDLWrapperReloadImpl : ", e.getMessage(), e);
                    throw we;
                }
            }
        }
    }

    return null;
}

From source file:org.dspace.installer_edm.InstallerCrosswalk.java

/**
 * Abre el jar para escribir el nuevo archivo class compilado, elresto de archivos los copia tal cual
 *
 * @throws IOException//from  w  ww  .  j ava  2 s.c  o  m
 */
protected void writeNewJar() throws IOException {
    // buffer para leer datos de los archivos
    final int BUFFER_SIZE = 1024;
    // directorio de trabajo
    File jarDir = new File(this.oaiApiJarJarFile.getName()).getParentFile();
    // nombre del jar
    String name = oaiApiJarWorkFile.getName();
    String extension = name.substring(name.lastIndexOf('.'));
    name = name.substring(0, name.lastIndexOf('.'));
    // archivo temporal del nuevo jar
    File newJarFile = File.createTempFile(name, extension, jarDir);
    newJarFile.deleteOnExit();
    // flujo de escritura del nuevo jar
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    // recorrer todos los archivos del jar menos el crosswalk para replicarlos
    try {
        Enumeration<JarEntry> entries = oaiApiJarJarFile.entries();
        while (entries.hasMoreElements()) {
            installerEDMDisplay.showProgress('.');
            JarEntry entry = entries.nextElement();
            if (!entry.getName().equals(edmCrossWalkClass)) {
                JarEntry entryOld = new JarEntry(entry);
                entryOld.setCompressedSize(-1);
                jarOutputStream.putNextEntry(entryOld);
                InputStream intputStream = oaiApiJarJarFile.getInputStream(entry);
                int count;
                byte data[] = new byte[BUFFER_SIZE];
                while ((count = intputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    jarOutputStream.write(data, 0, count);
                }
                intputStream.close();
            }
        }
        installerEDMDisplay.showLn();
        // aadir class compilado
        addClass2Jar(jarOutputStream);
        // cerrar jar original
        oaiApiJarJarFile.close();
        // borrar jar original
        oaiApiJarWorkFile.delete();
        // cambiar jar original por nuevo
        try {
            /*if (newJarFile.renameTo(oaiApiJarWorkFile) && oaiApiJarWorkFile.setExecutable(true, true)) {
            oaiApiJarWorkFile = new File(oaiApiJarName);
            } else {
            throw new IOException();
            }*/
            if (jarOutputStream != null)
                jarOutputStream.close();
            FileUtils.moveFile(newJarFile, oaiApiJarWorkFile);
            oaiApiJarWorkFile.setExecutable(true, true);
            oaiApiJarWorkFile = new File(oaiApiJarName);
        } catch (Exception io) {
            io.printStackTrace();
            throw new IOException();
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}

From source file:org.hyperic.hq.product.server.session.ProductPluginDeployer.java

private void unpackJar(File pluginJarFile, File destDir, String prefix) throws Exception {

    JarFile jar = null;//from   w  ww  .ja v  a 2 s  .  c o  m
    try {
        jar = new JarFile(pluginJarFile);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            JarEntry entry = e.nextElement();
            String name = entry.getName();

            if (name.startsWith(prefix)) {
                name = name.substring(prefix.length());
                if (name.length() == 0) {
                    continue;
                }
                File file = new File(destDir, name);
                if (entry.isDirectory()) {
                    file.mkdirs();
                } else {
                    FileUtil.copyStream(jar.getInputStream(entry), new FileOutputStream(file));
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        if (jar != null)
            jar.close();
    }
}