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.jdesktop.wonderland.modules.service.PendingManager.java

/**
 * Takes a base directory (which must exist and be readable) and expands
 * the contents of the archive module into that directory given the
 * URL of the module encoded as a jar file
 * //from w  w w  . j  a va  2  s  .c om
 * @param root The base directory in which the module is expanded
 * @throw IOException Upon error
 */
private void expand(File root, File jar) throws IOException {
    /*
     * Loop through each entry, fetch its input stream, and write to an
     * output stream for the file.
     */
    JarFile jarFile = new JarFile(jar);
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements() == true) {
        /* Fetch the next entry, its name is the relative file name */
        JarEntry entry = entries.nextElement();
        String entryName = entry.getName();
        long size = entry.getSize();

        /* Don't expand anything that beings with META-INF */
        if (entryName.startsWith("META-INF") == true) {
            continue;
        }

        /* Ignore if it is a directory, then create it */
        if (entryName.endsWith("/") == true) {
            File file = new File(root, entryName);
            file.mkdirs();
            continue;
        }

        /* Write out to a file in 'root' */
        File file = new File(root, entryName);
        InputStream jis = jarFile.getInputStream(entry);
        FileOutputStream os = new FileOutputStream(file);
        byte[] b = new byte[PendingManager.CHUNK_SIZE];
        long read = 0;
        while (read < size) {
            int len = jis.read(b);
            if (len == -1) {
                break;
            }
            read += len;
            os.write(b, 0, len);
        }
        jis.close();
        os.close();
    }
}

From source file:net.lightbody.bmp.proxy.jetty.util.JarFileResource.java

/**
 * Returns true if the respresenetd resource exists.
 *///from w w  w .  jav  a  2  s .  c  o m
public boolean exists() {
    if (_exists)
        return true;

    if (_urlString.endsWith("!/")) {
        String file_url = _urlString.substring(4, _urlString.length() - 2);
        try {
            return newResource(file_url).exists();
        } catch (Exception e) {
            LogSupport.ignore(log, e);
            return false;
        }
    }

    boolean check = checkConnection();

    // Is this a root URL?
    if (_jarUrl != null && _path == null) {
        // Then if it exists it is a directory
        _directory = check;
        return true;
    } else {
        // Can we find a file for it?
        JarFile jarFile = null;
        if (check)
            // Yes
            jarFile = _jarFile;
        else {
            // No - so lets look if the root entry exists.
            try {
                jarFile = ((JarURLConnection) ((new URL(_jarUrl)).openConnection())).getJarFile();
            } catch (Exception e) {
                LogSupport.ignore(log, e);
            }
        }

        // Do we need to look more closely?
        if (jarFile != null && _entry == null && !_directory) {
            // OK - we have a JarFile, lets look at the entries for our path
            Enumeration e = jarFile.entries();
            while (e.hasMoreElements()) {
                JarEntry entry = (JarEntry) e.nextElement();
                String name = entry.getName().replace('\\', '/');

                // Do we have a match
                if (name.equals(_path)) {
                    _entry = entry;
                    // Is the match a directory
                    _directory = _path.endsWith("/");
                    break;
                } else if (_path.endsWith("/")) {
                    if (name.startsWith(_path)) {
                        _directory = true;
                        break;
                    }
                } else if (name.startsWith(_path) && name.length() > _path.length()
                        && name.charAt(_path.length()) == '/') {
                    _directory = true;
                    break;
                }
            }
        }
    }

    _exists = (_directory || _entry != null);
    return _exists;
}

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

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleJarPath = getModuleJarPath(moduleId);
    Files.deleteIfExists(moduleJarPath);
    JarFile sourceJarFile;/*from ww w  . j av  a2 s. c  om*/
    try {
        sourceJarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    JarOutputStream destJarFile = new JarOutputStream(new FileOutputStream(moduleJarPath.toFile()));
    try {
        String moduleSpecFileName = moduleSpecSerializer.getModuleSpecFileName();
        Enumeration<JarEntry> sourceEntries = sourceJarFile.entries();
        while (sourceEntries.hasMoreElements()) {
            JarEntry sourceEntry = sourceEntries.nextElement();
            if (sourceEntry.getName().equals(moduleSpecFileName)) {
                // avoid double entry for module spec
                continue;
            }
            destJarFile.putNextEntry(sourceEntry);
            if (!sourceEntry.isDirectory()) {
                InputStream inputStream = sourceJarFile.getInputStream(sourceEntry);
                IOUtils.copy(inputStream, destJarFile);
                IOUtils.closeQuietly(inputStream);
            }
            destJarFile.closeEntry();
        }
        // write the module spec
        String serialized = moduleSpecSerializer.serialize(moduleSpec);
        JarEntry moduleSpecEntry = new JarEntry(moduleSpecSerializer.getModuleSpecFileName());
        destJarFile.putNextEntry(moduleSpecEntry);
        IOUtils.write(serialized, destJarFile);
        destJarFile.closeEntry();
    } finally {
        IOUtils.closeQuietly(sourceJarFile);
        IOUtils.closeQuietly(destJarFile);
    }
    // update the timestamp on the jar file to indicate that the module has been updated
    Files.setLastModifiedTime(moduleJarPath, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

From source file:com.iflytek.edu.cloud.frame.doc.ServiceDocBuilder.java

private void doServiceJavaSource(String jarFileUrl) throws IOException {
    JarFile jarFile = new JarFile(jarFileUrl);
    try {//from   w  w w .j a  v  a  2 s.  c o m
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Looking for matching resources in jar file [" + jarFileUrl + "]");
        }

        for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
            JarEntry entry = entries.nextElement();

            String entryPath = entry.getName();
            if (entryPath.endsWith(".java")) {
                InputStream inputStream = jarFile.getInputStream(entry);
                builder.addSource(new InputStreamReader(inputStream, "UTF-8"));
            }
        }
    } finally {
        jarFile.close();
    }
}

