Example usage for java.util.zip ZipEntry getSize

List of usage examples for java.util.zip ZipEntry getSize

Introduction

In this page you can find the example usage for java.util.zip ZipEntry getSize.

Prototype

public long getSize() 

Source Link

Document

Returns the uncompressed size of the entry data.

Usage

From source file:com.adaptris.core.lms.ZipFileBackedMessageTest.java

/**
 * This tests creates a compressed file/*from  w w w  .j a  v a  2s .  c o m*/
 */
@Test
public void testCreateCompressedFile() throws Exception {
    ZipFileBackedMessageFactory factory = getMessageFactory();
    factory.setCompressionMode(CompressionMode.Compress);
    FileBackedMessage orig = (FileBackedMessage) factory.newMessage();

    File srcFile = new File(BaseCase.PROPERTIES.getProperty("msg.initFromFile"));
    try (FileInputStream in = new FileInputStream(srcFile); OutputStream out = orig.getOutputStream()) {
        IOUtils.copy(in, out);
    }

    // File should now be compressed. Check if it's a zip file and if the compressed size equals the input file size
    try (ZipFile zipFile = new ZipFile(orig.currentSource())) {
        long size = 0;
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            size += entry.getSize();
        }

        assertEquals("message size", orig.getSize(), size);
        assertEquals("payload size", srcFile.length(), size);
    }

    // Check if the InputStream from the message also yields compressed data
    try (ZipInputStream zin = new ZipInputStream(orig.getInputStream());
            ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        zin.getNextEntry();
        IOUtils.copy(zin, out);
        assertEquals("payload size", srcFile.length(), out.size());
    }
}

From source file:com.l2jfree.gameserver.util.JarClassLoader.java

private byte[] loadClassData(String name) throws IOException {
    byte[] classData = null;
    for (String jarFile : _jars) {
        ZipFile zipFile = null;/*from ww w.  j  a  v  a  2 s  .  c o m*/
        DataInputStream zipStream = null;

        try {
            File file = new File(jarFile);
            zipFile = new ZipFile(file);
            String fileName = name.replace('.', '/') + ".class";
            ZipEntry entry = zipFile.getEntry(fileName);
            if (entry == null)
                continue;
            classData = new byte[(int) entry.getSize()];
            zipStream = new DataInputStream(zipFile.getInputStream(entry));
            zipStream.readFully(classData, 0, (int) entry.getSize());
            break;
        } catch (IOException e) {
            _log.warn(jarFile + ":", e);
            continue;
        } finally {
            try {
                if (zipFile != null)
                    zipFile.close();
            } catch (Exception e) {
                _log.warn("", e);
            }
            try {
                if (zipStream != null)
                    zipStream.close();
            } catch (Exception e) {
                _log.warn("", e);
            }
        }
    }
    if (classData == null)
        throw new IOException("class not found in " + _jars);
    return classData;
}

From source file:org.dbgl.util.FileUtils.java

public static long extractZipEntrySizeInBytes(final File archive, final String zipEntryToBeExtracted)
        throws IOException {
    ZipFile zf = new ZipFile(archive);
    ZipEntry entry = zf.getEntry(zipEntryToBeExtracted);
    zf.close();//from w w  w  .ja  va  2 s.  c  o m
    if (entry != null)
        return entry.getSize();
    return 0;
}

From source file:org.apache.nutch.parse.zip.ZipTextExtractor.java

public String extractText(InputStream input, String url, List outLinksList) throws IOException {
    String resultText = "";
    byte temp;//w  ww .j a v a 2s.c om

    ZipInputStream zin = new ZipInputStream(input);

    ZipEntry entry;

    while ((entry = zin.getNextEntry()) != null) {

        if (!entry.isDirectory()) {
            int size = (int) entry.getSize();
            byte[] b = new byte[size];
            for (int x = 0; x < size; x++) {
                int err = zin.read();
                if (err != -1) {
                    b[x] = (byte) err;
                }
            }
            String newurl = url + "/";
            String fname = entry.getName();
            newurl += fname;
            URL aURL = new URL(newurl);
            String base = aURL.toString();
            int i = fname.lastIndexOf('.');
            if (i != -1) {
                // Trying to resolve the Mime-Type
                String contentType = MIME.getMimeType(fname).getName();
                try {
                    Metadata metadata = new Metadata();
                    metadata.set(Response.CONTENT_LENGTH, Long.toString(entry.getSize()));
                    metadata.set(Response.CONTENT_TYPE, contentType);
                    Content content = new Content(newurl, base, b, contentType, metadata, this.conf);
                    Parse parse = new ParseUtil(this.conf).parse(content).get(content.getUrl());
                    ParseData theParseData = parse.getData();
                    Outlink[] theOutlinks = theParseData.getOutlinks();

                    for (int count = 0; count < theOutlinks.length; count++) {
                        outLinksList.add(
                                new Outlink(theOutlinks[count].getToUrl(), theOutlinks[count].getAnchor()));
                    }

                    resultText += entry.getName() + " " + parse.getText() + " ";
                } catch (ParseException e) {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("fetch okay, but can't parse " + fname + ", reason: " + e.getMessage());
                    }
                }
            }
        }
    }

    return resultText;
}

