Example usage for java.util.zip ZipFile getEntry

List of usage examples for java.util.zip ZipFile getEntry

Introduction

In this page you can find the example usage for java.util.zip ZipFile getEntry.

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the zip file entry for the specified name, or null if not found.

Usage

From source file:org.digidoc4j.ContainerBuilderTest.java

@Test
public void saveContainerWithoutSignaturesToFile() throws Exception {
    File dataFile = TestDataBuilder.createTestFile(testFolder);
    Container container = TestDataBuilder.createContainerWithFile(dataFile.getPath());
    String filePath = testFolder.newFile("test-container.bdoc").getPath();
    File containerFile = container.saveAsFile(filePath);
    assertTrue(FileUtils.sizeOf(containerFile) > 0);
    ZipFile zip = new ZipFile(filePath);
    assertNotNull(zip.getEntry("mimetype"));
    assertNotNull(zip.getEntry("META-INF/manifest.xml"));
    assertNotNull(zip.getEntry(dataFile.getName()));
}

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

private URL findResourceInZipfile(File file, String name) {
    try {//  w ww. ja  va 2 s .c o m
        ZipFile zipfile = new ZipFile(file);
        ZipEntry entry = zipfile.getEntry(name);

        if (entry != null) {
            return new URL("jar:" + file.toURL() + "!" + (name.startsWith("/") ? "" : "/") + name);
        } else {
            return null;
        }
    } catch (IOException e) {
        return null;
    }

}

From source file:net.sf.zekr.engine.translation.TranslationData.java

private void loadAndVerify() throws TranslationException {
    ZipFile zf = null;
    try {/*www . j  a va  2s.co  m*/
        logger.info("Loading translation pack " + this + "...");
        zf = new ZipFile(archiveFile);
        ZipEntry ze = zf.getEntry(file);
        if (ze == null) {
            logger.error("Load failed. No proper entry found in \"" + archiveFile.getName() + "\".");
            return;
        }

        byte[] textBuf = new byte[(int) ze.getSize()];
        if (!verify(zf.getInputStream(ze), textBuf))
            logger.warn("Unauthorized translation data pack: " + this);
        // throw new TranslationException("INVALID_TRANSLATION_SIGNATURE", new String[] { name });

        refineText(new String(textBuf, encoding));

        logger.log("Translation pack " + this + " loaded successfully.");
    } catch (IOException e) {
        logger.error("Problem while loading translation pack " + this + ".");
        logger.log(e);
        throw new TranslationException(e);
    } finally {
        try {
            zf.close();
        } catch (Exception e) {
            // do nothing
        }
    }
}

From source file:org.apache.webdav.ant.taskdefs.Put.java

private void uploadZipEntry(HttpURL url, String name, ZipFile zipFile) throws IOException {
    boolean putit = false;
    ZipEntry entry = zipFile.getEntry(name);

    try {//from   w  ww .j a  v  a  2s  .  co m
        if (this.overwrite) {
            putit = true;
        } else {
            // check last modified date (both GMT)
            long remoteLastMod = Utils.getLastModified(getHttpClient(), url);
            long localLastMod = entry.getTime();
            putit = localLastMod > remoteLastMod;
        }
    } catch (HttpException e) {
        switch (e.getReasonCode()) {
        case HttpStatus.SC_NOT_FOUND:
            putit = true;
            break;
        default:
            throw Utils.makeBuildException("Can't get lastmodified!?", e);
        }
    }

    if (putit) {
        log("Uploading: " + name, ifVerbose());
        String contentType = Mimetypes.getMimeType(name, DEFAULT_CONTENT_TYPE);
        Utils.putFile(getHttpClient(), url, zipFile.getInputStream(entry), contentType, this.locktoken);
        this.countWrittenFiles++;
    } else {
        countOmittedFiles++;
        log("Omitted: " + name + " (uptodate)", ifVerbose());
    }
}

From source file:org.jboss.web.tomcat.tc5.TomcatDeployer.java

private String findConfig(URL warURL) throws IOException {
    String result = null;/*from w  w  w . j  a v a2  s  .  c om*/
    // See if the warUrl is a dir or a file
    File warFile = new File(warURL.getFile());
    if (warURL.getProtocol().equals("file") && warFile.isDirectory() == true) {
        File webDD = new File(warFile, CONTEXT_CONFIG_FILE);
        if (webDD.exists() == true)
            result = webDD.getAbsolutePath();
    } else {
        ZipFile zipFile = new ZipFile(warFile);
        ZipEntry entry = zipFile.getEntry(CONTEXT_CONFIG_FILE);
        if (entry != null) {
            InputStream zipIS = zipFile.getInputStream(entry);
            byte[] buffer = new byte[512];
            int bytes;
            result = warFile.getAbsolutePath() + "-context.xml";
            FileOutputStream fos = new FileOutputStream(result);
            while ((bytes = zipIS.read(buffer)) > 0) {
                fos.write(buffer, 0, bytes);
            }
            zipIS.close();
            fos.close();
        }
        zipFile.close();
    }
    return result;
}

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   w w  w .j a  v  a  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:com.dibsyhex.apkdissector.ZipReader.java