From source file:org.nuxeo.osgi.JarBundleFile.java

@Override
public Collection<BundleFile> findNestedBundles(File tmpDir) throws IOException {
    URL base = new URL("jar:" + new File(jarFile.getName()).toURI().toURL().toExternalForm() + "!/");
    String fileName = getFileName();
    Enumeration<JarEntry> entries = jarFile.entries();
    List<BundleFile> nested = new ArrayList<BundleFile>();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (entry.getName().endsWith(".jar")) {
            String location = base + path;
            String name = path.replace('/', '_');
            File dest = new File(tmpDir, fileName + '-' + name);
            extractNestedJar(jarFile, entry, dest);
            nested.add(new NestedJarBundleFile(location, dest));
        }// w w  w.j  a v  a2  s .  com
    }
    return nested;
}

From source file:org.openmrs.module.web.WebModuleUtil.java

/**
 * Performs the webapp specific startup needs for modules Normal startup is done in
 * {@link ModuleFactory#startModule(Module)} If delayContextRefresh is true, the spring context
 * is not rerun. This will save a lot of time, but it also means that the calling method is
 * responsible for restarting the context if necessary (the calling method will also have to
 * call {@link #loadServlets(Module, ServletContext)} and
 * {@link #loadFilters(Module, ServletContext)}).<br>
 * <br>/* ww w. ja va2 s.  c om*/
 * If delayContextRefresh is true and this module should have caused a context refresh, a true
 * value is returned. Otherwise, false is returned
 *
 * @param mod Module to start
 * @param servletContext the current ServletContext
 * @param delayContextRefresh true/false whether or not to do the context refresh
 * @return boolean whether or not the spring context need to be refreshed
 */
