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:net.rim.ejde.internal.packaging.PackagingManager.java

/**
 * Checks if a jar file is a MidletJar created by rapc.
 *
 * @param f/*from   w w w.ja va2s  .  c  o  m*/
 * @return
 */
static public int getJarFileType(File f) {
    int type = 0x0;
    if (!f.exists()) {
        return type;
    }
    java.util.jar.JarFile jar = null;
    try {
        jar = new java.util.jar.JarFile(f, false);
        java.util.jar.Manifest manifest = jar.getManifest();
        if (manifest != null) {
            java.util.jar.Attributes attributes = manifest.getMainAttributes();
            String profile = attributes.getValue("MicroEdition-Profile");
            if (profile != null) {
                if ("MIDP-1.0".equals(profile) || "MIDP-2.0".equals(profile)) {
                    type = type | MIDLET_JAR;
                }
            }
        }
        Enumeration<JarEntry> entries = jar.entries();
        JarEntry entry;
        String entryName;
        InputStream is = null;
        IClassFileReader classFileReader = null;
        // check the attribute of the class files in the jar file
        for (; entries.hasMoreElements();) {
            entry = entries.nextElement();
            entryName = entry.getName();
            if (entryName.endsWith(IConstants.CLASS_FILE_EXTENSION_WITH_DOT)) {
                is = jar.getInputStream(entry);
                classFileReader = ToolFactory.createDefaultClassFileReader(is, IClassFileReader.ALL);
                if (isEvisceratedClass(classFileReader)) {
                    type = type | EVISCERATED_JAR;
                    break;
                }
            }
        }
    } catch (IOException e) {
        _log.error(e.getMessage());
    } finally {
        try {
            if (jar != null) {
                jar.close();
            }
        } catch (IOException e) {
            _log.error(e.getMessage());
        }
    }
    return type;
}

From source file:org.eclipse.wb.internal.core.editor.palette.dialogs.ImportArchiveDialog.java

private List<PaletteElementInfo> extractElementsFromJarByManifest(JarInputStream jarStream) throws Exception {
    List<PaletteElementInfo> elements = Lists.newArrayList();
    Manifest manifest = jarStream.getManifest();
    // check manifest, if null find it
    if (manifest == null) {
        try {/* w  ww.jav  a 2s  .co  m*/
            while (true) {
                JarEntry entry = jarStream.getNextJarEntry();
                if (entry == null) {
                    break;
                }
                if (JarFile.MANIFEST_NAME.equalsIgnoreCase(entry.getName())) {
                    // read manifest data
                    byte[] buffer = IOUtils.toByteArray(jarStream);
                    jarStream.closeEntry();
                    // create manifest
                    manifest = new Manifest(new ByteArrayInputStream(buffer));
                    break;
                }
            }
        } catch (Throwable e) {
            DesignerPlugin.log(e);
            manifest = null;
        }
    }
    if (manifest != null) {
        // extract all "Java-Bean: True" classes
        for (Iterator<Map.Entry<String, Attributes>> I = manifest.getEntries().entrySet().iterator(); I
                .hasNext();) {
            Map.Entry<String, Attributes> mapElement = I.next();
            Attributes attributes = mapElement.getValue();
            if (JAVA_BEAN_VALUE.equalsIgnoreCase(attributes.getValue(JAVA_BEAN_KEY))) {
                String beanClass = mapElement.getKey();
                if (beanClass == null || beanClass.length() <= JAVA_BEAN_CLASS_SUFFIX.length()) {
                    continue;
                }
                // convert 'aaa/bbb/ccc.class' to 'aaa.bbb.ccc'
                PaletteElementInfo element = new PaletteElementInfo();
                element.className = StringUtils.substringBeforeLast(beanClass, JAVA_BEAN_CLASS_SUFFIX)
                        .replace('/', '.');
                element.name = CodeUtils.getShortClass(element.className);
                elements.add(element);
            }
        }
    }
    return elements;
}

From source file:org.exist.repo.Deployment.java

public DocumentImpl getDescriptor(File jar) throws IOException, PackageException {
    final InputStream istream = new BufferedInputStream(new FileInputStream(jar));
    final JarInputStream jis = new JarInputStream(istream);
    JarEntry entry;
    DocumentImpl doc = null;//from   w  ww .  j a v a  2  s . c  o  m
    while ((entry = jis.getNextJarEntry()) != null) {
        if (!entry.isDirectory() && "expath-pkg.xml".equals(entry.getName())) {
            final ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int c;
            final byte[] b = new byte[4096];
            while ((c = jis.read(b)) > 0) {
                bos.write(b, 0, c);
            }

            bos.close();

            final byte[] data = bos.toByteArray();

            final ByteArrayInputStream bis = new ByteArrayInputStream(data);
            try {
                doc = DocUtils.parse(broker.getBrokerPool(), null, bis);
            } catch (final XPathException e) {
                throw new PackageException("Error while parsing expath-pkg.xml: " + e.getMessage(), e);
            }
            break;
        }
    }
    jis.close();
    return doc;
}

