Search in sources :

Example 11 with ZipOutputStream

use of java.util.zip.ZipOutputStream in project android_frameworks_base by ParanoidAndroid.

the class PackageHelper method extractPublicFiles.

public static int extractPublicFiles(String packagePath, File publicZipFile) throws IOException {
    final FileOutputStream fstr;
    final ZipOutputStream publicZipOutStream;
    if (publicZipFile == null) {
        fstr = null;
        publicZipOutStream = null;
    } else {
        fstr = new FileOutputStream(publicZipFile);
        publicZipOutStream = new ZipOutputStream(fstr);
    }
    int size = 0;
    try {
        final ZipFile privateZip = new ZipFile(packagePath);
        try {
            // Copy manifest, resources.arsc and res directory to public zip
            for (final ZipEntry zipEntry : Collections.list(privateZip.entries())) {
                final String zipEntryName = zipEntry.getName();
                if ("AndroidManifest.xml".equals(zipEntryName) || "resources.arsc".equals(zipEntryName) || zipEntryName.startsWith("res/")) {
                    size += zipEntry.getSize();
                    if (publicZipFile != null) {
                        copyZipEntry(zipEntry, privateZip, publicZipOutStream);
                    }
                }
            }
        } finally {
            try {
                privateZip.close();
            } catch (IOException e) {
            }
        }
        if (publicZipFile != null) {
            publicZipOutStream.finish();
            publicZipOutStream.flush();
            FileUtils.sync(fstr);
            publicZipOutStream.close();
            FileUtils.setPermissions(publicZipFile.getAbsolutePath(), FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP | FileUtils.S_IROTH, -1, -1);
        }
    } finally {
        IoUtils.closeQuietly(publicZipOutStream);
    }
    return size;
}
Also used : ZipFile(java.util.zip.ZipFile) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) ZipEntry(java.util.zip.ZipEntry) IOException(java.io.IOException)

Example 12 with ZipOutputStream

use of java.util.zip.ZipOutputStream in project OpenRefine by OpenRefine.

the class ProjectUtilities method saveToFile.

protected static void saveToFile(Project project, File file) throws IOException {
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
    try {
        Pool pool = new Pool();
        out.putNextEntry(new ZipEntry("data.txt"));
        try {
            project.saveToOutputStream(out, pool);
        } finally {
            out.closeEntry();
        }
        out.putNextEntry(new ZipEntry("pool.txt"));
        try {
            pool.save(out);
        } finally {
            out.closeEntry();
        }
    } finally {
        out.close();
    }
}
Also used : ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) ZipEntry(java.util.zip.ZipEntry) Pool(com.google.refine.util.Pool)

Example 13 with ZipOutputStream

use of java.util.zip.ZipOutputStream in project android_frameworks_base by ParanoidAndroid.

the class FileRotator method dumpAll.

/**
     * Dump all files managed by this rotator for debugging purposes.
     */
public void dumpAll(OutputStream os) throws IOException {
    final ZipOutputStream zos = new ZipOutputStream(os);
    try {
        final FileInfo info = new FileInfo(mPrefix);
        for (String name : mBasePath.list()) {
            if (info.parse(name)) {
                final ZipEntry entry = new ZipEntry(name);
                zos.putNextEntry(entry);
                final File file = new File(mBasePath, name);
                final FileInputStream is = new FileInputStream(file);
                try {
                    Streams.copy(is, zos);
                } finally {
                    IoUtils.closeQuietly(is);
                }
                zos.closeEntry();
            }
        }
    } finally {
        IoUtils.closeQuietly(zos);
    }
}
Also used : ZipOutputStream(java.util.zip.ZipOutputStream) ZipEntry(java.util.zip.ZipEntry) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 14 with ZipOutputStream

use of java.util.zip.ZipOutputStream in project Anki-Android by Ramblurr.

the class Connection method doInBackgroundUpgradeDecks.

