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:InstallJars.java

/** Copy a zip entry. */
protected void copyEntry(String target, ZipInputStream zis, ZipEntry ze) throws IOException {
    String name = ze.getName();//from w  w w  .  j a va  2  s  .c om
    boolean isDir = false;
    if (name.endsWith("/")) {
        name = name.substring(0, name.length() - 1);
        isDir = true;
    }
    String path = target + File.separator + name;
    path = path.replace('\\', '/');
    String mod = ze.getSize() > 0 ? ("[" + ze.getCompressedSize() + ":" + ze.getSize() + "]") : "";
    print("Expanding " + ze + mod + " to " + path);
    prepDirs(path, isDir);
    if (!isDir) {
        BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(path),
                BLOCK_SIZE * BLOCK_COUNT);
        try {
            byte[] buf = new byte[bufferSize];
            for (int size = zis.read(buf, 0, buf.length), count = 0; size >= 0; size = zis.read(buf, 0,
                    buf.length), count++) {
                // if (count % 4 == 0) print(".");
                os.write(buf, 0, size);
            }
        } finally {
            try {
                os.flush();
                os.close();
            } catch (IOException ioe) {
            }
        }
    }
    println();
}

From source file:slash.navigation.download.actions.Extractor.java

private void doExtract(File tempFile, File destination, boolean flatten) throws IOException {
    try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(tempFile))) {
        ZipEntry entry = zipInputStream.getNextEntry();
        while (entry != null) {
            if (entry.isDirectory()) {
                if (!flatten) {
                    File directory = new File(destination, entry.getName());
                    handleDirectory(directory, entry);
                }/*from   ww  w  . j  ava  2  s . co  m*/

            } else {
                File extracted;
                if (flatten)
                    extracted = new File(destination, lastPathFragment(entry.getName(), MAX_VALUE));
                else {
                    extracted = new File(destination, entry.getName());
                }
                File directory = extracted.getParentFile();
                handleDirectory(directory, entry);

                log.info(format("Extracting from %s to %s", tempFile, extracted));
                FileOutputStream output = new FileOutputStream(extracted);
                new Copier(listener).copy(zipInputStream, output, 0, entry.getSize());
                // do not close zip input stream
                closeQuietly(output);
                setLastModified(extracted, fromMillis(entry.getTime()));

                zipInputStream.closeEntry();
            }

            entry = zipInputStream.getNextEntry();
        }
    }
}

From source file:org.eclipse.smila.connectivity.framework.compound.zip.ZipCompoundCrawler.java

/**
 * Read attribute value./*from  w w w .  j a v  a  2s  . c om*/
 * 
 * @param zipEntry
 *          the ZipEntry
 * @param attribute
 *          the attribute
 * @param forceByteToString
 *          the force byte to string
 * 
 * @return the object
 * 
 * @throws CrawlerException
 *           the crawler exception
 */
private Serializable readAttribute(final ZipEntry zipEntry, final CompoundHandling.CompoundAttribute attribute,
        final boolean forceByteToString) throws CrawlerException {
    switch (attribute.getElementAttribute()) {
    case NAME:
        return FilenameUtils.getName(zipEntry.getName());
    case FILE_EXTENSION:
        return FilenameUtils.getExtension(zipEntry.getName());
    case PATH:
        return zipEntry.getName();
    case LAST_MODIFIED_DATE:
        return new Date(zipEntry.getTime());
    case SIZE:
        return new Long(zipEntry.getSize());
    case CONTENT:
        try {
            final byte[] bytes = readZipEntryContent(zipEntry);
            if (forceByteToString) {
                final String encoding = EncodingHelper.getEncoding(bytes);
                if (encoding != null) {
                    return IOUtils.toString(new ByteArrayInputStream(bytes), encoding);
                } else {
                    return IOUtils.toString(new ByteArrayInputStream(bytes));
                }
            } else {
                return bytes;
            }
        } catch (final IOException e) {
            throw new CrawlerException(e);
        }
    default:
        throw new RuntimeException(
                "Unknown compound element attributes type " + attribute.getElementAttribute());
    }
}

From source file:com.kunze.androidlocaltodo.TaskListActivity.java