From source file:org.digidoc4j.impl.bdoc.asic.AsicContainerParser.java

private DSSDocument extractStreamDocument(ZipEntry entry) {
    logger.debug("Zip entry size is " + entry.getSize() + " bytes");
    InputStream zipFileInputStream = getZipEntryInputStream(entry);
    String fileName = entry.getName();
    String mimeType = getDataFileMimeType(fileName);
    MimeType mimeTypeCode = MimeType.fromMimeTypeString(mimeType);
    DSSDocument document;/*from   w w w .  ja  v  a 2 s  . c o  m*/
    if (storeDataFilesOnlyInMemory || entry.getSize() <= maxDataFileCachedInBytes) {
        document = new InMemoryDocument(zipFileInputStream, fileName, mimeTypeCode);
    } else {
        document = new StreamDocument(zipFileInputStream, fileName, mimeTypeCode);
    }
    return document;
}

From source file:org.dbgl.util.FileUtils.java

public static long extractZipSizeInBytes(final File archive, final File dirToBeExtracted) throws IOException {
    long bytes = 0;
    ZipFile zf = new ZipFile(archive);
    for (Enumeration<? extends ZipEntry> entries = zf.entries(); entries.hasMoreElements();) {
        ZipEntry entry = entries.nextElement();
        if (areRelated(dirToBeExtracted, new File(entry.getName())))
            bytes += entry.getSize();
    }//from  ww w  .jav a 2  s. c om
    zf.close();
    return bytes;
}

From source file:com.jivesoftware.os.routing.bird.endpoints.base.LocateStringResource.java

String getStringResource() {
    Map<String, Long> htSizes = new HashMap<>();
    try {/* ww  w  .j  a v  a2  s .  co m*/
        try (final ZipFile zf = new ZipFile(jarFileName)) {
            Enumeration<? extends ZipEntry> e = zf.entries();
            while (e.hasMoreElements()) {
                ZipEntry ze = e.nextElement();
                if (!ze.getName().equals(resourceName)) {
                    continue;
                }
                htSizes.put(ze.getName(), ze.getSize());
            }
        }
        // extract resources and put them into the hashtable.
        FileInputStream fis = new FileInputStream(jarFileName);
        BufferedInputStream bis = new BufferedInputStream(fis);
        try (final ZipInputStream zis = new ZipInputStream(bis)) {
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                if (!ze.getName().equals(resourceName)) {
                    continue;
                }
                if (ze.isDirectory()) {
                    continue;
                }
                int size = (int) ze.getSize();
                // -1 means unknown size.
                if (size == -1) {
                    size = htSizes.get(ze.getName()).intValue();
                }
                byte[] b = new byte[size];
                int rb = 0;
                int chunk = 0;
                while ((size - rb) > 0) {
                    chunk = zis.read(b, rb, size - rb);
                    if (chunk == -1) {
                        break;
                    }
                    rb += chunk;
                }
                InputStream inputStream = new ByteArrayInputStream(b);
                StringWriter writer = new StringWriter();
                IOUtils.copy(inputStream, writer, "UTF-8");
                return writer.toString();
            }
        }
    } catch (Exception e) {
        LOG.warn("Failed to locate " + resourceName, e);
    }
    return null;
}

From source file:com.replaymod.replaystudio.launcher.ReverseLauncher.java