private Payload doInBackgroundUpgradeDecks(Payload data) {
    // Enable http request canceller
    mCancelCallback = new CancelCallback();
    String path = (String) data.data[0];
    File ankiDir = new File(path);
    if (!ankiDir.isDirectory()) {
        data.success = false;
        data.data = new Object[] { "wrong anki directory" };
        return data;
    }
    // step 1: gather all .anki files into a zip, without media.
    // we must store them as 1.anki, 2.anki and provide a map so we don't run into
    // encoding issues with the zip file.
    File[] fileList = ankiDir.listFiles(new OldAnkiDeckFilter());
    List<String> corruptFiles = new ArrayList<String>();
    JSONObject map = new JSONObject();
    byte[] buf = new byte[1024];
    String zipFilename = path + "/upload.zip";
    String colFilename = path + AnkiDroidApp.COLLECTION_PATH;
    try {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilename));
        int n = 1;
        for (File f : fileList) {
            String deckPath = f.getAbsolutePath();
            // set journal mode to delete
            try {
                AnkiDb d = AnkiDatabaseManager.getDatabase(deckPath);
            } catch (SQLiteDatabaseCorruptException e) {
                // ignore invalid .anki files
                corruptFiles.add(f.getName());
                continue;
            } finally {
                AnkiDatabaseManager.closeDatabase(deckPath);
            }
            // zip file
            String tmpName = n + ".anki";
            FileInputStream in = new FileInputStream(deckPath);
            ZipEntry ze = new ZipEntry(tmpName);
            zos.putNextEntry(ze);
            int len;
            while ((len = in.read(buf)) >= 0) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            map.put(tmpName, f.getName());
            n++;
        }
        // if all .anki files were found corrupted, abort
        if (fileList.length == corruptFiles.size()) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
            return data;
        }
        ZipEntry ze = new ZipEntry("map.json");
        zos.putNextEntry(ze);
        InputStream in = new ByteArrayInputStream(Utils.jsonToString(map).getBytes("UTF-8"));
        int len;
        while ((len = in.read(buf)) >= 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        zos.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    File zipFile = new File(zipFilename);
    // step 1.1: if it's over 50MB compressed, it must be upgraded by the user
    if (zipFile.length() > 50 * 1024 * 1024) {
        data.success = false;
        data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_exceeds) };
        return data;
    }
    // step 2: upload zip file to upgrade service and get token
    BasicHttpSyncer h = new BasicHttpSyncer(null, null);
    // note: server doesn't expect it to be gzip compressed, because the zip file is compressed
    // enable cancelling
    publishProgress(R.string.upgrade_decks_upload, null, true);
    try {
        HttpResponse resp = h.req("upgrade/upload", new FileInputStream(zipFile), 0, false, null, mCancelCallback);
        if (resp == null && !isCancelled()) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
            return data;
        }
        String result;
        String key = null;
        if (!isCancelled()) {
            result = h.stream2String(resp.getEntity().getContent());
            if (result != null && result.startsWith("ok:")) {
                key = result.split(":")[1];
            } else {
                data.success = false;
                data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
                return data;
            }
        }
        while (!isCancelled()) {
            result = h.stream2String(h.req("upgrade/status?key=" + key).getEntity().getContent());
            if (result.equals("error")) {
                data.success = false;
                data.data = new Object[] { "error" };
                return data;
            } else if (result.startsWith("waiting:")) {
                publishProgress(R.string.upgrade_decks_upload, result.split(":")[1]);
            } else if (result.equals("upgrading")) {
                publishProgress(new Object[] { R.string.upgrade_decks_upgrade_started });
            } else if (result.equals("ready")) {
                break;
            } else {
                data.success = false;
                data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
                return data;
            }
            Thread.sleep(1000);
        }
        // gzip compression if the client says it can handle it
        if (!isCancelled()) {
            publishProgress(new Object[] { R.string.upgrade_decks_downloading });
            resp = h.req("upgrade/download?key=" + key, null, 6, true, null, mCancelCallback);
        // uploads/downloads have finished so disable cancelling
        }
        publishProgress(R.string.upgrade_decks_downloading, null, false);
        if (isCancelled()) {
            return null;
        }
        if (resp == null) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_failed) };
            return data;
        }
        // step 5: check the received file is valid
        InputStream cont = resp.getEntity().getContent();
        if (!h.writeToFile(cont, colFilename)) {
            data.success = false;
            data.data = new Object[] { sContext.getString(R.string.upgrade_deck_web_upgrade_sdcard, new File(colFilename).length() / 1048576 + 1) };
            (new File(colFilename)).delete();
            return data;
        }
        // check the received file is ok
        publishProgress(new Object[] { R.string.sync_check_download_file });
        publishProgress(R.string.sync_check_download_file);
        try {
            AnkiDb d = AnkiDatabaseManager.getDatabase(colFilename);
            if (!d.queryString("PRAGMA integrity_check").equalsIgnoreCase("ok")) {
                data.success = false;
                data.data = new Object[] { sContext.getResources() };
                return data;
            }
        } finally {
            AnkiDatabaseManager.closeDatabase(colFilename);
        }
        Collection col = AnkiDroidApp.openCollection(colFilename);
        ArrayList<String> decks = col.getDecks().allNames(false);
        ArrayList<String> failed = new ArrayList<String>();
        ArrayList<File> mediaDirs = new ArrayList<File>();
        for (File f : fileList) {
            String name = f.getName().replaceFirst("\\.anki$", "");
            if (!decks.contains(name)) {
                failed.add(name);
            } else {
                mediaDirs.add(new File(f.getAbsolutePath().replaceFirst("\\.anki$", ".media")));
            }
        }
        File newMediaDir = new File(col.getMedia().getDir());
        // step 6. move media files to new media directory
        publishProgress(new Object[] { R.string.upgrade_decks_media });
        ArrayList<String> failedMedia = new ArrayList<String>();
        File curMediaDir = null;
        for (File mediaDir : mediaDirs) {
            curMediaDir = mediaDir;
            // Check if media directory exists and is local
            if (!curMediaDir.exists() || !curMediaDir.isDirectory()) {
                // If not try finding it in dropbox 1.2.x
                curMediaDir = new File(AnkiDroidApp.getDropboxDir(), mediaDir.getName());
                if (!curMediaDir.exists() || !curMediaDir.isDirectory()) {
                    // No media for this deck
                    continue;
                }
            }
            // Found media dir, copy files
            for (File m : curMediaDir.listFiles()) {
                try {
                    Utils.copyFile(m, new File(newMediaDir, m.getName()));
                } catch (IOException e) {
                    failedMedia.add(curMediaDir.getName().replaceFirst("\\.media$", ".anki"));
                    break;
                }
            }
        }
        data.data = new Object[] { failed, failedMedia, newMediaDir.getAbsolutePath() };
        data.success = true;
        return data;
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        (new File(zipFilename)).delete();
    }
}
Also used : ZipEntry(java.util.zip.ZipEntry) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) SQLiteDatabaseCorruptException(android.database.sqlite.SQLiteDatabaseCorruptException) AnkiDb(com.ichi2.anki.AnkiDb) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JSONException(org.json.JSONException) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) BasicHttpSyncer(com.ichi2.libanki.sync.BasicHttpSyncer) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) Collection(com.ichi2.libanki.Collection) JSONObject(org.json.JSONObject) File(java.io.File)