From source file:org.argouml.moduleloader.ModuleLoader2.java

/**
 * Check a jar file for an ArgoUML extension/module.
 * <p>//from   w  w  w  . j a  v  a2s.c  om
 *
 * If there isn't a manifest or it isn't readable, we fall back to using the
 * raw JAR entries.
 *
 * @param classloader
 *            The classloader to use.
 * @param file
 *            The file to process.
 * @throws ClassNotFoundException
 *             if the manifest file contains a class that doesn't exist.
 */
private void processJarFile(ClassLoader classloader, File file) throws ClassNotFoundException {

    LOG.log(Level.INFO, "Opening jar file {0}", file);
    JarFile jarfile = null;
    try {
        jarfile = new JarFile(file);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Unable to open " + file, e);
        return;
    } finally {
        IOUtils.closeQuietly(jarfile);
    }

    Manifest manifest;
    try {
        manifest = jarfile.getManifest();
        if (manifest == null) {
            // We expect all extensions to have a manifest even though we
            // can operate without one if necessary.
            LOG.log(Level.WARNING, file + " does not have a manifest");
        }
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Unable to read manifest of " + file, e);
        return;
    }

    // TODO: It is a performance drain to load all classes at startup time.
    // They should be lazy loaded when needed. Instead of scanning all
    // classes for ones which implement our loadable module interface, we
    // should use a manifest entry or a special name/name pattern that we
    // look for to find the single main module class to load here. - tfm

    boolean loadedClass = false;
    if (manifest == null) {
        Enumeration<JarEntry> jarEntries = jarfile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry entry = jarEntries.nextElement();
            loadedClass = loadedClass | processEntry(classloader, entry.getName());
        }
    } else {
        Map<String, Attributes> entries = manifest.getEntries();
        for (String key : entries.keySet()) {
            // Look for our specification
            loadedClass = loadedClass | processEntry(classloader, key);
        }
    }

    // Add this to search list for I18N properties
    // (Done for both modules & localized property file sets)
    Translator.addClassLoader(classloader);

    // If it didn't have a loadable module class and it doesn't look like
    // a localized property set, warn the user that something funny is in
    // their extension directory
    if (!loadedClass && !file.getName().contains("argouml-i18n-")) {
        LOG.log(Level.SEVERE, "Failed to find any loadable ArgoUML modules in jar " + file);
    }
}

From source file:com.ecyrd.jspwiki.ui.TemplateManager.java

/**
 * List all installed i18n language properties
 * //from w  w w  .j av  a2 s. c  om
 * @param pageContext
 * @return map of installed Languages (with help of Juan Pablo Santos Rodriguez)
 * @since 2.7.x
 */
public Map listLanguages(PageContext pageContext) {
    LinkedHashMap<String, String> resultMap = new LinkedHashMap<String, String>();

    String clientLanguage = ((HttpServletRequest) pageContext.getRequest()).getLocale().toString();
    JarInputStream jarStream = null;

    try {
        JarEntry entry;
        InputStream inputStream = pageContext.getServletContext().getResourceAsStream(I18NRESOURCE_PATH);
        jarStream = new JarInputStream(inputStream);

        while ((entry = jarStream.getNextJarEntry()) != null) {
            String name = entry.getName();

            if (!entry.isDirectory() && name.startsWith(I18NRESOURCE_PREFIX)
                    && name.endsWith(I18NRESOURCE_SUFFIX)) {
                name = name.substring(I18NRESOURCE_PREFIX.length(), name.lastIndexOf(I18NRESOURCE_SUFFIX));

                Locale locale = new Locale(name.substring(0, 2),
                        ((name.indexOf("_") == -1) ? "" : name.substring(3, 5)));

                String defaultLanguage = "";

                if (clientLanguage.startsWith(name)) {
                    defaultLanguage = LocaleSupport.getLocalizedMessage(pageContext, I18NDEFAULT_LOCALE);
                }

                resultMap.put(name, locale.getDisplayName(locale) + " " + defaultLanguage);
            }
        }
    } catch (IOException ioe) {
        if (log.isDebugEnabled())
            log.debug("Could not search jar file '" + I18NRESOURCE_PATH
                    + "'for properties files due to an IOException: \n" + ioe.getMessage());
    } finally {
        if (jarStream != null) {
            try {
                jarStream.close();
            } catch (IOException e) {
            }
        }
    }

    return resultMap;
}

