Example usage for java.util.jar JarFile entries

List of usage examples for java.util.jar JarFile entries

Introduction

In this page you can find the example usage for java.util.jar JarFile entries.

Prototype

public Enumeration<JarEntry> entries() 

Source Link

Document

Returns an enumeration of the jar file entries.

Usage

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;
    try {//from   w  w  w  .j  av  a  2  s  .co  m
        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:org.kantega.revoc.source.MavenSourceArtifactSourceSource.java

private MavenSourceInfo parseInfo(String filePath, URL resource) {

    File file = new File(filePath);

    JarFile jarFile = null;
    boolean isNewFile = false;
    try {//from   ww w . java  2 s  .  c o m
        URLConnection urlConnection = resource.openConnection();
        if (urlConnection instanceof JarURLConnection) {
            jarFile = ((JarURLConnection) urlConnection).getJarFile();
        } else {
            jarFile = new JarFile(file);
            isNewFile = true;
        }
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String prefix = "META-INF/maven/";
            String propSuffix = "/pom.properties";

            if (entry.getName().startsWith(prefix) && entry.getName().endsWith(propSuffix)) {
                Properties props = new Properties();
                InputStream inputStream = jarFile.getInputStream(entry);
                props.load(inputStream);
                inputStream.close();
                String groupId = props.getProperty("groupId");
                String artifactId = props.getProperty("artifactId");
                String version = props.getProperty("version");

                if (file.getName().startsWith(artifactId + "-" + version)) {
                    return new MavenSourceInfo(groupId, artifactId, version);
                }

            }
        }
        return null;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (isNewFile) {
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

From source file:edu.stanford.muse.email.JarDocCache.java

public Set<Integer> getAllContentIdxs(String prefix) throws IOException, ClassNotFoundException {
    Set<Integer> result = new LinkedHashSet<Integer>();
    JarFile jarFile = null;
    String fname = baseDir + File.separator + prefix + ".contents";
    try {/* w w w.  j  ava2s  .  c  o m*/
        jarFile = new JarFile(fname);
    } catch (Exception e) {
        log.info("No Jar file exists: " + fname);
    }
    if (jarFile == null)
        return result;

    Enumeration<JarEntry> entries = jarFile.entries();
    String suffix = ".content";
    while (entries.hasMoreElements()) {
        JarEntry je = entries.nextElement();
        String s = je.getName();
        if (!s.endsWith(suffix))
            continue;
        String idx_str = s.substring(0, s.length() - suffix.length());
        int index = -1;
        try {
            index = Integer.parseInt(idx_str);
        } catch (Exception e) {
            log.error("Funny file in header: " + index);
        }

        result.add(index);
    }
    return result;
}

From source file:edu.stanford.muse.email.JarDocCache.java

public Map<Integer, Document> getAllHeaders(String prefix) throws IOException, ClassNotFoundException {
    Map<Integer, Document> result = new LinkedHashMap<Integer, Document>();
    JarFile jarFile = null;
    String fname = baseDir + File.separator + prefix + ".headers";
    try {/*from  w  ww.  java 2s  . co  m*/
        jarFile = new JarFile(fname);
    } catch (Exception e) {
        log.info("No Jar file exists: " + fname);
    }
    if (jarFile == null)
        return result;

    Enumeration<JarEntry> entries = jarFile.entries();
    String suffix = ".header";
    while (entries.hasMoreElements()) {
        JarEntry je = entries.nextElement();
        String s = je.getName();
        if (!s.endsWith(suffix))
            continue;
        String idx_str = s.substring(0, s.length() - suffix.length());
        int index = -1;
        try {
            index = Integer.parseInt(idx_str);
        } catch (Exception e) {
            log.error("Funny file in header: " + index);
        }

        ObjectInputStream ois = new ObjectInputStream(jarFile.getInputStream(je));
        Document ed = (Document) ois.readObject();
        ois.close();
        result.put(index, ed);
    }
    return result;
}

From source file:org.guvnor.m2repo.backend.server.M2RepositoryServiceImplTest.java

@Test
public void testDeployArtifact() throws Exception {
    deployArtifact(gavBackend);/*from  w  ww .  ja  v a 2 s  .co  m*/

    Collection<File> files = repo.listFiles();

    boolean found = false;
    for (File file : files) {
        String fileName = file.getName();
        if (fileName.startsWith("guvnor-m2repo-editor-backend-0.0.1") && fileName.endsWith(".jar")) {
            found = true;
            String path = file.getPath();
            String jarPath = path.substring(GuvnorM2Repository.M2_REPO_DIR.length() + 1);
            String pom = GuvnorM2Repository.getPomText(jarPath);
            assertNotNull(pom);
            break;
        }
    }

    assertTrue("Did not find expected file after calling M2Repository.addFile()", found);

    // Test get artifact file
    File file = repo.getArtifactFileFromRepository(gavBackend);
    assertNotNull("Empty file for artifact", file);
    JarFile jarFile = new JarFile(file);
    int count = 0;

    String lastEntryName = null;
    for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
        ++count;
        JarEntry entry = entries.nextElement();
        assertNotEquals("Endless loop.", lastEntryName, entry.getName());
    }
    assertTrue("Empty jar file!", count > 0);
}

From source file:org.jahia.data.templates.ModulesPackage.java

private ModulesPackage(JarFile jarFile) throws IOException {
    modules = new LinkedHashMap<String, PackagedModule>();
    Attributes manifestAttributes = jarFile.getManifest().getMainAttributes();
    version = new Version(manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_VERSION));
    name = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_NAME);
    description = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_DESCRIPTION);
    // read jars/*from ww  w  . j a  v a 2  s.  c  om*/
    Enumeration<JarEntry> jars = jarFile.entries();

    while (jars.hasMoreElements()) {
        JarEntry jar = jars.nextElement();
        JarFile moduleJarFile = null;
        OutputStream output = null;
        if (StringUtils.endsWith(jar.getName(), ".jar")) {
            try {
                InputStream input = jarFile.getInputStream(jar);
                File moduleFile = File.createTempFile(jar.getName(), "");
                output = new FileOutputStream(moduleFile);
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = input.read(bytes)) != -1) {
                    output.write(bytes, 0, read);
                }
                moduleJarFile = new JarFile(moduleFile);
                Attributes moduleManifestAttributes = moduleJarFile.getManifest().getMainAttributes();
                String bundleName = moduleManifestAttributes.getValue(Constants.ATTR_NAME_BUNDLE_SYMBOLIC_NAME);
                String jahiaGroupId = moduleManifestAttributes.getValue(Constants.ATTR_NAME_GROUP_ID);
                if (bundleName == null || jahiaGroupId == null) {
                    throw new IOException(
                            "Jar file " + jar.getName() + " in package does not seems to be a DX bundle.");
                }
                modules.put(bundleName, new PackagedModule(bundleName, moduleManifestAttributes, moduleFile));
            } finally {
                IOUtils.closeQuietly(output);
                if (moduleJarFile != null) {
                    moduleJarFile.close();
                }
            }
        }
    }

    // we finally sort modules based on dependencies
    try {
        sortByDependencies(modules);
    } catch (CycleDetectedException e) {
        throw new JahiaRuntimeException("A cyclic dependency detected in the modules of the supplied package",
                e);
    }
}