Example 15 with ZipOutputStream

use of java.util.zip.ZipOutputStream in project Anki-Android by Ramblurr.

the class DeckTask method doInBackgroundExportApkg.

private TaskData doInBackgroundExportApkg(TaskData... params) {
    Log.i(AnkiDroidApp.TAG, "doInBackgroundExportApkg");
    Object[] data = params[0].getObjArray();
    String colPath = (String) data[0];
    String apkgPath = (String) data[1];
    boolean includeMedia = (Boolean) data[2];
    byte[] buf = new byte[1024];
    try {
        try {
            AnkiDb d = AnkiDatabaseManager.getDatabase(colPath);
        } catch (SQLiteDatabaseCorruptException e) {
            // collection is invalid
            return new TaskData(false);
        } finally {
            AnkiDatabaseManager.closeDatabase(colPath);
        }
        // export collection
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(apkgPath));
        FileInputStream colFin = new FileInputStream(colPath);
        ZipEntry ze = new ZipEntry("collection.anki2");
        zos.putNextEntry(ze);
        int len;
        while ((len = colFin.read(buf)) >= 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        colFin.close();
        // export media
        JSONObject media = new JSONObject();
        if (includeMedia) {
            File mediaDir = new File(AnkiDroidApp.getCurrentAnkiDroidMediaDir());
            if (mediaDir.exists() && mediaDir.isDirectory()) {
                File[] mediaFiles = mediaDir.listFiles();
                int c = 0;
                for (File f : mediaFiles) {
                    FileInputStream mediaFin = new FileInputStream(f);
                    ze = new ZipEntry(Integer.toString(c));
                    zos.putNextEntry(ze);
                    while ((len = mediaFin.read(buf)) >= 0) {
                        zos.write(buf, 0, len);
                    }
                    zos.closeEntry();
                    media.put(Integer.toString(c), f.getName());
                }
            }
        }
        ze = new ZipEntry("media");
        zos.putNextEntry(ze);
        InputStream mediaIn = new ByteArrayInputStream(Utils.jsonToString(media).getBytes("UTF-8"));
        while ((len = mediaIn.read(buf)) >= 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        zos.close();
    } catch (FileNotFoundException e) {
        return new TaskData(false);
    } catch (IOException e) {
        return new TaskData(false);
    } catch (JSONException e) {
        return new TaskData(false);
    }
    return new TaskData(true);
}
Also used : AnkiDb(com.ichi2.anki.AnkiDb) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) FileNotFoundException(java.io.FileNotFoundException) SQLiteDatabaseCorruptException(android.database.sqlite.SQLiteDatabaseCorruptException) JSONException(org.json.JSONException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) JSONObject(org.json.JSONObject) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Aggregations

ZipOutputStream (java.util.zip.ZipOutputStream)463 ZipEntry (java.util.zip.ZipEntry)308 FileOutputStream (java.io.FileOutputStream)216 File (java.io.File)181 IOException (java.io.IOException)118 ZipFile (java.util.zip.ZipFile)104 BufferedOutputStream (java.io.BufferedOutputStream)90 ByteArrayOutputStream (java.io.ByteArrayOutputStream)83 FileInputStream (java.io.FileInputStream)82 Test (org.junit.Test)68 InputStream (java.io.InputStream)61 ZipInputStream (java.util.zip.ZipInputStream)44 ByteArrayInputStream (java.io.ByteArrayInputStream)39 BufferedInputStream (java.io.BufferedInputStream)28 OutputStream (java.io.OutputStream)26 Path (java.nio.file.Path)22 ArrayList (java.util.ArrayList)19 FileNotFoundException (java.io.FileNotFoundException)18 HashMap (java.util.HashMap)17 CRC32 (java.util.zip.CRC32)13