From source file:org.apache.axis2.jaxws.util.WSDL4JWrapper.java

private URL getURLFromJAR(URLClassLoader urlLoader, URL relativeURL) {
    URL[] urlList = null;/*from w w w . j  ava 2  s .c  om*/
    ResourceFinderFactory rff = (ResourceFinderFactory) MetadataFactoryRegistry
            .getFactory(ResourceFinderFactory.class);
    ResourceFinder cf = rff.getResourceFinder();
    if (log.isDebugEnabled()) {
        log.debug("ResourceFinderFactory: " + rff.getClass().getName());
        log.debug("ResourceFinder: " + cf.getClass().getName());
    }

    urlList = cf.getURLs(urlLoader);
    if (urlList == null) {
        if (log.isDebugEnabled()) {
            log.debug("No URL's found in URL ClassLoader");
        }
        throw ExceptionFactory.makeWebServiceException(Messages.getMessage("WSDL4JWrapperErr1"));
    }

    for (URL url : urlList) {
        if ("file".equals(url.getProtocol())) {
            // Insure that Windows spaces are properly handled in the URL
            final File f = new File(url.getPath().replaceAll("%20", " "));
            // If file is not of type directory then its a jar file
            if (isAFile(f)) {
                try {
                    JarFile jf = (JarFile) AccessController.doPrivileged(new PrivilegedExceptionAction() {
                        public Object run() throws IOException {
                            return new JarFile(f);
                        }
                    });
                    Enumeration<JarEntry> 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 = 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) {
                    throw ExceptionFactory.makeWebServiceException(e);
                }
            }
        }
    }

    return null;
}

From source file:net.rim.ejde.internal.packaging.PackagingJob.java

/**
 * If the cod file represented by the given <code>codFilePath</code> contains sibling cod file, un-zip it and copy all sibling
 * cod files to the <code>destinationFolderPath</code>. If the cod file is a single cod file, just copy it to the
 * <code>destinationFolderPath</code>.
 *
 * @param codFilePath/*from w  w  w.  j a va  2 s  .c  o m*/
 * @param destinationFolderPath
 * @throws CoreException
 */
private void copySiblingCod(IPath codFilePath, IPath destinationFolderPath) throws CoreException {
    boolean hasSiblingCod = false;
    File codFile = codFilePath.toFile();
    try {
        JarFile zipFile = new JarFile(codFile);
        Enumeration<JarEntry> entries = zipFile.entries();
        if (entries.hasMoreElements()) {
            hasSiblingCod = true;
            JarEntry entry;
            for (; entries.hasMoreElements();) {
                entry = entries.nextElement();
                if (entry.isDirectory()) {
                    // this should not happen
                    continue;
                }
                InputStream is = zipFile.getInputStream(entry);
                File outputFile = destinationFolderPath.append(entry.getName()).toFile();
                PackagingManager.copyInputStream(is,
                        new BufferedOutputStream(new FileOutputStream(outputFile)));
            }
        } else {
            hasSiblingCod = false;
        }
    } catch (IOException e) {
        if (codFile.exists()) {
            // if the cod file does not contain any sibling file, we get IOException
            hasSiblingCod = false;
        } else {
            _log.error(e);
        }
    } finally {
        if (!hasSiblingCod) {
            // if the cod file is a single cod file, copy it to the destination
            DeploymentHelper.executeCopy(codFile, destinationFolderPath.append(codFile.getName()).toFile());
        }
    }
}

From source file:com.greenpepper.maven.plugin.SpecificationRunnerMojo.java

private void extractHtmlReportSummary() throws IOException, URISyntaxException {
    final String path = "html-summary-report";
    final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

    forceMkdir(reportsDirectory);/*from ww w .j a v  a 2  s .co m*/
    if (jarFile.isFile()) { // Run with JAR file
        JarFile jar = new JarFile(jarFile);
        Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            String name = jarEntry.getName();
            if (name.startsWith(path)) { //filter according to the path
                File file = getFile(reportsDirectory, substringAfter(name, path));
                if (jarEntry.isDirectory()) {
                    forceMkdir(file);
                } else {
                    forceMkdir(file.getParentFile());
                    if (!file.exists()) {
                        copyInputStreamToFile(jar.getInputStream(jarEntry), file);
                    }
                }
            }
        }
        jar.close();
    } else { // Run with IDE
        URL url = getClass().getResource("/" + path);
        if (url != null) {
            File apps = FileUtils.toFile(url);
            if (apps.isDirectory()) {
                copyDirectory(apps, reportsDirectory);
            } else {
                throw new IllegalStateException(
                        format("Internal resource '%s' should be a directory.", apps.getAbsolutePath()));
            }
        } else {
            throw new IllegalStateException(format("Internal resource '/%s' should be here.", path));
        }
    }
}

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