From source file:org.mentawai.annotations.ApplicationManagerWithAnnotations.java

@SuppressWarnings("rawtypes")
private void findAnnotatedClasses(String resources) throws IOException {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Enumeration<URL> urls = cl.getResources(resources);
    while (urls.hasMoreElements()) {
        URL url = urls.nextElement();
        if (url.getProtocol().equals("file")) {
            File file = new File(url.getFile());
            findAnnotatedClass(file);/*from ww w.  j a v a 2 s .co m*/
        } else if (url.getProtocol().equals("jar")) {
            URL urlJar = new URL(url.getFile().split("\\!")[0]);
            JarFile jarFile;
            try {
                jarFile = new JarFile(new File(urlJar.toURI().getPath()));
            } catch (URISyntaxException ex) {
                Logger.getLogger(ApplicationManagerWithAnnotations.class.getName()).log(Level.SEVERE, null, ex);
                continue;
            }
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                if (getPackageTestJar().matcher(entry.getName()).matches()
                        && entry.getName().endsWith(".class")) {
                    String className = entry.getName().replace('/', '.').substring(0,
                            entry.getName().length() - 6);
                    try {
                        Class klass = Class.forName(className);
                        if (BaseAction.class.isAssignableFrom(klass)) {
                            System.out.println("Add Annotated Class:" + className);
                            annotatedClasses.add(klass);
                        }
                    } catch (Exception e) {
                        System.out.println("error! this class was not started:" + entry.getName());
                    }
                }
            }
        }
    }
}

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  2s . 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:org.guvnor.m2repo.backend.server.M2MavenRepositoryServiceImplTest.java

@Test
public void testDeployArtifact() throws Exception {
    deployArtifact(gavBackend);/*ww w  . j av  a 2s  .  c o m*/

    Collection<File> files = repo.listFiles();

    boolean found = false;
    for (File file : files) {
        String fileName = file.getName();
        if (fileName.startsWith("guvnor-m2repo-editor-backend-0.0.1") && fileName.endsWith(".jar")) {
            found = true;
            String path = file.getPath();
            String jarPath = path.substring(
                    repo.getM2RepositoryRootDir(ArtifactRepositoryService.GLOBAL_M2_REPO_NAME).length());
            String pom = repo.getPomText(jarPath);
            assertNotNull(pom);
            break;
        }
    }

    assertTrue("Did not find expected file after calling M2Repository.addFile()", found);

    // Test get artifact file
    File file = repo.getArtifactFileFromRepository(gavBackend);
    assertNotNull("Empty file for artifact", file);
    JarFile jarFile = new JarFile(file);
    int count = 0;

    String lastEntryName = null;
    for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
        ++count;
        JarEntry entry = entries.nextElement();
        assertNotEquals("Endless loop.", lastEntryName, entry.getName());
    }
    assertTrue("Empty jar file!", count > 0);
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private void loadClasses(File[] jarFiles, URLClassLoader cl) throws Exception {
    for (File input : jarFiles) {
        try {/*from   www  .  j  av  a2  s  . c om*/
            //load classes from plugin's jar files using the classloader above
            //loadClassesFromJar(input, cl);
            JarFile jarFile = new JarFile(input.getAbsolutePath());
            Enumeration e = jarFile.entries();
            while (e.hasMoreElements()) {
                JarEntry je = (JarEntry) e.nextElement();
                if (je.isDirectory() || !je.getName().endsWith(".class")) {
                    continue;
                }
                String className = je.getName().substring(0, je.getName().length() - 6);
                className = className.replace('/', '.');
                try {
                    cl.loadClass(className);
                } catch (Throwable ex) {
                    String error = "Error loadin class: " + className;
                    _logger.error(error);
                }
            }
        } catch (Throwable e) {
            String error = "Unexpected error loading class for file: " + input.getName() + " - "
                    + e.getMessage();
            _logger.error(error, e);
            throw new Exception(error, e);
        }
    }
}