Extract a valid model from a zip

@param $type
@param $zipFile
@return mixed
@throws PortableElementInconsistencyModelException
428921
public function getValidPortableElementFromZipSource($type, $zipFile)
    {
        /** @var PortableElementPackageParser $parser */
        $parser = $this->getPortableModelRegistry()->getModel($type)->getPackageParser();
        $source = $parser->extract($zipFile);
        $object = $parser->getModel()->createDataObject($parser->getManifestContent($zipFile));
        $this->validate($object, $source);

        return $object;
    }
365383
public static boolean isZipFile(File zipFile) {
    try {
      ZipFile zf = new ZipFile(zipFile);
      boolean isZip = zf.getEntries().hasMoreElements();
      zf.close();
      return isZip;
    } catch (IOException e) {
      return false;
    }
  }
809067
public static void extractFile(File zipFile,
                                   String entryName,
                                   File destination) throws IOException {
        ZipFile zip = new ZipFile(zipFile);

        try {
            ZipEntry entry = zip.getEntry(entryName);

            if (entry != null) {
                // Get an input stream for the entry.
                InputStream entryStream = zip.getInputStream(entry);
                try {
                    // Create the output file
                    File parent = destination.getParentFile();
                    if (parent != null) {
                        parent.mkdirs();
                    }

                    FileOutputStream file = new FileOutputStream(destination);

                    try {
                        // Allocate a buffer for reading the entry data.
                        byte[] data = new byte[BUFFER];
                        int bytesRead;

                        // Read the entry data and write it to the output file.
                        while ((bytesRead = entryStream.read(data)) != -1) {
                            file.write(data, 0, bytesRead);
                        }
                    } finally {
                        file.close();
                    }
                } finally {
                    entryStream.close();
                }
            } else {
                throw new IOException(zipFile.getName() + " does not contain: "
                        + entryName);
            }
        } finally {
            zip.close();
        }
    }
364790
protected function unzipPHP($zipFile, $destinationDirectory, array $options)
    {
        if (!class_exists('ZipArchive')) {
            throw new Exception('Unable to unzip files using ZipArchive. Please ensure the Zip extension is installed.');
        }
        $zip = new ZipArchive();
        try {
            $flags = 0;
            if (!$options['skipCheck']) {
                $flags |= ZipArchive::CHECKCONS;
            }
            $zipErr = @$zip->open($zipFile, $flags);
            if ($zipErr !== true) {
                throw new Exception($this->describeZipArchiveError($zip, $zipErr));
            }
            if (@$zip->extractTo($destinationDirectory) !== true) {
                throw new Exception($this->describeZipArchiveError($zip, ZipArchive::ER_OK));
            }
            @$zip->close();
            $zip = null;
        } catch (Exception $x) {
            if ($zip !== null) {
                try {
                    @$zip->close();
                } catch (\Exception $foo) {
                }
                $zip = null;
            }
            throw $x;
        }
    }
1260935
public function extractTo($destination, $entities = null)
    {
        if ($entities) {
            return $this->zipArchive->extractTo($destination, $entities);
        } else {
            return $this->zipArchive->extractTo($destination);
        }
    }
1298823
def get_zip_class():
    
    class ContextualZipFile(zipfile.ZipFile):
        def __enter__(self):
            return self
        def __exit__(self, type, value, traceback):
            self.close
    return zipfile.ZipFile if hasattr(zipfile.ZipFile, '__exit__') else \
        ContextualZipFile
310202
public function extract_import_contents(string $zipfilepath) : array {

        $importtempdir = make_request_directory('analyticsimport' . microtime(false));

        $zip = new \zip_packer();
        $filelist = $zip->extract_to_pathname($zipfilepath, $importtempdir);

        if (empty($filelist[self::CONFIG_FILE_NAME])) {
            // Missing required file.
            throw new \moodle_exception('errorimport', 'analytics');
        }

        $jsonmodeldata = file_get_contents($importtempdir . DIRECTORY_SEPARATOR . self::CONFIG_FILE_NAME);

        if (!$modeldata = json_decode($jsonmodeldata)) {
            throw new \moodle_exception('errorimport', 'analytics');
        }

        if (empty($modeldata->target) || empty($modeldata->timesplitting) || empty($modeldata->indicators)) {
            throw new \moodle_exception('errorimport', 'analytics');
        }

        $mlbackenddir = $importtempdir . DIRECTORY_SEPARATOR . 'mlbackend';
        if (!is_dir($mlbackenddir)) {
            $mlbackenddir = false;
        }

        return [$modeldata, $mlbackenddir];
    }