private Map<String, Reader> getXmlReaderMap(JarFile jarFile) throws IOException {
    final Map<String, Reader> rtn = new HashMap<String, Reader>();
    final Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        final JarEntry entry = entries.nextElement();
        if (entry.isDirectory()) {
            continue;
        }//from   www.  ja  va  2 s .  c om
        if (!entry.getName().toLowerCase().endsWith(".xml")) {
            continue;
        }
        InputStream is = null;
        try {
            is = jarFile.getInputStream(entry);
            final BufferedReader br = new BufferedReader(new InputStreamReader(is));
            final StringBuilder buf = new StringBuilder();
            String tmp;
            while (null != (tmp = br.readLine())) {
                buf.append(tmp);
            }
            rtn.put(entry.getName(), new NoCloseStringReader(buf.toString()));
        } finally {
            close(is);
        }
    }
    return rtn;
}

From source file:com.evolveum.midpoint.test.ldap.OpenDJController.java

/**
 * Extract template from class// w ww.ja v  a2 s.  com
 */
private void extractTemplate(File dst, String templateName) throws IOException, URISyntaxException {

    LOGGER.info("Extracting OpenDJ template....");
    if (!dst.exists()) {
        LOGGER.debug("Creating target dir {}", dst.getPath());
        dst.mkdirs();
    }

    templateRoot = new File(DATA_TEMPLATE_DIR, templateName);
    String templateRootPath = DATA_TEMPLATE_DIR + "/" + templateName; // templateRoot.getPath does not work on Windows, as it puts "\" into the path name (leading to problems with getSystemResource)

    // Determing if we need to extract from JAR or directory
    if (templateRoot.isDirectory()) {
        LOGGER.trace("Need to do directory copy.");
        MiscUtil.copyDirectory(templateRoot, dst);
        return;
    }

    LOGGER.debug("Try to localize OpenDJ Template in JARs as " + templateRootPath);

    URL srcUrl = ClassLoader.getSystemResource(templateRootPath);
    LOGGER.debug("srcUrl " + srcUrl);
    // sample:
    // file:/C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar!/test-data/opendj.template
    // output:
    // /C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar
    //
    // beware that in the URL there can be spaces encoded as %20, e.g.
    // file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar!/test-data/opendj.template
    //
    if (srcUrl.getPath().contains("!/")) {
        URI srcFileUri = new URI(srcUrl.getPath().split("!/")[0]); // e.g. file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar
        File srcFile = new File(srcFileUri);
        JarFile jar = new JarFile(srcFile);
        LOGGER.debug("Extracting OpenDJ from JAR file {} to {}", srcFile.getPath(), dst.getPath());

        Enumeration<JarEntry> entries = jar.entries();

        JarEntry e;
        byte buf[] = new byte[655360];
        while (entries.hasMoreElements()) {
            e = entries.nextElement();

            // skip other files
            if (!e.getName().contains(templateRootPath)) {
                continue;
            }

            // prepare destination file
            String filepath = e.getName().substring(templateRootPath.length());
            File dstFile = new File(dst, filepath);

            // test if directory
            if (e.isDirectory()) {
                LOGGER.debug("Create directory: {}", dstFile.getAbsolutePath());
                dstFile.mkdirs();
                continue;
            }

            LOGGER.debug("Extract {} to {}", filepath, dstFile.getAbsolutePath());
            // Find file on classpath
            InputStream is = ClassLoader.getSystemResourceAsStream(e.getName());
            // InputStream is = jar.getInputStream(e); //old way

            // Copy content
            OutputStream out = new FileOutputStream(dstFile);
            int len;
            while ((len = is.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.close();
            is.close();
        }
        jar.close();
    } else {
        try {
            File file = new File(srcUrl.toURI());
            File[] files = file.listFiles();
            for (File subFile : files) {
                if (subFile.isDirectory()) {
                    MiscUtil.copyDirectory(subFile, new File(dst, subFile.getName()));
                } else {
                    MiscUtil.copyFile(subFile, new File(dst, subFile.getName()));
                }
            }
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }
    LOGGER.debug("OpenDJ Extracted");
}