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:com.adaptris.core.lms.ZipFileBackedMessageTest.java

/**
 * This tests creates a compressed file//w ww.j  a v a 2 s  .c om
 */
@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:cpw.mods.fml.server.FMLServerHandler.java

private void searchZipForENUSLanguage(File source) throws IOException {
    ZipFile zf = new ZipFile(source);
    for (ZipEntry ze : Collections.list(zf.entries())) {
        Matcher matcher = assetENUSLang.matcher(ze.getName());
        if (matcher.matches()) {
            FMLLog.fine("Injecting found translation data in zip file %s at %s into language system",
                    source.getName(), ze.getName());
            StringTranslate.inject(zf.getInputStream(ze));
        }/*w  ww.  j  av a2 s.co m*/
    }
    zf.close();
}

From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.RemoteApiController.java

/**
 * Create a new project.//from  w w  w  .ja v  a 2  s.c om
 *
 * To test, use the Linux "curl" command.
 *
 * curl -v -F 'file=@test.zip' -F 'name=Test' -F 'filetype=tcf'
 * 'http://USERNAME:PASSWORD@localhost:8080/de.tudarmstadt.ukp.clarin.webanno.webapp/api/project
 * '
 *
 * @param aName
 *            the name of the project to create.
 * @param aFileType
 *            the type of the files contained in the ZIP. The possible file types are configured
 *            in the formats.properties configuration file of WebAnno.
 * @param aFile
 *            a ZIP file containing the project data.
 * @throws Exception if there was en error.
 */
@RequestMapping(value = "/project", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseStatus(HttpStatus.NO_CONTENT) void createProject(@RequestParam("file") MultipartFile aFile,
        @RequestParam("name") String aName, @RequestParam("filetype") String aFileType) throws Exception {
    LOG.info("Creating project [" + aName + "]");

    if (!ZipUtils.isZipStream(aFile.getInputStream())) {
        throw new InvalidFileNameException("", "is an invalid Zip file");
    }

    // Get current user
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    User user = userRepository.get(username);
    Project project = null;

    // Configure project
    if (!projectRepository.existsProject(aName)) {
        project = new Project();
        project.setName(aName);

        // Create the project and initialize tags
        projectRepository.createProject(project, user);
        annotationService.initializeTypesForProject(project, user, new String[] {}, new String[] {},
                new String[] {}, new String[] {}, new String[] {}, new String[] {}, new String[] {},
                new String[] {});
        // Create permission for this user
        ProjectPermission permission = new ProjectPermission();
        permission.setLevel(PermissionLevel.ADMIN);
        permission.setProject(project);
        permission.setUser(username);
        projectRepository.createProjectPermission(permission);

        permission = new ProjectPermission();
        permission.setLevel(PermissionLevel.USER);
        permission.setProject(project);
        permission.setUser(username);
        projectRepository.createProjectPermission(permission);
    }
    // Existing project
    else {
        throw new IOException("The project with name [" + aName + "] exists");
    }

    // Iterate through all the files in the ZIP

    // If the current filename does not start with "." and is in the root folder of the ZIP,
    // import it as a source document
    File zimpFile = File.createTempFile(aFile.getOriginalFilename(), ".zip");
    aFile.transferTo(zimpFile);
    ZipFile zip = new ZipFile(zimpFile);

    for (Enumeration<?> zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) {
        //
        // Get ZipEntry which is a file or a directory
        //
        ZipEntry entry = (ZipEntry) zipEnumerate.nextElement();

        // If it is the zip name, ignore it
        if ((FilenameUtils.removeExtension(aFile.getOriginalFilename()) + "/").equals(entry.toString())) {
            continue;
        }
        // IF the current filename is META-INF/webanno/source-meta-data.properties store it
        // as
        // project meta data
        else if (entry.toString().replace("/", "")
                .equals((META_INF + "webanno/source-meta-data.properties").replace("/", ""))) {
            InputStream zipStream = zip.getInputStream(entry);
            projectRepository.savePropertiesFile(project, zipStream, entry.toString());

        }
        // File not in the Zip's root folder OR not
        // META-INF/webanno/source-meta-data.properties
        else if (StringUtils.countMatches(entry.toString(), "/") > 1) {
            continue;
        }
        // If the current filename does not start with "." and is in the root folder of the
        // ZIP, import it as a source document
        else if (!FilenameUtils.getExtension(entry.toString()).equals("")
                && !FilenameUtils.getName(entry.toString()).equals(".")) {

            uploadSourceDocument(zip, entry, project, user, aFileType);
        }

    }

    LOG.info("Successfully created project [" + aName + "] for user [" + username + "]");

}

From source file:com.github.chenxiaolong.dualbootpatcher.switcher.service.BootUIActionTask.java

/**
 * Get currently installed version of boot UI
 *
 * @param iface Mbtool interface/*from   w w  w .j  av a  2  s . c o m*/
 * @return The {@link Version} installed or null if an error occurs or the version number is
 *         invalid
 * @throws IOException
 * @throws MbtoolException
 */
@Nullable
private Version getCurrentVersion(MbtoolInterface iface) throws IOException, MbtoolException {
    String mountPoint = getCacheMountPoint(iface);
    String zipPath = mountPoint + MAPPINGS[0].target;

    File tempZip = new File(getContext().getCacheDir() + "/bootui.zip");
    tempZip.delete();

    try {
        iface.pathCopy(zipPath, tempZip.getAbsolutePath());
        iface.pathChmod(tempZip.getAbsolutePath(), 0644);

        // Set SELinux label
        try {
            String label = iface.pathSelinuxGetLabel(tempZip.getParent(), false);
            iface.pathSelinuxSetLabel(tempZip.getAbsolutePath(), label, false);
        } catch (MbtoolCommandException e) {
            Log.w(TAG, tempZip + ": Failed to set SELinux label", e);
        }
    } catch (MbtoolCommandException e) {
        return null;
    }

    ZipFile zf = null;
    String versionStr = null;
    String gitVersionStr = null;

    try {
        zf = new ZipFile(tempZip);

        final Enumeration<? extends ZipEntry> entries = zf.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry ze = entries.nextElement();

            if (ze.getName().equals(PROPERTIES_FILE)) {
                Properties prop = new Properties();
                prop.load(zf.getInputStream(ze));
                versionStr = prop.getProperty(PROP_VERSION);
                gitVersionStr = prop.getProperty(PROP_GIT_VERSION);
                break;
            }
        }
    } catch (IOException e) {
        Log.e(TAG, "Failed to read bootui.zip", e);
    } finally {
        if (zf != null) {
            try {
                zf.close();
            } catch (IOException e) {
                // Ignore
            }
        }

        tempZip.delete();
    }

    Log.d(TAG, "Boot UI version: " + versionStr);
    Log.d(TAG, "Boot UI git version: " + gitVersionStr);

    if (versionStr != null) {
        return Version.from(versionStr);
    } else {
        return null;
    }
}