private void LoadAstrid() {
    // Look for a zip file in the proper location
    String loc = Environment.getExternalStorageDirectory() + "/AstridImport/";
    AlertDialog.Builder errorBuilder = new AlertDialog.Builder(this);
    errorBuilder.setTitle("Error reading Astrid Import!");
    ZipInputStream zipStream = null;
    InputStream stream = null;/* w  ww .j  av  a 2  s. co  m*/
    try {
        // Try to safely open the file
        String errText = "Cannot find Astrid file in " + loc;
        File astridDir = new File(loc);
        if (!astridDir.isDirectory()) {
            throw new Exception(errText);
        }

        File[] files = astridDir.listFiles();
        if (files.length != 1) {
            throw new Exception(errText);
        }

        File astridFile = files[0];
        if (!astridFile.isFile()) {
            throw new Exception(errText);
        }

        // Try to unzip the file and unpack the tasks
        errText = "Could not unzip file " + astridFile.getAbsolutePath();
        stream = new FileInputStream(astridFile);
        zipStream = new ZipInputStream(stream);

        ZipEntry tasksEntry = null;
        while ((tasksEntry = zipStream.getNextEntry()) != null) {
            if (tasksEntry.getName().equals("tasks.csv")) {
                break;
            }
        }
        if (tasksEntry == null) {
            throw new Exception(errText);
        }

        int size = (int) tasksEntry.getSize();
        byte tasksContent[] = new byte[size];
        int offset = 0;
        while (size != 0) {
            int read = zipStream.read(tasksContent, offset, size);
            if (read == 0) {
                throw new Exception(errText);
            }
            offset += read;
            size -= read;
        }

        String tasksString = new String(tasksContent, "UTF-8");

        // Parse the tasks in the task list
        errText = "Could not parse task list";
        List<String> taskLines = new LinkedList<String>(Arrays.asList(tasksString.split("\n")));
        // Remove the header row
        taskLines.remove(0);
        // Some tasks have newlines in quotes, so we have to adjust for that.
        ListIterator<String> it = taskLines.listIterator();
        while (it.hasNext()) {
            String task = it.next();
            while (CountQuotes(task) % 2 == 1) {
                it.remove();
                task += it.next();
            }
            it.set(task);
        }
        for (String taskLine : taskLines) {
            List<String> taskFields = new LinkedList<String>(Arrays.asList(taskLine.split(",", -1)));
            // Some tasks have commas in quotes, so we have to adjust for that.
            it = taskFields.listIterator();
            while (it.hasNext()) {
                String field = it.next();
                while (CountQuotes(field) % 2 == 1) {
                    it.remove();
                    field += it.next();
                }
                it.set(field);
            }

            Task taskElement = new Task();
            taskElement.mName = taskFields.get(0);
            taskElement.mDescription = taskFields.get(8);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

            taskElement.mDueDate = Calendar.getInstance();
            taskElement.mDueDate.setTime(dateFormat.parse(taskFields.get(4)));
            String completedString = taskFields.get(9);
            taskElement.mCompletedDate = Calendar.getInstance();
            if (completedString.equals("")) {
                taskElement.mCompletedDate.setTimeInMillis(0);
            } else {
                taskElement.mCompletedDate.setTime(dateFormat.parse(completedString));
            }
            taskElement.mRepeatUnit = Task.RepeatUnit.NONE;
            taskElement.mRepeatTime = 0;
            taskElement.mRepeatFromComplete = false;
            String repeatString = taskFields.get(6);
            String repeatFields[] = repeatString.split(":");
            if (repeatFields[0].equals("RRULE")) {
                repeatFields = repeatFields[1].split(";");
                String freqFields[] = repeatFields[0].split("=");
                if (freqFields[0].equals("FREQ")) {
                    if (freqFields[1].equals("YEARLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.YEARS;
                    } else if (freqFields[1].equals("MONTHLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.MONTHS;
                    } else if (freqFields[1].equals("WEEKLY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.WEEKS;
                    } else if (freqFields[1].equals("DAILY")) {
                        taskElement.mRepeatUnit = Task.RepeatUnit.DAYS;
                    }
                }
                freqFields = repeatFields[1].split("=");
                if (freqFields[0].equals("INTERVAL")) {
                    taskElement.mRepeatTime = Integer.valueOf(freqFields[1]);
                }
                if (repeatFields.length > 2 && repeatFields[2] != null) {
                    freqFields = repeatFields[2].split("=");
                    if (freqFields[0].equals("FROM") && freqFields[1].equals("COMPLETION")) {
                        taskElement.mRepeatFromComplete = true;
                    }
                }
            }
            mDB.AddTask(taskElement);
        }

        RefreshView();
    } catch (Exception e) {
        AlertDialog dlg = errorBuilder.setMessage(e.getMessage()).create();
        dlg.show();
    } finally {

        try {
            if (zipStream != null) {
                zipStream.close();
            }
            if (stream != null) {
                stream.close();
            }
        } catch (Exception e) {
            AlertDialog dlg = errorBuilder.setMessage(e.getMessage()).create();
            dlg.show();
        }
    }
}

From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java

@Test
public void mimeTypePosition() throws Exception {
    UCFPackage container = new UCFPackage();
    container.setPackageMediaType(UCFPackage.MIME_EPUB);
    assertEquals(UCFPackage.MIME_EPUB, container.getPackageMediaType());
    container.save(tmpFile);/*from ww w . ja  va2 s  .co  m*/
    assertTrue(tmpFile.exists());
    ZipFile zipFile = new ZipFile(tmpFile);
    // Must be first entry
    ZipEntry mimeEntry = zipFile.entries().nextElement();
    assertEquals("First zip entry is not 'mimetype'", "mimetype", mimeEntry.getName());
    assertEquals("mimetype should be uncompressed, but compressed size mismatch", mimeEntry.getCompressedSize(),
            mimeEntry.getSize());
    assertEquals("mimetype should have STORED method", ZipEntry.STORED, mimeEntry.getMethod());
    assertEquals("Wrong mimetype", UCFPackage.MIME_EPUB,
            IOUtils.toString(zipFile.getInputStream(mimeEntry), "ASCII"));

    // Check position 30++ according to
    // http://livedocs.adobe.com/navigator/9/Navigator_SDK9_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Navigator_SDK9_HTMLHelp&file=Appx_Packaging.6.1.html#1522568
    byte[] expected = ("mimetype" + UCFPackage.MIME_EPUB + "PK").getBytes("ASCII");
    FileInputStream in = new FileInputStream(tmpFile);
    byte[] actual = new byte[expected.length];
    try {
        assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET));
        assertEquals(expected.length, in.read(actual));
    } finally {
        in.close();
    }
    assertArrayEquals(expected, actual);
}

From source file:rapture.plugin.install.PluginSandbox.java

public void makeItemFromZipEntry(ZipFile zip, ZipEntry entry) throws IOException, NoSuchAlgorithmException {
    if ("plugin.txt".equals(entry.getName()))
        return;/*ww w .  j  a  va 2  s  . c om*/
    MessageDigest md = MessageDigest.getInstance("MD5");
    try {
        Pair<RaptureURI, String> pair = PluginSandboxItem.calculateURI(entry);
        RaptureURI uri = pair.getLeft();
        String variant = pair.getRight();
        if (uri == null) {
            return;
        }
        byte[] content = PluginContentReader.readFromZip(zip, entry, md);

        if (log.isDebugEnabled()) {
            log.debug(String.format("name=%s, size=%s", entry.getName(), entry.getSize()));
            log.debug(String.format("content size=%s", content.length));
            log.debug("********* SAME??? " + (content.length == entry.getSize()));
        }
        String hash = Hex.encodeHexString(md.digest());

        PluginSandboxItem result = new PluginSandboxItem(uri, variant, hash, content);
        if (rootDir != null) {
            result.updateFilePath(rootDir);
        }
        updateIndex(uri, variant, result);
    } catch (Exception ex) {
        // do nothing -- ignore extraneous files/entries
    }
}

From source file:dev.dworks.apps.anexplorer.provider.ExternalStorageProvider.java

private void includeZIPFile(MatrixCursor result, String docId, ZipEntry zipEntry) throws FileNotFoundException {

    int flags = 0;

    final String displayName = zipEntry.getName();
    final String mimeType = ""; //getTypeForFile(zipEntry);

    final RowBuilder row = result.newRow();
    row.add(Document.COLUMN_DOCUMENT_ID, docId);
    row.add(Document.COLUMN_DISPLAY_NAME, displayName);
    row.add(Document.COLUMN_SIZE, zipEntry.getSize());
    row.add(Document.COLUMN_MIME_TYPE, mimeType);
    row.add(Document.COLUMN_PATH, "");//zipEntry.getAbsolutePath());
    row.add(Document.COLUMN_FLAGS, flags);
    if (zipEntry.isDirectory()) {
        row.add(Document.COLUMN_SUMMARY, "? files");
    }//from   w  ww . ja  va  2s. co  m

    // Only publish dates reasonably after epoch
    long lastModified = zipEntry.getTime();
    if (lastModified > 31536000000L) {
        row.add(Document.COLUMN_LAST_MODIFIED, lastModified);
    }
}

From source file:org.broad.igv.feature.genome.GenomeManager.java

/**
 * Rewrite the {@link Globals#GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY} property to equal
 * the specified {@code newSequencePath}. Works by creating a temp file and renaming
 *
 * @param targetFile      A .genome file, in zip format
 * @param newSequencePath/*from w  w  w  .j a  va2s  . c  o  m*/
 * @return boolean indicating success or failure.
 * @throws IOException
 */
static boolean rewriteSequenceLocation(File targetFile, String newSequencePath) throws IOException {

    ZipFile targetZipFile = new ZipFile(targetFile);
    boolean success = false;

    File tmpZipFile = File.createTempFile("tmpGenome", ".zip");
    ZipEntry propEntry = targetZipFile.getEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME);

    InputStream propertyInputStream = null;
    ZipOutputStream zipOutputStream = null;
    Properties inputProperties = new Properties();

    try {
        propertyInputStream = targetZipFile.getInputStream(propEntry);
        BufferedReader reader = new BufferedReader(new InputStreamReader(propertyInputStream));

        //Copy over property.txt, only replacing a few properties
        inputProperties.load(reader);
        inputProperties.put(Globals.GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY, newSequencePath);
        inputProperties.put(Globals.GENOME_ARCHIVE_CUSTOM_SEQUENCE_LOCATION_KEY, Boolean.TRUE.toString());

        ByteArrayOutputStream propertyBytes = new ByteArrayOutputStream();
        PrintWriter propertyFileWriter = new PrintWriter(new OutputStreamWriter(propertyBytes));

        inputProperties.store(propertyFileWriter, null);

        propertyFileWriter.flush();
        byte[] newPropertyBytes = propertyBytes.toByteArray();

        Enumeration<? extends ZipEntry> entries = targetZipFile.entries();
        zipOutputStream = new ZipOutputStream(new FileOutputStream(tmpZipFile));
        while (entries.hasMoreElements()) {
            ZipEntry curEntry = entries.nextElement();
            ZipEntry writeEntry = null;

            if (curEntry.getName().equals(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME)) {
                writeEntry = new ZipEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME);
                writeEntry.setSize(newPropertyBytes.length);
                zipOutputStream.putNextEntry(writeEntry);
                zipOutputStream.write(newPropertyBytes);
                continue;
            } else {
                //Because the compressed size can vary,
                //we generate a new ZipEntry and copy some attributes
                writeEntry = new ZipEntry(curEntry.getName());
                writeEntry.setSize(curEntry.getSize());
                writeEntry.setComment(curEntry.getComment());
                writeEntry.setTime(curEntry.getTime());
            }

            zipOutputStream.putNextEntry(writeEntry);
            InputStream tmpIS = null;
            try {
                tmpIS = targetZipFile.getInputStream(writeEntry);
                int bytes = IOUtils.copy(tmpIS, zipOutputStream);
                log.debug(bytes + " bytes written to " + targetFile);
            } finally {
                if (tmpIS != null)
                    tmpIS.close();
            }

        }
    } catch (Exception e) {
        tmpZipFile.delete();
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (propertyInputStream != null)
            propertyInputStream.close();
        if (zipOutputStream != null) {
            zipOutputStream.flush();
            zipOutputStream.finish();
            zipOutputStream.close();
        }
        zipOutputStream = null;
        System.gc();
        success = true;
    }

    //This is a hack. I don't know why it's necessary,
    //but for some reason the output zip file seems to be corrupt
    //at least when called from GenomeManager.refreshArchive
    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {
        //
    }

    //Rename tmp file
    if (success) {
        targetFile.delete();
        FileUtils.copyFile(tmpZipFile, targetFile);
        success = targetFile.exists();
        tmpZipFile.delete();
    }
    return success;
}

