Example usage for java.util.zip ZipFile ZipFile

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

Introduction

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

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * Given a set of validation messages and a DOCX file to which those messages apply, 
 * creates a Word comment for each message, attached either to the paragraph the
 * message points to (by XPath) or to the first paragraph of the document if there
 * is not XPath for the message./*from  ww w  .j a  v a  2  s .  c  o m*/
 * @param docxFile The DOCX file to be updated.
 * @param newDocxFile New DOCX file that will be a copy of the input DOCX with comments added.
 * @param logDoc The messages document as a DOM.
 * @throws ZipException
 * @throws IOException
 * @throws BosMemberValidationException
 * @throws DomException
 * @throws Exception
 * @throws XPathExpressionException
 * @throws FileNotFoundException
 */
public static void addValidationMessagesToDocxFile(File docxFile, File newDocxFile, Document logDoc)
        throws ZipException, IOException, BosMemberValidationException, DomException, Exception,
        XPathExpressionException, FileNotFoundException {
    String[] catalogs = new String[0];
    Document documentDom = null;
    Document commentsDom = null;

    Map<URI, Document> domCache = new HashMap<URI, Document>();
    BosConstructionOptions bosOptions = new BosConstructionOptions(log, domCache);
    bosOptions.setCatalogs(catalogs);

    ZipFile docxZip = new ZipFile(docxFile);
    ZipComponents zipComponents = new ZipComponents(docxZip);

    ZipComponent documentXml = zipComponents.getEntry(DocxConstants.DOCUMENT_XML_PATH);

    // Load comments template doc:

    URL commentsTemplateUrl = DocxConstants.class.getResource("resources/comments.xml");
    Element commentTemplate = Word2DitaValidationHelper.getCommentTemplate(commentsTemplateUrl, bosOptions);
    commentsDom = Word2DitaValidationHelper.getCommentsDom(bosOptions, zipComponents, commentsTemplateUrl);

    documentDom = zipComponents.getDomForZipComponent(bosOptions, DocxConstants.DOCUMENT_XML_PATH);
    addMessagesToDocxXml(logDoc, documentDom, commentsDom, commentTemplate);
    Word2DitaValidationHelper.saveDomToZipComponent(documentDom, documentXml);

    ZipComponent comments = zipComponents.getEntry(DocxConstants.COMMENTS_XML_PATH);
    if (comments == null) {
        comments = zipComponents.createZipComponent(DocxConstants.COMMENTS_XML_PATH);
    }
    // System.out.println("[1] Comments.xml: " + IOUtils.toString(DomUtil.serializeToInputStream(commentsDom)));
    Word2DitaValidationHelper.saveDomToZipComponent(commentsDom,
            zipComponents.getEntry(DocxConstants.COMMENTS_XML_PATH));

    Word2DitaValidationHelper.addCommentFileRelationship(zipComponents, bosOptions);
    Word2DitaValidationHelper.addCommentFileContentType(zipComponents, bosOptions);

    Word2DitaValidationHelper.saveZipComponents(zipComponents, newDocxFile);
}

From source file:com.servoy.extension.install.CopyZipEntryImporter.java

public void handleFile() {
    if (expFile != null && expFile.exists() && expFile.isFile() && expFile.canRead()
            && expFile.getName().endsWith(FileBasedExtensionProvider.EXTENSION_PACKAGE_FILE_EXTENSION)
            && installDir != null && installDir.exists() && installDir.isDirectory() && installDir.canWrite()) {
        ZipFile zipFile = null;//from   w w  w  .  j  av a  2  s  .  c  o  m
        try {
            zipFile = new ZipFile(expFile);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory()) {
                    String fileName = entry.getName().replace('\\', '/');
                    fileName = fileName.replace(WEBTEMPLATES_SOURCE_FOLDER, WEBTEMPLATES_DESTINATION_FOLDER);
                    File outputFile = new File(installDir, fileName);
                    handleZipEntry(outputFile, zipFile, entry);
                }
            }
        } catch (IOException ex) {
            String tmp = "Exception while handling entries of expFile: " + expFile; //$NON-NLS-1$
            messages.addError(tmp);
            Debug.error(tmp, ex);
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    // ignore
                }
            }

            enforceBackUpFolderLimit();
        }
        handleExpFile();
    } else {
        // shouldn't happen
        String tmp = "Invalid install/uninstall file/destination: " + expFile + ", " + installDir; //$NON-NLS-1$//$NON-NLS-2$
        messages.addError(tmp);
        Debug.error(tmp);
    }
}