From source file:com.alibaba.jstorm.yarn.utils.JStormUtils.java

/**
 * Extra dir from the jar to destdir//from   w  w w . ja  va 2 s. co  m
 *
 * @param jarpath
 * @param dir
 * @param destdir
 */
public static void extractDirFromJar(String jarpath, String dir, String destdir) {
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(jarpath);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries != null && entries.hasMoreElements()) {
            ZipEntry ze = entries.nextElement();
            if (!ze.isDirectory() && ze.getName().startsWith(dir)) {
                InputStream in = zipFile.getInputStream(ze);
                try {
                    File file = new File(destdir, ze.getName());
                    if (!file.getParentFile().mkdirs()) {
                        if (!file.getParentFile().isDirectory()) {
                            throw new IOException("Mkdirs failed to create " + file.getParentFile().toString());
                        }
                    }
                    OutputStream out = new FileOutputStream(file);
                    try {
                        byte[] buffer = new byte[8192];
                        int i;
                        while ((i = in.read(buffer)) != -1) {
                            out.write(buffer, 0, i);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    if (in != null)
                        in.close();
                }
            }
        }
    } catch (Exception e) {
        LOG.warn("No " + dir + " from " + jarpath + "!\n" + e.getMessage());
    } finally {
        if (zipFile != null)
            try {
                zipFile.close();
            } catch (Exception e) {
                LOG.warn(e.getMessage());
            }

    }
}

From source file:com.yunrang.hadoop.app.utils.CustomizedUtil.java

/**
 * Add entries to <code>packagedClasses</code> corresponding to class files
 * contained in <code>jar</code>.
 * /*  w  ww  .ja  v a  2s.c  o m*/
 * @param jar
 *            The jar who's content to list.
 * @param packagedClasses
 *            map[class -> jar]
 */
public static void updateMap(String jar, Map<String, String> packagedClasses) throws IOException {
    if (null == jar || jar.isEmpty()) {
        return;
    }
    ZipFile zip = null;
    try {
        zip = new ZipFile(jar);
        for (Enumeration<? extends ZipEntry> iter = zip.entries(); iter.hasMoreElements();) {
            ZipEntry entry = iter.nextElement();
            if (entry.getName().endsWith("class")) {
                packagedClasses.put(entry.getName(), jar);
            }
        }
    } finally {
        if (null != zip)
            zip.close();
    }
}

From source file:net.amigocraft.mpt.command.InstallCommand.java