From source file:org.rhq.core.util.updater.Deployer.java

/**
 * Returns an estimated amount of disk space the deployment will need if it gets installed.
 * @return information on the estimated disk usage
 * @throws Exception if cannot determine the estimated disk usage
 *///from w ww .j a v  a 2 s .c o m
public DeploymentDiskUsage estimateDiskUsage() throws Exception {
    final DeploymentDiskUsage diskUsage = new DeploymentDiskUsage();

    File partition = this.deploymentData.getDestinationDir();
    long usableSpace = partition.getUsableSpace();
    while (usableSpace == 0L && partition != null) {
        partition = partition.getParentFile();
        if (partition != null) {
            usableSpace = partition.getUsableSpace();
        }
    }

    diskUsage.setMaxDiskUsable(usableSpace);

    Set<File> zipFiles = this.deploymentData.getZipFiles();
    for (File zipFile : zipFiles) {
        ZipUtil.walkZipFile(zipFile, new ZipEntryVisitor() {
            public boolean visit(ZipEntry entry, ZipInputStream stream) throws Exception {
                if (!entry.isDirectory()) {
                    final long size = entry.getSize();
                    diskUsage.increaseDiskUsage(size > 0 ? size : 0);
                    diskUsage.incrementFileCount();
                }
                return true;
            }
        });
    }

    Map<File, File> rawFiles = this.deploymentData.getRawFiles();
    for (File rawFile : rawFiles.keySet()) {
        diskUsage.increaseDiskUsage(rawFile.length());
        diskUsage.incrementFileCount();
    }

    return diskUsage;
}