public void getZipEntries(String name) {
    try {//  www  .j a  v a 2  s.c  o m
        File file = new File(name);
        ZipFile zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> enumeration = zipFile.entries();

        System.out.println("Listing Entries in the apkfile");

        response.displayLog("Listing Entries in the apkfile");

        while (enumeration.hasMoreElements()) {
            Object key = enumeration.nextElement();
            //String s=key.toString()+":"+zipFile.getEntry(key.toString());
            String s = zipFile.getEntry(key.toString()).toString();
            System.out.println("  " + s);

            response.displayLog(s);
        }

        zipFile.close();
    } catch (Exception e) {
        System.out.println(e.toString());
        response.displayError(e.toString());
    }
}

From source file:com.krawler.esp.fileparser.wordparser.DocxParser.java

public String extractText(String filepath) {
    StringBuilder sb = new StringBuilder();

    ZipFile docxfile = null;
    try {/*w w  w . j  a va  2s. com*/
        docxfile = new ZipFile(filepath);
    } catch (Exception e) {
        // file corrupt or otherwise could not be found
        logger.warn(e.getMessage(), e);
        return sb.toString();
    }
    InputStream in = null;
    try {
        ZipEntry ze = docxfile.getEntry("word/document.xml");
        in = docxfile.getInputStream(ze);
    } catch (NullPointerException nulle) {
        System.err.println("Expected entry word/document.xml does not exist");
        logger.warn(nulle.getMessage(), nulle);
        return sb.toString();
    } catch (IOException ioe) {
        logger.warn(ioe.getMessage(), ioe);
        return sb.toString();
    }
    Document document = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.parse(in);
    } catch (ParserConfigurationException pce) {
        logger.warn(pce.getMessage(), pce);
        return sb.toString();
    } catch (SAXException sex) {
        sex.printStackTrace();
        return sb.toString();
    } catch (IOException ioe) {
        logger.warn(ioe.getMessage(), ioe);
        return sb.toString();
    } finally {
        try {
            docxfile.close();
        } catch (IOException ioe) {
            System.err.println("Exception closing file.");
            logger.warn(ioe.getMessage(), ioe);
        }
    }
    NodeList list = document.getElementsByTagName("w:t");
    List<String> content = new ArrayList<String>();
    for (int i = 0; i < list.getLength(); i++) {
        Node aNode = list.item(i);
        content.add(aNode.getFirstChild().getNodeValue());
    }
    for (String s : content) {
        sb.append(s);
    }

    return sb.toString();
}

From source file:org.jboss.windup.interrogator.impl.ClassInterrogator.java

private JavaMetadata extractJavaFile(String className, Set<String> clzImports, ZipEntryMetadata archiveEntry) {
    JavaMetadata javaMeta = new JavaMetadata();
    try {// w w w . j a  v  a  2  s . co  m
        File clzFile;
        File javaFile;

        //TODO: make this work for directorymeta too.
        ZipMetadata zipMeta = (ZipMetadata) archiveEntry.getArchiveMeta();
        ZipFile zipFile = zipMeta.getZipFile();
        ZipEntry entry = archiveEntry.getZipEntry();
        // check to see whether the Java version is packaged with the archive...
        String javaZipEntry = StringUtils.removeEnd(entry.getName(), ".class") + ".java";

        if (zipFile.getEntry(javaZipEntry) != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found Java in archive: " + className);
            }
            ZipEntry javaEntry = zipFile.getEntry(javaZipEntry);
            archiveEntry.setZipEntry(javaEntry);
            javaFile = archiveEntry.getFilePointer();
        } else {
            clzFile = archiveEntry.getFilePointer();
            javaFile = new File(StringUtils.substringBeforeLast(clzFile.getAbsolutePath(), ".class") + ".java");
            File javaPathFile = new File(
                    StringUtils.substringBeforeLast(clzFile.getAbsolutePath(), File.separator));

            if (LOG.isDebugEnabled()) {
                LOG.debug("Did not find class in archive. Decompiling class: " + className);
            }
            decompiler.decompile(className, clzFile, javaPathFile);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Unzipped class: " + className);
            }
        }

        javaMeta.setFilePointer(javaFile);
        javaMeta.setArchiveMeta(archiveEntry.getArchiveMeta());
        javaMeta.setClassDependencies(clzImports);
        javaMeta.setQualifiedClassName(className);
        javaMeta.setBlackListedDependencies(blacklistPackageResolver.extractBlacklist(clzImports));

        return javaMeta;
    } catch (Exception e) {
        if (e instanceof FatalWindupException) {
            throw (FatalWindupException) e;
        }

        LOG.error(e);
        return null;
    }
}

From source file:hudson.model.DirectoryBrowserSupportTest.java

@Issue("JENKINS-19752")
@Test/*from  w ww.  ja  va  2s . c  om*/
public void zipDownload() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    p.setScm(new SingleFileSCM("artifact.out", "Hello world!"));
    p.getPublishersList().add(new ArtifactArchiver("*", "", true));
    assertEquals(Result.SUCCESS, p.scheduleBuild2(0).get().getResult());

    HtmlPage page = j.createWebClient().goTo("job/" + p.getName() + "/lastSuccessfulBuild/artifact/");
    Page download = page.getAnchorByHref("./*zip*/archive.zip").click();
    File zipfile = download((UnexpectedPage) download);

    ZipFile readzip = new ZipFile(zipfile);

    InputStream is = readzip.getInputStream(readzip.getEntry("archive/artifact.out"));

    // ZipException in case of JENKINS-19752
    assertFalse("Downloaded zip file must not be empty", is.read() == -1);

    is.close();
    readzip.close();
    zipfile.delete();
}