public static void installPackage(String id) throws MPTException {
    if (Thread.currentThread().getId() == Main.mainThreadId)
        throw new MPTException(ERROR_COLOR + "Packages may not be installed from the main thread!");
    id = id.toLowerCase();/*from   www  .j ava 2  s .  co  m*/
    try {
        File file = new File(Main.plugin.getDataFolder(), "cache" + File.separator + id + ".zip");
        if (!file.exists())
            downloadPackage(id);
        if (!Main.packageStore.containsKey("packages")
                && ((JSONObject) Main.packageStore.get("packages")).containsKey(id))
            throw new MPTException(
                    ERROR_COLOR + "Cannot find package by id " + ID_COLOR + id + ERROR_COLOR + "!");
        JSONObject pack = (JSONObject) ((JSONObject) Main.packageStore.get("packages")).get(id);
        List<String> files = new ArrayList<>();
        lockStores();
        boolean success = MiscUtil.unzip(new ZipFile(file), Bukkit.getWorldContainer(), files);
        if (!KEEP_ARCHIVES)
            file.delete();
        pack.put("installed", pack.get("version").toString());
        JSONArray fileArray = new JSONArray();
        for (String str : files)
            fileArray.add(str);
        pack.put("files", fileArray);
        try {
            writePackageStore();
        } catch (IOException ex) {
            ex.printStackTrace();
            unlockStores();
            throw new MPTException(ERROR_COLOR + "Failed to write package store to disk!");
        }
        unlockStores();
        if (!success)
            throw new MPTException(
                    ERROR_COLOR + "Some files were not extracted. Use verbose logging for details.");
    } catch (IOException ex) {
        throw new MPTException(ERROR_COLOR + "Failed to access archive!");
    }
}

From source file:com.liferay.mobile.sdk.core.tests.MobileSDKCoreTests.java

private void checkJarPaths(File jar, String[] paths) throws Exception {
    assertTrue(jar.exists());/*w w  w  . jav a2  s  . c o m*/

    final ZipFile jarFile = new ZipFile(jar);

    for (String path : paths) {
        ZipEntry entry = jarFile.getEntry(path);

        assertNotNull(entry);
    }

    jarFile.close();
}

From source file:com.dreikraft.axbo.sound.SoundPackageUtil.java

/**
 * retrieves an entry from the package file (ZIP file)
 *
 * @param packageFile the sound package file
 * @param entryName the name of the entry in the ZIP file
 * @throws com.dreikraft.infactory.sound.SoundPackageException encapsulates
 * all low level (IO) exceptions/*from  ww w. j a  va2s . com*/
 * @return the entry data as stream
 */
public static InputStream getPackageEntryStream(File packageFile, String entryName)
        throws SoundPackageException {
    if (packageFile == null) {
        throw new SoundPackageException(new IllegalArgumentException("missing package file"));
    }

    InputStream keyIn = null;
    try {
        ZipFile packageZip = new ZipFile(packageFile);

        // get key from package
        ZipEntry keyEntry = packageZip.getEntry(LICENSE_KEY_ENTRY);
        keyIn = packageZip.getInputStream(keyEntry);
        Key key = CryptoUtil.unwrapKey(keyIn, PUBLIC_KEY_FILE);

        // read entry
        ZipEntry entry = packageZip.getEntry(entryName);
        return new ZipClosingInputStream(packageZip,
                CryptoUtil.decryptInput(packageZip.getInputStream(entry), key));
    } catch (ZipException ex) {
        throw new SoundPackageException(ex);
    } catch (IOException ex) {
        throw new SoundPackageException(ex);
    } catch (CryptoException ex) {
        throw new SoundPackageException(ex);
    } finally {
        try {
            if (keyIn != null) {
                keyIn.close();
            }
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
    }
}

From source file:com.google.appinventor.buildserver.util.AARLibrary.java

/**
 * Unpacks the Android Archive to a directory in the file system. The unpacking operation will
 * create a new directory named with the archive's package name to prevent collisions with
 * other Android Archives./* ww  w  . j  a va  2s  . c  o  m*/
 * @param path the path to where the archive will be unpacked.
 * @throws IOException if any error occurs attempting to read the archive or write new files to
 *                     the file system.
 */
public void unpackToDirectory(final File path) throws IOException {
    ZipFile zip = null;
    try {
        zip = new ZipFile(aarPath);
        packageName = extractPackageName(zip);
        basedir = new File(path, packageName);
        if (!basedir.mkdirs()) {
            throw new IOException("Unable to create directory for AAR package");
        }
        InputStream input = null;
        OutputStream output = null;
        Enumeration<? extends ZipEntry> i = zip.entries();
        while (i.hasMoreElements()) {
            ZipEntry entry = i.nextElement();
            File target = new File(basedir, entry.getName());
            if (entry.isDirectory() && !target.exists() && !target.mkdirs()) {
                throw new IOException("Unable to create directory " + path.getAbsolutePath());
            } else if (!entry.isDirectory()) {
                try {
                    output = new FileOutputStream(target);
                    input = zip.getInputStream(entry);
                    IOUtils.copy(input, output);
                } finally {
                    IOUtils.closeQuietly(input);
                    IOUtils.closeQuietly(output);
                }
                catalog(target);
            }
        }
        resdir = new File(basedir, "res");
        if (!resdir.exists()) {
            resdir = null;
        }
    } finally {
        IOUtils.closeQuietly(zip);
    }
}