From source file:org.pentaho.platform.plugin.services.importexport.CommandLineProcessor.java

/**
 * --import --url=http://localhost:8080/pentaho --username=admin --password=password --file-path=metadata.xmi
 * --resource-type=DATASOURCE --datasource-type=METADATA --overwrite=true --metadata-domain-id=steel-wheels
 * //w ww. j  a v  a 2s.com
 * @param contextURL
 * @param metadataDatasourceFile
 * @param overwrite
 * @throws ParseException
 * @throws IOException
 */
private void performMetadataDatasourceImport(String contextURL, File metadataDatasourceFile, String overwrite)
        throws ParseException, IOException {
    File metadataFileInZip = null;
    InputStream metadataFileInZipInputStream = null;

    String metadataImportURL = contextURL + METADATA_DATASOURCE_IMPORT;

    String domainId = getOptionValue(
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_METADATA_DOMAIN_ID_KEY"),
            Messages.getInstance().getString("CommandLineProcessor.INFO_OPTION_METADATA_DOMAIN_ID_NAME"), true,
            false);

    WebResource resource = client.resource(metadataImportURL);

    FormDataMultiPart part = new FormDataMultiPart();

    final String name = RepositoryFilenameUtils.separatorsToRepository(metadataDatasourceFile.getName());
    final String ext = RepositoryFilenameUtils.getExtension(name);

    try {
        if (ext.equals(ZIP_EXT)) {
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(metadataDatasourceFile));
            ZipEntry entry = zipInputStream.getNextEntry();
            while (entry != null) {
                final String entryName = RepositoryFilenameUtils.separatorsToRepository(entry.getName());
                final String extension = RepositoryFilenameUtils.getExtension(entryName);
                File tempFile = null;
                boolean isDir = entry.getSize() == 0;
                if (!isDir) {
                    tempFile = File.createTempFile("zip", null);
                    tempFile.deleteOnExit();
                    FileOutputStream fos = new FileOutputStream(tempFile);
                    IOUtils.copy(zipInputStream, fos);
                    fos.close();
                }
                if (extension.equals(METADATA_DATASOURCE_EXT)) {
                    if (metadataFileInZip == null) {
                        metadataFileInZip = new File(entryName);
                        metadataFileInZipInputStream = new FileInputStream(metadataFileInZip);
                    }
                }

                zipInputStream.closeEntry();
                entry = zipInputStream.getNextEntry();
            }
            zipInputStream.close();

            part.field("overwrite", "true".equals(overwrite) ? "true" : "false",
                    MediaType.MULTIPART_FORM_DATA_TYPE);
            part.field("domainId", domainId, MediaType.MULTIPART_FORM_DATA_TYPE).field("metadataFile",
                    metadataFileInZipInputStream, MediaType.MULTIPART_FORM_DATA_TYPE);

            // If the import service needs the file name do the following.
            part.getField("metadataFile").setContentDisposition(FormDataContentDisposition.name("metadataFile")
                    .fileName(metadataFileInZip.getName()).build());

            // Response response
            ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class,
                    part);
            if (response != null) {
                String message = response.getEntity(String.class);
                System.out.println(Messages.getInstance()
                        .getString("CommandLineProcessor.INFO_REST_RESPONSE_RECEIVED", message));
            }

        } else {
            FileInputStream metadataDatasourceInputStream = new FileInputStream(metadataDatasourceFile);

            part.field("overwrite", "true".equals(overwrite) ? "true" : "false",
                    MediaType.MULTIPART_FORM_DATA_TYPE);
            part.field("domainId", domainId, MediaType.MULTIPART_FORM_DATA_TYPE).field("metadataFile",
                    metadataDatasourceInputStream, MediaType.MULTIPART_FORM_DATA_TYPE);

            // If the import service needs the file name do the following.
            part.getField("metadataFile").setContentDisposition(FormDataContentDisposition.name("metadataFile")
                    .fileName(metadataDatasourceFile.getName()).build());

            // Response response
            ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class,
                    part);
            if (response != null) {
                String message = response.getEntity(String.class);
                System.out.println(Messages.getInstance()
                        .getString("CommandLineProcessor.INFO_REST_RESPONSE_RECEIVED", message));
            }
            metadataDatasourceInputStream.close();
        }
    } finally {
        metadataFileInZipInputStream.close();
        part.cleanup();
    }

}