public static boolean startModule(Module mod, ServletContext servletContext, boolean delayContextRefresh) {

    if (log.isDebugEnabled()) {
        log.debug("trying to start module " + mod);
    }

    // only try and start this module if the api started it without a
    // problem.
    if (ModuleFactory.isModuleStarted(mod) && !mod.hasStartupError()) {

        String realPath = getRealPath(servletContext);

        if (realPath == null) {
            realPath = System.getProperty("user.dir");
        }

        File webInf = new File(realPath + "/WEB-INF".replace("/", File.separator));
        if (!webInf.exists()) {
            webInf.mkdir();
        }

        copyModuleMessagesIntoWebapp(mod, realPath);
        log.debug("Done copying messages");

        // flag to tell whether we added any xml/dwr/etc changes that necessitate a refresh
        // of the web application context
        boolean moduleNeedsContextRefresh = false;

        // copy the html files into the webapp (from /web/module/ in the module)
        // also looks for a spring context file. If found, schedules spring to be restarted
        JarFile jarFile = null;
        OutputStream outStream = null;
        InputStream inStream = null;
        try {
            File modFile = mod.getFile();
            jarFile = new JarFile(modFile);
            Enumeration<JarEntry> entries = jarFile.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                log.debug("Entry name: " + name);
                if (name.startsWith("web/module/")) {
                    // trim out the starting path of "web/module/"
                    String filepath = name.substring(11);

                    StringBuffer absPath = new StringBuffer(realPath + "/WEB-INF");

                    // If this is within the tag file directory, copy it into /WEB-INF/tags/module/moduleId/...
                    if (filepath.startsWith("tags/")) {
                        filepath = filepath.substring(5);
                        absPath.append("/tags/module/");
                    }
                    // Otherwise, copy it into /WEB-INF/view/module/moduleId/...
                    else {
                        absPath.append("/view/module/");
                    }

                    // if a module id has a . in it, we should treat that as a /, i.e. files in the module
                    // ui.springmvc should go in folder names like .../ui/springmvc/...
                    absPath.append(mod.getModuleIdAsPath() + "/" + filepath);
                    if (log.isDebugEnabled()) {
                        log.debug("Moving file from: " + name + " to " + absPath);
                    }

                    // get the output file
                    File outFile = new File(absPath.toString().replace("/", File.separator));
                    if (entry.isDirectory()) {
                        if (!outFile.exists()) {
                            outFile.mkdirs();
                        }
                    } else {
                        // make the parent directories in case it doesn't exist
                        File parentDir = outFile.getParentFile();
                        if (!parentDir.exists()) {
                            parentDir.mkdirs();
                        }

                        //if (outFile.getName().endsWith(".jsp") == false)
                        //   outFile = new File(absPath.replace("/", File.separator) + MODULE_NON_JSP_EXTENSION);

                        // copy the contents over to the webapp for non directories
                        outStream = new FileOutputStream(outFile, false);
                        inStream = jarFile.getInputStream(entry);
                        OpenmrsUtil.copyFile(inStream, outStream);
                    }
                } else if (name.equals("moduleApplicationContext.xml")
                        || name.equals("webModuleApplicationContext.xml")) {
                    moduleNeedsContextRefresh = true;
                } else if (name.equals(mod.getModuleId() + "Context.xml")) {
                    String msg = "DEPRECATED: '" + name
                            + "' should be named 'moduleApplicationContext.xml' now. Please update/upgrade. ";
                    throw new ModuleException(msg, mod.getModuleId());
                }
            }
        } catch (IOException io) {
            log.warn("Unable to copy files from module " + mod.getModuleId() + " to the web layer", io);
        } finally {
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException io) {
                    log.warn("Couldn't close jar file: " + jarFile.getName(), io);
                }
            }
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException io) {
                    log.warn("Couldn't close InputStream: " + io);
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException io) {
                    log.warn("Couldn't close OutputStream: " + io);
                }
            }
        }

        // find and add the dwr code to the dwr-modules.xml file (if defined)
        InputStream inputStream = null;
        try {
            Document config = mod.getConfig();
            Element root = config.getDocumentElement();
            if (root.getElementsByTagName("dwr").getLength() > 0) {

                // get the dwr-module.xml file that we're appending our code to
                File f = new File(realPath + "/WEB-INF/dwr-modules.xml".replace("/", File.separator));

                // testing if file exists
                if (!f.exists()) {
                    // if it does not -> needs to be created
                    createDwrModulesXml(realPath);
                }

                inputStream = new FileInputStream(f);
                Document dwrmodulexml = getDWRModuleXML(inputStream, realPath);
                Element outputRoot = dwrmodulexml.getDocumentElement();

                // loop over all of the children of the "dwr" tag
                Node node = root.getElementsByTagName("dwr").item(0);
                Node current = node.getFirstChild();

                while (current != null) {
                    if ("allow".equals(current.getNodeName()) || "signatures".equals(current.getNodeName())
                            || "init".equals(current.getNodeName())) {
                        ((Element) current).setAttribute("moduleId", mod.getModuleId());
                        outputRoot.appendChild(dwrmodulexml.importNode(current, true));
                    }

                    current = current.getNextSibling();
                }

                moduleNeedsContextRefresh = true;

                // save the dwr-modules.xml file.
                OpenmrsUtil.saveDocument(dwrmodulexml, f);
            }
        } catch (FileNotFoundException e) {
            throw new ModuleException(realPath + "/WEB-INF/dwr-modules.xml file doesn't exist.", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException io) {
                    log.error("Error while closing input stream", io);
                }
            }
        }

        // mark to delete the entire module web directory on exit
        // this will usually only be used when an improper shutdown has occurred.
        String folderPath = realPath + "/WEB-INF/view/module/" + mod.getModuleIdAsPath();
        File outFile = new File(folderPath.replace("/", File.separator));
        outFile.deleteOnExit();

        // additional checks on module needing a context refresh
        if (moduleNeedsContextRefresh == false && mod.getAdvicePoints() != null
                && mod.getAdvicePoints().size() > 0) {

            // AOP advice points are only loaded during the context refresh now.
            // if the context hasn't been marked to be refreshed yet, mark it
            // now if this module defines some advice
            moduleNeedsContextRefresh = true;

        }

        // refresh the spring web context to get the just-created xml
        // files into it (if we copied an xml file)
        if (moduleNeedsContextRefresh && delayContextRefresh == false) {
            if (log.isDebugEnabled()) {
                log.debug("Refreshing context for module" + mod);
            }

            try {
                refreshWAC(servletContext, false, mod);
                log.debug("Done Refreshing WAC");
            } catch (Exception e) {
                String msg = "Unable to refresh the WebApplicationContext";
                mod.setStartupErrorMessage(msg, e);

                if (log.isWarnEnabled()) {
                    log.warn(msg + " for module: " + mod.getModuleId(), e);
                }

                try {
                    stopModule(mod, servletContext, true);
                    ModuleFactory.stopModule(mod, true, true); //remove jar from classloader play
                } catch (Exception e2) {
                    // exception expected with most modules here
                    if (log.isWarnEnabled()) {
                        log.warn("Error while stopping a module that had an error on refreshWAC", e2);
                    }
                }

                // try starting the application context again
                refreshWAC(servletContext, false, mod);

                notifySuperUsersAboutModuleFailure(mod);
            }

        }

        if (!delayContextRefresh && ModuleFactory.isModuleStarted(mod)) {
            // only loading the servlets/filters if spring is refreshed because one
            // might depend on files being available in spring
            // if the caller wanted to delay the refresh then they are responsible for
            // calling these two methods on the module

            // find and cache the module's servlets
            //(only if the module started successfully previously)
            log.debug("Loading servlets and filters for module: " + mod);
            loadServlets(mod, servletContext);
            loadFilters(mod, servletContext);
        }

        // return true if the module needs a context refresh and we didn't do it here
        return (moduleNeedsContextRefresh && delayContextRefresh == true);

    }

    // we aren't processing this module, so a context refresh is not necessary
    return false;
}

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  ava2s. 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.bimserver.plugins.classloaders.FileJarClassLoader.java

