Example usage for java.util.jar JarEntry getSize

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

Introduction

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

Prototype

public long getSize() 

Source Link

Document

Returns the uncompressed size of the entry data.

Usage

From source file:Main.java

public static void main(String[] args) throws IOException {
    JarFile jf = new JarFile("a.jar");
    Enumeration e = jf.entries();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        System.out.println(je.getName());
        long uncompressedSize = je.getSize();
        long compressedSize = je.getCompressedSize();
        long crc = je.getCrc();
        int method = je.getMethod();
        String comment = je.getComment();
        System.out.println(new Date(je.getTime()));
        System.out.println("from  " + uncompressedSize + " bytes to " + compressedSize);
        if (method == ZipEntry.STORED) {
            System.out.println("ZipEntry.STORED");
        } else if (method == ZipEntry.DEFLATED) {
            System.out.println(ZipEntry.DEFLATED);
        }//  ww  w.j a va 2  s  .c o  m
        System.out.println("Its CRC is " + crc);
        System.out.println(comment);
        System.out.println(je.isDirectory());

        Attributes a = je.getAttributes();
        if (a != null) {
            Object[] nameValuePairs = a.entrySet().toArray();
            for (int j = 0; j < nameValuePairs.length; j++) {
                System.out.println(nameValuePairs[j]);
            }
        }
        System.out.println();
    }
}

From source file:Main.java

public static void main(String[] args) throws IOException {

    JarFile jf = new JarFile(args[0]);
    Enumeration e = jf.entries();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        String name = je.getName();
        Date lastModified = new Date(je.getTime());
        long uncompressedSize = je.getSize();
        long compressedSize = je.getCompressedSize();

        System.out.println(lastModified);
        System.out.println(uncompressedSize);
        System.out.println(compressedSize);
    }/*from   w  ww . j a  v  a2  s  .  c o  m*/
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {

    JarFile jf = new JarFile(args[0]);
    Enumeration e = jf.entries();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        String name = je.getName();
        Date lastModified = new Date(je.getTime());
        long uncompressedSize = je.getSize();
        long compressedSize = je.getCompressedSize();

        int method = je.getMethod();

        if (method == ZipEntry.STORED) {
            System.out.println(name + " was stored at " + lastModified);
            System.out.println("with a size of  " + uncompressedSize + " bytes");
        } else if (method == ZipEntry.DEFLATED) {
            System.out.println(name + " was deflated at " + lastModified);
            System.out.println("from  " + uncompressedSize + " bytes to " + compressedSize
                    + " bytes, a savings of " + (100.0 - 100.0 * compressedSize / uncompressedSize) + "%");
        } else {/*from   ww w.j  a  va2 s  .com*/
            System.out.println(name + " was compressed using an unrecognized method at " + lastModified);
            System.out.println("from  " + uncompressedSize + " bytes to " + compressedSize
                    + " bytes, a savings of " + (100.0 - 100.0 * compressedSize / uncompressedSize) + "%");
        }
    }
}

From source file:Main.java

private static void process(Object obj) {
    JarEntry entry = (JarEntry) obj;
    String name = entry.getName();
    long size = entry.getSize();
    long compressedSize = entry.getCompressedSize();
    System.out.println(name + "\t" + size + "\t" + compressedSize);
}

From source file:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * /*from  w  ww.j  a  va2 s. c o m*/
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * The ClassPathResource will be scanned for all resources in the path specified by the resource.
 * For example  a path like:
 *    new ClassPathResource("resource/images/pager/", SheptBaseController.class);
 * takes all the resources in the path 'resource/images/pager' (but not in sub-path)
 * from the specified clazz 'SheptBaseController'
 * 
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 * @throws URISyntaxException 
 */