702421
def extract_csv(zip_path, destination):
    
    with zipfile.ZipFile(zip_path) as zf:
        member_to_unzip = None
        for member in zf.namelist():
            if member.endswith('.csv'):
                member_to_unzip = member
                break

        if not member_to_unzip:
            raise LookupError(
                "Couldn't find any CSV file in the archive"
            )

        with zf.open(member_to_unzip) as zfp, \
                open(destination, 'wb') as dfp:
            dfp.write(zfp.read())
791132
public static void extract(final File zipfile, final File outdir) {
        try {
            ZipInputStream zin = new ZipInputStream(new FileInputStream(zipfile));
            ZipEntry entry;
            String name, dir;
            while ((entry = zin.getNextEntry()) != null) {
                name = entry.getName();
                if (entry.isDirectory()) {
                    mkdirs(outdir, name);
                    continue;
                }

                dir = dirpart(name);
                if (dir != null) {
                    mkdirs(outdir, dir);
                }

                extractFile(zin, outdir, name);
            }
            zin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
278086
final public static function zipWith()
    {
        $xss = func_get_args();
        $f = array_pop($xss);
        $zipped = static::unzip($xss);
        return static::map($zipped, function($xs, $i, $xss) use ($f) {
            return call_user_func_array($f, $xs);
        });
    }
861258
public static void unzip(InputStream zipFile, String dest) throws IOException {
        byte[] buffer = new byte[1024];

        //create output directory is not exists
        File folder = new File(dest);

        if (folder.exists()) {
            FileUtil.delete(folder);
        }

        folder.mkdir();

        //get the zip file content
        try (ZipInputStream zis = new ZipInputStream(zipFile)) {
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();
            File parent = new File(dest);
            while (ze != null) {
                String fileName = ze.getName();
                if (ze.isDirectory()) {
                    File newFolder = new File(parent, fileName);
                    newFolder.mkdir();
                } else {
                    File newFile = new File(parent, fileName);
                    try (FileOutputStream fos = new FileOutputStream(newFile)) {
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                ze = zis.getNextEntry();
            }

            zis.closeEntry();
        }
    }
413637
public function extractZipTo($filepath, $destination)
    {
        $chapterZip = new \ZipArchive ();

        if ($chapterZip->open($filepath)) {
            $chapterZip->extractTo($destination);
            $chapterZip->close();
        }
    }
731941
public static void extractZipEntry(final ZipFile zipFile, final ZipEntry target,
		final File toDirectory) throws IOException
	{
		final File fileToExtract = new File(toDirectory, target.getName());
		new File(fileToExtract.getParent()).mkdirs();

		try (InputStream is = zipFile.getInputStream(target);
			BufferedInputStream bis = new BufferedInputStream(is);
			FileOutputStream fos = new FileOutputStream(fileToExtract);
			BufferedOutputStream bos = new BufferedOutputStream(fos))
		{
			for (int c; (c = bis.read()) != -1;)
			{
				bos.write((byte)c);
			}
			bos.flush();
		}
		catch (final IOException e)
		{
			throw e;
		}
	}
182865
public void instrumentZipFile(File zf) throws IOException {
        if (!zf.canRead() || !zf.canWrite()) {
            throw new IOException(zf + " can not be replaced");
        }

        File tempFile = File.createTempFile(zf.getName(), null, zf.getParentFile());
        if (tempFile.exists() && !tempFile.delete()) {
            throw new IOException("Unable to delete existing temp file " + tempFile.getName());
        }
        if (!zf.renameTo(tempFile)) {
            throw new IOException("Unable to rename existing jar " + zf);
        }

        ZipFile zipFile = new ZipFile(tempFile);
        FileOutputStream fos = new FileOutputStream(zf);
        ZipOutputStream zos = new ZipOutputStream(fos);
        boolean restoreZipFile = false;
        try {
            byte[] buffer = new byte[8192];
            Enumeration<? extends ZipEntry> e = zipFile.entries();
            while (e.hasMoreElements()) {
                ZipEntry oldEntry = e.nextElement();
                InputStream zis = zipFile.getInputStream(oldEntry);
                byte[] transformedClass = null;

                if (oldEntry.getName().endsWith(".class")) {
                    transformedClass = transform(zis);
                    if (transformedClass == null) {
                        zis = zipFile.getInputStream(oldEntry);
                    }
                }

                ZipEntry newEntry = new ZipEntry(oldEntry.getName());
                newEntry.setTime(transformedClass == null ? oldEntry.getTime() : System.currentTimeMillis());
                newEntry.setComment(oldEntry.getComment());
                newEntry.setExtra(oldEntry.getExtra());
                newEntry.setSize(transformedClass == null ? oldEntry.getSize() : transformedClass.length);

                if (newEntry.getSize() > Integer.MAX_VALUE) {
                    throw new IOException("ZipEntry too large: " + newEntry.getSize());
                }

                int entrySize = (int) newEntry.getSize();
                if (entrySize > buffer.length) {
                    buffer = new byte[entrySize];
                }

                if (transformedClass != null) {
                    System.arraycopy(transformedClass, 0, buffer, 0, entrySize);
                } else {
                    int totalBytesRead = 0;
                    while (totalBytesRead < entrySize) {
                        int bytesRead = zis.read(buffer, totalBytesRead, entrySize - totalBytesRead);
                        if (bytesRead == -1) {
                            throw new IOException("End of file encountered");
                        }
                        totalBytesRead += bytesRead;
                    }
                }

                zos.putNextEntry(newEntry);
                zos.write(buffer, 0, entrySize);
            }
        } catch (IOException ioe) {
            restoreZipFile = true;
            throw ioe;
        } catch (Throwable t) {
            restoreZipFile = true;
            IOException ioe = new IOException("Unexpected exception encountered during instrumentation");
            ioe.initCause(t);
            throw ioe;
        } finally {
            zos.close();
            fos.close();
            zipFile.close();
            if (restoreZipFile) {
                zf.delete();
                tempFile.renameTo(zf);
            } else {
                tempFile.delete();
            }
        }
    }
565139
public function extractZipFile($container, $path, $zip, $clean = false, $drop_path = '')
    {
        if ($clean) {
            try {
                // clear out anything in this directory
                $blobs = $this->listBlobs($container, $path);
                if (!empty($blobs)) {
                    foreach ($blobs as $blob) {
                        if ((0 !== strcasecmp($path, $blob['name']))) { // not folder itself
                            $this->deleteBlob($container, $blob['name']);
                        }
                    }
                }
            } catch (\Exception $ex) {
                throw new InternalServerErrorException("Could not clean out existing directory $path.\n{$ex->getMessage()}");
            }
        }
        for ($i = 0; $i < $zip->numFiles; $i++) {
            try {
                $name = $zip->getNameIndex($i);
                if (empty($name)) {
                    continue;
                }
                if (!empty($drop_path)) {
                    $name = str_ireplace($drop_path, '', $name);
                }
                $fullPathName = $path . $name;
                if ('/' === substr($fullPathName, -1)) {
                    $this->createFolder($container, $fullPathName, true, [], false);
                } else {
                    $parent = FileUtilities::getParentFolder($fullPathName);
                    if (!empty($parent)) {
                        $this->createFolder($container, $parent, true, [], false);
                    }
                    $content = $zip->getFromIndex($i);
                    $this->writeFile($container, $fullPathName, $content);
                }
            } catch (\Exception $ex) {
                throw $ex;
            }
        }

        return ['name' => rtrim($path, DIRECTORY_SEPARATOR), 'path' => $path];
    }
1219968
public static function unzip($file, $destination) {
		if (!file_exists($file)) {
			return false;
		}

		if (!file_exists($destination)) {
			mkdir($destination);
		}

		if (class_exists('ZipArchive')) {
			$result = static::unzip_using_ziparchive($file, $destination);
			if ($result === true) {
				return true;
			}
		} else {
			throw new \Exception('No zip support available', 500);
		}
	}
21787
def unzip(source_file, destination_dir):
    
    with zipfile.ZipFile(source_file) as zf:
        zf.extractall(destination_dir)