public void launch(CommandLine cmd) throws Exception {
    ZipFile file = new ZipFile(cmd.getArgs()[0]);
    ZipEntry entry = file.getEntry("recording.tmcpr");
    if (entry == null) {
        throw new IOException("Input file is not a valid replay file.");
    }/*from   w  w  w  . ja va 2 s. c  om*/
    long size = entry.getSize();
    if (size == -1) {
        throw new IOException("Uncompressed size of recording.tmcpr not set.");
    }

    InputStream from = file.getInputStream(entry);
    RandomAccessFile to = new RandomAccessFile(cmd.getArgs()[1], "rw");

    to.setLength(size);
    int nRead;
    long pos = size;
    byte[] buffer = new byte[8192];

    long lastUpdate = -1;
    while (true) {
        long pct = 100 - pos * 100 / size;
        if (lastUpdate != pct) {
            System.out.print("Reversing " + size + " bytes... " + pct + "%\r");
            lastUpdate = pct;
        }
        int next = readInt(from);
        int length = readInt(from);
        if (next == -1 || length == -1) {
            break; // reached end of stream
        }
        // Increase buffer if necessary
        if (length + 8 > buffer.length) {
            buffer = new byte[length + 8];
        }
        buffer[0] = (byte) ((next >>> 24) & 0xFF);
        buffer[1] = (byte) ((next >>> 16) & 0xFF);
        buffer[2] = (byte) ((next >>> 8) & 0xFF);
        buffer[3] = (byte) (next & 0xFF);
        buffer[4] = (byte) ((length >>> 24) & 0xFF);
        buffer[5] = (byte) ((length >>> 16) & 0xFF);
        buffer[6] = (byte) ((length >>> 8) & 0xFF);
        buffer[7] = (byte) (length & 0xFF);

        nRead = 0;
        while (nRead < length) {
            nRead += from.read(buffer, 8 + nRead, length - nRead);
        }

        pos -= length + 8;
        to.seek(pos);
        to.write(buffer, 0, length + 8);
    }

    from.close();
    to.close();

    System.out.println("\nDone!");
}

From source file:uk.co.a1dutch.zipper.ZipperTest.java

private void assertZipContent(String file, String zipPath, String fileContent) throws IOException {
    try (ZipFile zip = new ZipFile(outputZip(file))) {
        ZipEntry entry = zip.getEntry(zipPath);
        assertThat(entry, is(notNullValue()));

        try (InputStream zeis = zip.getInputStream(entry)) {
            byte[] buffer = new byte[(int) entry.getSize()];
            IOUtils.read(zeis, buffer);//from  ww w . jav  a2s .  c o  m

            assertThat(new String(buffer), is(equalTo(fileContent)));
        }
    }
}

From source file:org.orbeon.oxf.processor.zip.UnzipProcessor.java

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(UnzipProcessor.this, name) {

        public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) {
            try {
                // Read input in a temporary file
                final File temporaryZipFile;
                {/*ww  w.  j av  a  2 s. co  m*/
                    final FileItem fileItem = NetUtils.prepareFileItem(NetUtils.REQUEST_SCOPE, logger);
                    final OutputStream fileOutputStream = fileItem.getOutputStream();
                    readInputAsSAX(context, getInputByName(INPUT_DATA),
                            new BinaryTextXMLReceiver(fileOutputStream));
                    temporaryZipFile = ((DiskFileItem) fileItem).getStoreLocation();
                }

                xmlReceiver.startDocument();
                // <files>
                xmlReceiver.startElement("", "files", "files", SAXUtils.EMPTY_ATTRIBUTES);
                ZipFile zipFile = new ZipFile(temporaryZipFile);
                for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
                    // Go through each entry in the zip file
                    ZipEntry zipEntry = (ZipEntry) entries.nextElement();
                    // Get file name
                    String fileName = zipEntry.getName();
                    long fileSize = zipEntry.getSize();
                    String fileTime = DateUtils.DateTime().print(zipEntry.getTime());

                    InputStream entryInputStream = zipFile.getInputStream(zipEntry);
                    String uri = NetUtils.inputStreamToAnyURI(entryInputStream, NetUtils.REQUEST_SCOPE, logger);
                    // <file name="filename.ext">uri</file>
                    AttributesImpl fileAttributes = new AttributesImpl();
                    fileAttributes.addAttribute("", "name", "name", "CDATA", fileName);
                    fileAttributes.addAttribute("", "size", "size", "CDATA", Long.toString(fileSize));
                    fileAttributes.addAttribute("", "dateTime", "dateTime", "CDATA", fileTime);
                    xmlReceiver.startElement("", "file", "file", fileAttributes);
                    xmlReceiver.characters(uri.toCharArray(), 0, uri.length());
                    // </file>
                    xmlReceiver.endElement("", "file", "file");
                }
                // </files>
                xmlReceiver.endElement("", "files", "files");
                xmlReceiver.endDocument();

            } catch (IOException e) {
                throw new OXFException(e);
            } catch (SAXException e) {
                throw new OXFException(e);
            }
        }

        // We don't do any caching here since the file we produce are temporary. So we don't want a processor
        // downstream to keep a reference to a document that contains temporary URI that have since been deleted.

    };
    addOutput(name, output);
    return output;
}