public static void copyResources(ClassPathResource cpr, String webAppDestPath)
        throws IOException, URISyntaxException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();

    URL url = cpr.getURL();
    // jarUrl is the URL of the containing lib, e.g. shept.org in this case
    URL jarUrl = ResourceUtils.extractJarFileURL(url);
    String urlFile = url.getFile();
    String resPath = "";
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    if (separatorIndex != -1) {
        // just copy the the location path inside the jar without leading separators !/
        resPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
    } else {
        return; // no resource within jar to copy
    }

    File f = new File(ResourceUtils.toURI(jarUrl));
    JarFile jf = new JarFile(f);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (path.startsWith(resPath) && entry.getSize() > 0) {
            String fileName = path.substring(path.lastIndexOf("/"));
            File dstFile = new File(dstPath, fileName); //  (StringUtils.applyRelativePath(dstPath, fileName));
            Resource fileRes = cpr.createRelative(fileName);
            if (!dstFile.exists() && fileRes.exists()) {
                FileOutputStream fos = new FileOutputStream(dstFile);
                FileCopyUtils.copy(fileRes.getInputStream(), fos);
                logger.info("Successfully copied file " + fileName + " from " + cpr.getPath() + " to "
                        + dstFile.getPath());
            }
        }
    }

    if (jf != null) {
        jf.close();
    }

}

From source file:dk.netarkivet.common.utils.batch.ByteJarLoader.java

/**
 * Constructor for the ByteLoader.//from  w w  w  . ja v  a2  s .c om
 * 
 * @param files
 *            An array of files, which are assumed to be jar-files, but
 *            they need not have the extension .jar
 */
public ByteJarLoader(File... files) {
    ArgumentNotValid.checkNotNull(files, "File ... files");
    ArgumentNotValid.checkTrue(files.length != 0, "Should not be empty array");
    for (File file : files) {
        try {
            JarFile jarFile = new JarFile(file);
            for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
                JarEntry entry = e.nextElement();
                String name = entry.getName();
                InputStream in = jarFile.getInputStream(entry);
                ByteArrayOutputStream out = new ByteArrayOutputStream((int) entry.getSize());
                StreamUtils.copyInputStreamToOutputStream(in, out);
                log.trace("Entering data for class '" + name + "'");
                binaryData.put(name, out.toByteArray());
            }
        } catch (IOException e) {
            throw new IOFailure("Failed to load jar file '" + file.getAbsolutePath() + "': " + e);
        }
    }
}

From source file:com.igormaznitsa.jcp.it.maven.ITPreprocessorMojo.java

@Test
@SuppressWarnings("unchecked")
public void testPreprocessorUsage() throws Exception {
    final File testDir = ResourceExtractor.simpleExtractResources(this.getClass(), "./dummy_maven_project");

    final Verifier verifier = new Verifier(testDir.getAbsolutePath());

    verifier.deleteArtifact("com.igormaznitsa", "DummyMavenProjectToTestJCP", "1.0-SNAPSHOT", "jar");
    verifier.executeGoal("package");
    assertFalse("Folder must be removed", new File("./dummy_maven_project/target").exists());

    final File resultJar = ResourceExtractor.simpleExtractResources(this.getClass(),
            "./dummy_maven_project/DummyMavenProjectToTestJCP-1.0-SNAPSHOT.jar");

    verifier.verifyErrorFreeLog();// w w  w . j  a v a2 s.  co m
    verifier.verifyTextInLog("PREPROCESSED_TESTING_COMPLETED");
    verifier.verifyTextInLog("Cleaning has been started");
    verifier.verifyTextInLog("Removing preprocessed source folder");
    verifier.verifyTextInLog("Removing preprocessed test source folder");
    verifier.verifyTextInLog("Scanning for deletable directories");
    verifier.verifyTextInLog("Deleting directory:");
    verifier.verifyTextInLog("Cleaning has been completed");
    verifier.verifyTextInLog(" mvn.project.property.some.datapass.base=***** ");
    verifier.verifyTextInLog(" mvn.project.property.some.private.key=***** ");

    final JarAnalyzer jarAnalyzer = new JarAnalyzer(resultJar);
    List<JarEntry> classEntries;
    try {
        classEntries = (List<JarEntry>) jarAnalyzer.getClassEntries();

        for (final JarEntry ce : classEntries) {
            assertFalse(ce.getName().contains("excludedfolder"));
        }

        assertEquals("Must have only class", 1, classEntries.size());
        final JarEntry classEntry = classEntries.get(0);
        assertNotNull(findClassEntry(jarAnalyzer, "com/igormaznitsa/dummyproject/testmain2.class"));

        DataInputStream inStream = null;
        final byte[] buffer = new byte[(int) classEntry.getSize()];
        Class<?> instanceClass = null;
        try {
            inStream = new DataInputStream(jarAnalyzer.getEntryInputStream(classEntry));
            inStream.readFully(buffer);

            instanceClass = new ClassLoader() {

                public Class<?> loadClass(final byte[] data) throws ClassNotFoundException {
                    return defineClass(null, data, 0, data.length);
                }
            }.loadClass(buffer);
        } finally {
            IOUtils.closeQuietly(inStream);
        }

        if (instanceClass != null) {
            final Object instance = instanceClass.newInstance();
            assertEquals("Must return the project name", "Dummy Maven Project To Test JCP",
                    instanceClass.getMethod("test").invoke(instance));
        } else {
            fail("Unexpected state");
        }
    } finally {
        jarAnalyzer.closeQuietly();
    }
}

