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:org.artifactory.repo.service.ArchiveContentRetriever.java

public ArchiveFileContent getArchiveFileContent(LocalRepo repo, RepoPath archivePath, String archiveEntryPath)
        throws IOException {
    String content = null;/*from   www  . j a  va2  s.c  o m*/
    String sourceJarPath = null;
    List<String> searchList = null;
    String failureReason = null;
    ZipInputStream jis = null;
    String sourceEntryPath = null;
    try {
        if (archiveEntryPath.endsWith(".class")) {
            sourceEntryPath = NamingUtils.javaSourceNameFromClassName(archiveEntryPath);
            // locate the sources jar and find the source file in it
            String sourceJarName = PathUtils.stripExtension(archivePath.getName()) + "-sources."
                    + PathUtils.getExtension(archivePath.getName());
            String sourcesJarPath = archivePath.getParent().getPath() + "/" + sourceJarName;
            // search in the sources file first
            searchList = Lists.newArrayList(sourcesJarPath, archivePath.getPath());
        } else if (isTextFile(archiveEntryPath)) {
            // read directly from this archive
            searchList = Lists.newArrayList(archivePath.getPath());
            sourceEntryPath = archiveEntryPath;
        } else {
            failureReason = "View source for " + archiveEntryPath + " is not supported";
        }

        if (searchList != null) {
            boolean found = false;
            for (int i = 0; i < searchList.size() && !found; i++) {
                String sourcesJarPath = searchList.get(i);
                log.debug("Looking for {} source in {}", sourceEntryPath, sourceJarPath);
                VfsFile sourceFile = repo.getImmutableFile(new RepoPathImpl(repo.getKey(), sourcesJarPath));
                if (sourceFile == null) {
                    failureReason = "Source jar not found.";
                } else if (!ContextHelper.get().getAuthorizationService()
                        .canRead(InternalRepoPathFactory.create(repo.getKey(), sourcesJarPath))) {
                    failureReason = "No read permissions for the source jar.";
                } else {
                    List<String> alternativeExtensions = null;
                    if ("java".equalsIgnoreCase(PathUtils.getExtension(sourceEntryPath))) {
                        alternativeExtensions = Lists.newArrayList("groovy", "fx");
                    }

                    jis = new ZipInputStream(sourceFile.getStream());
                    ZipEntry zipEntry = ZipUtils.locateEntry(jis, sourceEntryPath, alternativeExtensions);
                    if (zipEntry == null) {
                        failureReason = "Source file not found.";
                    } else {
                        found = true; // source entry was found in the jar
                        int maxAllowedSize = 1024 * 1024;
                        if (zipEntry.getSize() > maxAllowedSize) {
                            failureReason = String.format(
                                    "Source file is too big to render: file size: %s, max size: %s.",
                                    zipEntry.getSize(), maxAllowedSize);

                        } else {
                            // read the current entry (the source entry path)
                            content = IOUtils.toString(jis, "UTF-8");
                            sourceEntryPath = zipEntry.getName();
                            sourceJarPath = sourcesJarPath;
                        }
                    }
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(jis);
    }

    if (content != null) {
        return new ArchiveFileContent(content, InternalRepoPathFactory.create(repo.getKey(), sourceJarPath),
                sourceEntryPath);
    } else {
        return ArchiveFileContent.contentNotFound(failureReason);
    }
}

From source file:org.nebulaframework.deployment.classloading.GridArchiveClassLoader.java

/**
 * Searches given JAR file stream within the {@code GridArchive} to
 * locate a specified class file. //  ww  w  .java  2s . c  o  m
 * <p>
 * Note that as it is implemented to read from Zip file stream, 
 * this requires each entry with in the JAR to be matched 
 * against the required class file's expected path.
 * <p>
 * An alternate implementation would be to implement this to write each
 * JAR file as a temporary file and then use direct path to find the 
 * class file. However, this implementation proved to be much slower
 * than the current implementation, due to slow disk access times.
 *  
 * @param inStream {@code InputStream} for the JAR file
 * @param fileName expected filename of the Class to be found
 * 
 * @return The {@code byte[]} for the class file, if found, or {@code null}
 * 
 * @throws IOException if an IO error occurs during operation
 */
protected byte[] findInJarStream(InputStream inStream, String fileName) throws IOException {

    // Get ZipInputStream to unzip content
    ZipInputStream zipInStream = new ZipInputStream(inStream);

    ZipEntry entry = null;

    // Compare against each entry
    while ((entry = zipInStream.getNextEntry()) != null) {
        // If match found
        if (entry.getName().equals(fileName)) {
            log.debug("Match Found");
            return IOSupport.readBytes(zipInStream, entry.getSize());
        }
    }

    // Not Found, return null
    return null;
}

From source file:com.sshtools.j2ssh.util.DynamicClassLoader.java

private byte[] loadClassFromZipfile(File file, String name, ClassCacheEntry cache) throws IOException {
    // Translate class name to file name
    String classFileName = name.replace('.', '/') + ".class";

    ZipFile zipfile = new ZipFile(file);

    try {/*from   w  ww  .ja v  a2  s  .  c o m*/
        ZipEntry entry = zipfile.getEntry(classFileName);

        if (entry != null) {
            cache.origin = file;

            return loadBytesFromStream(zipfile.getInputStream(entry), (int) entry.getSize());
        } else {
            // Not found
            return null;
        }
    } finally {
        zipfile.close();
    }
}

From source file:com.sshtools.j2ssh.util.ExtensionClassLoader.java

private byte[] loadClassFromZipfile(File file, String name, ClassCacheEntry cache) throws IOException {
    // Translate class name to file name
    String classFileName = name.replace('.', '/') + ".class";

    ZipFile zipfile = new ZipFile(file);

    try {/*from   ww w  . j  a va 2  s .c o m*/
        ZipEntry entry = zipfile.getEntry(classFileName);

        if (entry != null) {
            if (cache != null) {
                cache.origin = file;

            }
            return loadBytesFromStream(zipfile.getInputStream(entry), (int) entry.getSize());
        } else {
            // Not found
            return null;
        }
    } finally {
        zipfile.close();
    }
}

From source file:org.photovault.imginfo.DataExporter.java

/**
 * Reads a zip file entry into byte array
 * @param e The entry to read//from ww w  .ja v  a  2s  .  c  om
 * @param zipis ZipInputStream that is read
 * @return The data in entry
 * @throws IOException
 */

private byte[] readZipEntry(ZipEntry e, ZipInputStream zipis) throws IOException {
    long esize = e.getSize();
    byte[] data = null;
    if (esize > 0) {
        data = new byte[(int) esize];
        zipis.read(data);
    } else {
        byte[] tmp = new byte[65536];
        int offset = 0;
        int bytesRead = 0;
        while ((bytesRead = zipis.read(tmp, offset, tmp.length - offset)) > 0) {
            offset += bytesRead;
            if (offset >= tmp.length) {
                tmp = Arrays.copyOf(tmp, tmp.length * 2);
            }
        }
        data = Arrays.copyOf(tmp, offset);
    }
    return data;
}

From source file:org.pentaho.reporting.libraries.repository.zip.ZipContentLocation.java

public ZipContentLocation(ZipRepository repository, ZipContentLocation parent, ZipEntry zipEntry) {
    if (repository == null) {
        throw new NullPointerException();
    }/*  www .jav a 2s .  c o  m*/
    if (parent == null) {
        throw new NullPointerException();
    }
    if (zipEntry == null) {
        throw new NullPointerException();
    }

    this.repository = repository;
    this.parent = parent;
    this.entryName = IOUtils.getInstance().getFileName(zipEntry.getName());
    this.comment = zipEntry.getComment();
    this.size = zipEntry.getSize();
    this.time = zipEntry.getTime();
    this.entries = new HashMap();
    this.name = RepositoryUtilities.buildName(this, "/") + '/';
}

From source file:slash.navigation.download.tools.UpdateCatalog.java

private void updateMap(DatasourceType datasourceType, Map map) throws IOException {
    String url = datasourceType.getBaseUrl() + map.getUri();

    // HEAD for last modified, content length, etag
    Download download = head(url);//from ww  w  . j  a va2s . c  o  m
    if (download.getState().equals(NotModified))
        return;

    if (download.getState().equals(Failed)) {
        log.severe(format("Failed to download %s as a map", map.getUri()));
        return;
    }

    Checksum checksum = download.getFile().getActualChecksum();
    MapType mapType = createMapType(map.getUri(), singletonList(checksum), null);
    datasourceType.getMap().add(mapType);

    // GET with range for .zip or .map header
    if (!download.getFile().getFile().exists())
        download = downloadPartial(url, checksum.getContentLength());

    if (download.getState().equals(Failed)) {
        log.severe(format("Failed to download %s partially as a map", map.getUri()));
        return;
    }

    if (map.getUri().endsWith(DOT_ZIP)) {
        try (ZipInputStream zipInputStream = new ZipInputStream(
                new FileInputStream(download.getFile().getFile()))) {
            ZipEntry entry = zipInputStream.getNextEntry();
            while (entry != null) {
                if (!entry.isDirectory() && entry.getName().endsWith(DOT_MAP)) {
                    log.info(format("Found map %s in URI %s", entry.getName(), map.getUri()));
                    mapType.getFragment()
                            .add(createFragmentType(entry.getName(), entry.getTime(), entry.getSize()));

                    BoundingBox boundingBox = MapUtil.extractBoundingBox(zipInputStream, entry.getSize());
                    if (boundingBox != null)
                        mapType.setBoundingBox(asBoundingBoxType(boundingBox));

                    // do not close zip input stream and cope with partially copied zips
                    try {
                        zipInputStream.closeEntry();
                    } catch (EOFException e) {
                        // intentionally left empty
                    }
                }

                try {
                    entry = zipInputStream.getNextEntry();
                } catch (EOFException e) {
                    entry = null;
                }
            }
        }

    } else if (map.getUri().endsWith(DOT_MAP)) {
        log.info(format("Found map %s", map.getUri()));
        BoundingBox boundingBox = MapUtil.extractBoundingBox(download.getFile().getFile());
        if (boundingBox != null)
            mapType.setBoundingBox(asBoundingBoxType(boundingBox));
    } else
        log.warning(format("Ignoring %s as a map", map.getUri()));

    updatePartially(datasourceType);
}

From source file:org.paxle.tools.ieporter.cm.impl.ConfigurationIEPorter.java

public Map<String, Dictionary<String, Object>> importConfigurations(File file) throws Exception {
    BufferedInputStream input = null;
    Map<String, Dictionary<String, Object>> configs = new HashMap<String, Dictionary<String, Object>>();
    try {// w w w  . ja v  a  2 s  .  c  om
        input = new BufferedInputStream(new FileInputStream(file), 5);

        // pre-read data to detect file type
        byte[] test = new byte[5];
        input.mark(5);
        input.read(test);
        input.reset();

        if (new String(test, "UTF-8").equals("<?xml")) {
            // XML Document found
            Document doc = this.readXMLDocument(file);
            Map<String, Dictionary<String, Object>> config = this.importConfigurations(doc);
            configs.putAll(config);
        } else if (new String(test, 0, 2).equals("PK")) {
            // open zip file
            final ZipInputStream zis = new ZipInputStream(input);

            // loop through entries
            ZipEntry ze;
            while ((ze = zis.getNextEntry()) != null) {
                // skip directories
                if (ze.isDirectory())
                    continue;

                // read data into memory
                long size = ze.getSize();
                ByteArrayOutputStream bout = (size < 0) ? new ByteArrayOutputStream()
                        : new ByteArrayOutputStream((int) size);
                IOUtils.copy(zis, bout);
                bout.close();

                // read XML
                ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
                Document doc = this.readXMLStream(bin);
                bin.close();

                // parser configuration
                Map<String, Dictionary<String, Object>> config = this.importConfigurations(doc);
                configs.putAll(config);
            }

            zis.close();
        } else {
            // Unknown file
            throw new IllegalArgumentException("Unknown file type");
        }
    } finally {
        if (input != null)
            try {
                input.close();
            } catch (Exception e) {
                /* ignore this */}
    }

    return configs;
}

From source file:org.agnitas.cms.web.CMTemplateAction.java

private byte[] getEntryData(ZipInputStream zipInputStream, ZipEntry entry) throws IOException {
    byte[] fileData = new byte[(int) entry.getSize()];
    byte[] buf = new byte[2048];
    int bytesRead = 0;
    int dataIndex = 0;
    while (bytesRead != -1) {
        bytesRead = zipInputStream.read(buf);
        for (int i = 0; i < bytesRead; i++) {
            if (dataIndex < fileData.length && i < buf.length) {
                fileData[dataIndex] = buf[i];
                dataIndex++;//from  w  w w .  j  a  v a  2s .com
            }
        }
    }
    return fileData;
}

From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java

private boolean unpackZip(String path, String zipname) {
    InputStream is;// w w  w .j a va2  s  . c o  m
    ZipInputStream zis;
    BufferedInputStream bis;
    try {
        String filename;
        is = new FileInputStream(path + zipname);
        bis = new BufferedInputStream(is);
        zis = new ZipInputStream(bis);
        ZipEntry ze;
        //                 byte[] buffer = new byte[1024];
        //                 int count;
        long fileSize = 0;

        //Gesamtdownloadgre bestimmen
        //                 while ((ze = zis.getNextEntry()) != null) 
        //                 { 
        ze = zis.getNextEntry();
        fileSize = ze.getSize() + fileSize;
        //                 }

        int fileSizeInKB = (int) (fileSize / 1024);

        Message msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UNZIP_STARTED, fileSizeInKB, 0, "");
        activityHandler.sendMessage(msg);

        int bytesRead = 0, totalRead = 0;

        FileInputStream gis = new FileInputStream(path + zipname);

        BufferedInputStream fis = new BufferedInputStream(gis);

        ZipInputStream dis = new ZipInputStream(fis);

        while ((ze = dis.getNextEntry()) != null) {
            // zapis do souboru
            filename = ze.getName();

            // Need to create directories if not exists, or
            // it will generate an Exception...
            if (ze.isDirectory()) {
                File fmd = new File(path + filename);
                fmd.mkdirs();
                continue;
            }

            //

            //                BufferedInputStream inStream = new BufferedInputStream(mFTPClient.retrieveFileStream(ftpPathName));
            //                File outFile = new File(fileName);
            FileOutputStream fileStream = new FileOutputStream(path + filename);
            byte[] data = new byte[KleFuEntry.DOWNLOAD_BUFFER_SIZE];

            while (!isInterrupted() && (bytesRead = zis.read(data)) >= 0) {
                fileStream.write(data, 0, bytesRead);

                // update progress bar
                totalRead += bytesRead;
                int totalReadInKB = totalRead / 1024;
                msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UPDATE_PROGRESS_BAR, totalReadInKB, 0);
                activityHandler.sendMessage(msg);
            }
            //                
            fileStream.close();
            //                 inStream.close();

            //                     FileOutputStream fout = new FileOutputStream(path + filename);
            //
            //                     while ((count = zis.read(buffer)) != -1) 
            //                     {
            //                         fout.write(buffer, 0, count);             
            //                     }
            //
            //                     fout.close();               
            //                     zis.closeEntry();
        }

        zis.close();
        dis.close();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}