From source file:com.skwas.cordova.appinfo.AppInfo.java

public static long getBuildDate(Context context) {

    ZipFile zf = null;//from  w  w w .ja v a  2 s  .  c o  m
    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
        zf = new ZipFile(ai.sourceDir);
        ZipEntry ze = zf.getEntry("classes.dex");
        long time = ze.getTime();
        return time;

    } catch (Exception e) {
    }

    finally {
        try {
            if (zf != null)
                zf.close();
        } catch (IOException e) {
        }
    }

    return 0l;
}

From source file:com.mgmtp.jfunk.common.util.Configuration.java

/**
 * Loads a properties file. If the file is a zip file, the file {@code testing.properties} is
 * loaded from the zip file root directory. Otherwise,
 * {@link ResourceLoader#getConfigInputStream(String)} is used to load the file.
 * //from w  ww . jav  a2 s .com
 * @param fileName
 *            The file name
 * @param preserveExisting
 *            If {@code true}, existing properties will not be overwritten from the specified
 *            properties file.
 */
public void load(final String fileName, final boolean preserveExisting) {
    logger.info("Loading config file: {} (preserveExisting={})", fileName, preserveExisting);

    InputStream is = null;
    try {
        loadingDepth++;
        if (fileName.endsWith(JFunkConstants.ZIP_FILE_SUFFIX)) {
            logger.info("Loading zip archive '{}'...", fileName);
            zipArchive = new ZipFile(fileName);
            ZipEntry entry = zipArchive.getEntry(JFunkConstants.SCRIPT_PROPERTIES);
            if (entry == null) {
                entry = zipArchive.getEntry("script.properties");
            }
            is = zipArchive.getInputStream(entry);
            // keeping preExisting properties is activated with preserveExisting set to true
            doLoad(is, preserveExisting);
        } else {
            is = ResourceLoader.getConfigInputStream(fileName);
            logger.info("Loading file '{}'...", fileName);

            // System properties must always be loaded before extra properties are,
            // so they can use System properties in placeholders
            putAll(ExtendedProperties.fromProperties(System.getProperties()));
            doLoad(is, preserveExisting);
            loadExtraFiles(JFunkConstants.SYSTEM_PROPERTIES, preserveExisting);
        }

        if (loadingDepth == 1) {
            // Add System properties again because they also take precedence over extra properties
            putAll(ExtendedProperties.fromProperties(System.getProperties()));

            // Archiving is always necessary when execution mode is 'start'.
            // Otherwise continuing after the breakpoint would not be possible.
            if (JFunkConstants.EXECUTION_MODE_START.equals(get(JFunkConstants.EXECUTION_MODE))) {
                put(JFunkConstants.ARCHIVING_MODE, JFunkConstants.ARCHIVING_MODE_ALL);
            }

            Properties props = System.getProperties();
            copyProperty(props, this, JFunkConstants.JAVAX_NET_SSL_KEY_STORE_PASSWORD);
            copyProperty(props, this, JFunkConstants.JAVAX_NET_SSL_KEY_STORE);
            copyProperty(props, this, JFunkConstants.JAVAX_NET_SSL_KEY_STORE_TYPE);
            copyProperty(props, this, JFunkConstants.JAVAX_NET_SSL_TRUST_STORE_PASSWORD);
            copyProperty(props, this, JFunkConstants.JAVAX_NET_SSL_TRUST_STORE);
            copyProperty(props, this, JFunkConstants.JAVAX_NET_SSL_TRUST_STORE_TYPE);
        }
        loadingDepth--;
    } catch (IOException ex) {
        throw new JFunkException("Error loading properties: " + fileName, ex);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:org.adl.samplerte.server.LMSPackageHandler.java

/****************************************************************************
**
** Method:   display()//from w w  w.j  av a 2s  .c om
** Input:  String zipFileName  --  The name of the zip file to be used    
** Output:   none
**
** Description: This method is being used as a debugging tool.  It writes
**              the contents of a zip file to the dos console.
**
*****************************************************************************/
public static void display(String zipFileName) {
    if (_Debug) {
        System.out.println("*************");
        System.out.println("in display()");
        System.out.println("*************\n");
    }
    try {
        System.out.println("** " + zipFileName + " **\n");
        System.out.println("*****************************************");
        System.out.println("The Package Contains the following files:");
        System.out.println("*****************************************\n");

        zf = new ZipFile(zipFileName);

        for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
            System.out.println(((ZipEntry) entries.nextElement()).getName());
        }

        zf.close();
    } catch (IOException e) {
        System.out.println("IO Exception Caught: " + e);
    }
    if (_Debug) {
        System.out.println("\n\n");
    }
}

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

private void loadAndVerify() throws TranslationException {
    ZipFile zf = null;/*from   w w  w. ja  v a2s.c  o  m*/
    try {
        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:UnZip.java

/** For a given Zip file, process each entry. */
public void unZip(String fileName) {
    dirsMade = new TreeSet();
    try {/*from   w  ww  . ja v a  2s  .  co m*/
        zippy = new ZipFile(fileName);
        Enumeration all = zippy.entries();
        while (all.hasMoreElements()) {
            getFile((ZipEntry) all.nextElement());
        }
    } catch (IOException err) {
        System.err.println("IO Error: " + err);
        return;
    }
}

From source file:ccm.pay2spawn.types.MusicType.java

@Override
public void printHelpList(File configFolder) {
    musicFolder = new File(configFolder, "music");
    if (musicFolder.mkdirs()) {
        new Thread(new Runnable() {
            @Override//from  w ww .java2 s  . co  m
            public void run() {
                try {
                    File zip = new File(musicFolder, "music.zip");
                    FileUtils.copyURLToFile(new URL(Constants.MUSICURL), zip);
                    ZipFile zipFile = new ZipFile(zip);
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        File entryDestination = new File(musicFolder, entry.getName());
                        entryDestination.getParentFile().mkdirs();
                        InputStream in = zipFile.getInputStream(entry);
                        OutputStream out = new FileOutputStream(entryDestination);
                        IOUtils.copy(in, out);
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                    }
                    zipFile.close();
                    zip.delete();
                } catch (IOException e) {
                    Pay2Spawn.getLogger()
                            .warn("Error downloading music file. Get from github and unpack yourself please.");
                    e.printStackTrace();
                }
            }
        }, "Pay2Spawn music download and unzip").start();
    }
}

From source file:ch.ivyteam.ivy.maven.TestIarPackagingMojo.java

@Test
public void canDefineCustomExclusions() throws Exception {
    IarPackagingMojo mojo = rule.getMojo();
    String filterCandidate = "private/notPublic.txt";
    assertThat(new File(mojo.project.getBasedir(), filterCandidate)).exists();

    mojo.iarExcludes = new String[] { "private", "private/**/*" };
    mojo.execute();/*from w  w  w .  j  av a2 s.c  om*/
    try (ZipFile archive = new ZipFile(mojo.project.getArtifact().getFile())) {
        assertThat(archive.getEntry("private")).as("Custom exclusion must be filtered").isNull();
        assertThat(archive.getEntry(filterCandidate)).as("Custom exclusion must be filtered").isNull();
        assertThat(archive.size()).isGreaterThan(50).as("archive must contain content");
    }
}

From source file:net.solarnetwork.node.backup.test.DefaultBackupManagerTest.java

@Test
public void createBackup() throws IOException {
    List<BackupResourceProvider> providers = new ArrayList<BackupResourceProvider>();
    List<BackupResource> resources = new ArrayList<BackupResource>();
    ClassPathResource txtResource = new ClassPathResource(TEST_FILE_TXT, DefaultBackupManagerTest.class);
    resources.add(new ResourceBackupResource(txtResource, TEST_FILE_TXT));
    providers.add(new StaticBackupResourceProvider(resources, RESTORE_DIR));
    manager.setResourceProviders(providers);
    final Backup backup = manager.createBackup();
    assertNotNull(backup);// w w w  .ja  v  a  2s  . c  om

    final File archiveFile = new File(service.getBackupDir(),
            String.format(FileSystemBackupService.ARCHIVE_KEY_NAME_FORMAT, backup.getKey()));
    assertTrue(archiveFile.canRead());
    ZipFile zipFile = new ZipFile(archiveFile);
    try {
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        int entryCount;
        for (entryCount = 0; entries.hasMoreElements(); entryCount++) {
            ZipEntry entry = entries.nextElement();
            assertEquals("The zip entry should be prefixed by the BackupResourceProvider key",
                    DefaultBackupManagerTest.class.getName() + '/' + TEST_FILE_TXT, entry.getName());
        }
        assertEquals(1, entryCount);
        this.backup = backup;
    } finally {
        zipFile.close();
    }
}