From source file:io.vertx.lang.js.JSVerticleFactory.java

private boolean hasNodeModules(URL url) {
    JarEntry modules = null;
    try {/*from  w w  w  .  j  a  v  a2  s .  co  m*/
        modules = ClasspathFileResolver.getJarEntry(url, "node_modules");
    } catch (IOException ex) {
        log.warn(ex.toString());
        return false;
    }
    return modules != null && (modules.isDirectory() || modules.getSize() == 0);
}

From source file:com.googlecode.onevre.utils.ServerClassLoader.java

private Class<?> defineClassFromJar(String name, URL url, File jar, String pathName) throws IOException {
    JarFile jarFile = new JarFile(jar);
    JarEntry entry = jarFile.getJarEntry(pathName);
    InputStream input = jarFile.getInputStream(entry);
    byte[] classData = new byte[(int) entry.getSize()];
    int totalBytes = 0;
    while (totalBytes < classData.length) {
        int bytesRead = input.read(classData, totalBytes, classData.length - totalBytes);
        if (bytesRead == -1) {
            throw new IOException("Jar Entry too short!");
        }/*from w w w. j av  a2 s  .c o m*/
        totalBytes += bytesRead;
    }
    Class<?> loadedClass = defineClass(name, classData, 0, classData.length,
            new CodeSource(url, entry.getCertificates()));
    input.close();
    jarFile.close();
    return loadedClass;
}

From source file:com.rbmhtechnology.apidocserver.controller.ApiDocController.java

private void serveFileFromJarFile(HttpServletResponse response, File jar, String subPath) throws IOException {
    JarFile jarFile = null;//  w w  w .  j a v a2s. c om
    try {
        jarFile = new JarFile(jar);
        JarEntry entry = jarFile.getJarEntry(subPath);

        if (entry == null) {
            response.sendError(404);
            return;
        }

        // fallback for requesting a directory without a trailing /
        // this leads to a jarentry which is not null, and not a directory and of size 0
        // this shouldn't be
        if (!entry.isDirectory() && entry.getSize() == 0) {
            if (!subPath.endsWith("/")) {
                JarEntry entryWithSlash = jarFile.getJarEntry(subPath + "/");
                if (entryWithSlash != null && entryWithSlash.isDirectory()) {
                    entry = entryWithSlash;
                }
            }
        }

        if (entry.isDirectory()) {
            for (String indexFile : DEFAULT_INDEX_FILES) {
                entry = jarFile.getJarEntry((subPath.endsWith("/") ? subPath : subPath + "/") + indexFile);
                if (entry != null) {
                    break;
                }
            }
        }

        if (entry == null) {
            response.sendError(404);
            return;
        }

        response.setContentLength((int) entry.getSize());
        String mimetype = getMimeType(entry.getName());
        response.setContentType(mimetype);
        InputStream input = jarFile.getInputStream(entry);
        try {
            ByteStreams.copy(input, response.getOutputStream());
        } finally {
            input.close();
        }
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}