private void loadEmbeddedJarFileSystems(Path path) {
    try {/*from   ww  w.  j a v a2 s  .co m*/
        if (Files.isDirectory(path)) {
            for (Path subPath : PathUtils.list(path)) {
                loadEmbeddedJarFileSystems(subPath);
            }
        } else {
            // This is annoying, but we are caching the contents of JAR files within JAR files in memory, could not get the JarFileSystem to work with jar:jar:file URI's
            // Also there is a problem with not being able to change position within a file, at least in the JarFileSystem
            // It looks like there are 2 other solutions to this problem:
            // - Copy the embedded JAR files to a tmp directory, and load from there with a JarFileSystem wrapper (at some stage we were doing this for all JAR contents, 
            // resulted in 50.000 files, which was annoying, but a few JAR files probably won't hurt
            // - Don't allow plugins to have embedded JAR's, could force them to extract all dependencies...
            //
            if (path.getFileName().toString().toLowerCase().endsWith(".jar")) {
                JarInputStream jarInputStream = new JarInputStream(Files.newInputStream(path));
                try {
                    JarEntry jarEntry = jarInputStream.getNextJarEntry();
                    while (jarEntry != null) {
                        jarContent.put(jarEntry.getName(), IOUtils.toByteArray(jarInputStream));
                        jarEntry = jarInputStream.getNextJarEntry();
                    }
                } finally {
                    jarInputStream.close();
                }
            }
        }
    } catch (IOException e) {
        LOGGER.error("", e);
    }
}

From source file:org.openspaces.pu.container.standalone.StandaloneProcessingUnitContainerProvider.java

private boolean isWithinDir(JarEntry jarEntry, String dir) {
    return jarEntry.getName().startsWith(dir + "/") && jarEntry.getName().length() > (dir + "/").length();
}

From source file:com.taobao.android.builder.tools.asm.ClazzBasicHandler.java

public void execute() throws IOException {

    logger.info("[ClazzReplacer] rewriteJar from " + jar.getAbsolutePath() + " to " + outJar.getAbsolutePath());

    JarFile jarFile = new JarFile(jar);

    JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(outJar)));

    Enumeration<JarEntry> jarFileEntries = jarFile.entries();

    while (jarFileEntries.hasMoreElements()) {

        JarEntry ze = jarFileEntries.nextElement();

        String pathName = ze.getName();

        logger.info(jar.getAbsolutePath() + "->" + pathName);

        if (!pathName.endsWith(".class")) {
            justCopy(jarFile, jos, ze, pathName);
            continue;
        }/*from w ww. j a v a 2  s . c o m*/

        handleClazz(jarFile, jos, ze, pathName);

    }

    jarFile.close();
    //        IOUtils.closeQuietly(fileOutputStream);
    IOUtils.closeQuietly(jos);
}