Search in sources :

Example 56 with ZipException

use of java.util.zip.ZipException in project Glowstone by GlowstoneMC.

the class RegionFile method getChunkDataInputStream.

/**
 * Gets an (uncompressed) stream representing the chunk data. Returns null if the chunk is not
 * found or an error occurs.
 *
 * @param x the chunk X coordinate relative to the region
 * @param z the chunk Z coordinate relative to the region
 * @return an input stream with the chunk data, or null if the chunk is missing
 * @throws IOException if the file cannot be read, or the chunk is invalid
 */
public DataInputStream getChunkDataInputStream(int x, int z) throws IOException {
    checkBounds(x, z);
    int offset = getOffset(x, z);
    if (offset == 0) {
        // does not exist
        return null;
    }
    int totalSectors = sectorsUsed.length();
    int sectorNumber = offset >> 8;
    int numSectors = offset & 0xFF;
    if (sectorNumber + numSectors > totalSectors) {
        throw new IOException("Invalid sector: " + sectorNumber + "+" + numSectors + " > " + totalSectors);
    }
    file.seek(sectorNumber * SECTOR_BYTES);
    int length = file.readInt();
    if (length > SECTOR_BYTES * numSectors) {
        throw new IOException("Invalid length: " + length + " > " + SECTOR_BYTES * numSectors);
    } else if (length <= 0) {
        throw new IOException("Invalid length: " + length + " <= 0 ");
    }
    byte version = file.readByte();
    if (version == VERSION_GZIP) {
        byte[] data = new byte[length - 1];
        file.read(data);
        try {
            return new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data), 2048)));
        } catch (ZipException e) {
            if (e.getMessage().equals("Not in GZIP format")) {
                GlowServer.logger.info("Incorrect region version, switching to zlib...");
                file.seek((sectorNumber * SECTOR_BYTES) + Integer.BYTES);
                file.write(VERSION_DEFLATE);
                return getZlibInputStream(data);
            }
        }
    } else if (version == VERSION_DEFLATE) {
        byte[] data = new byte[length - 1];
        file.read(data);
        return getZlibInputStream(data);
    }
    throw new IOException("Unknown version: " + version);
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream)

Example 57 with ZipException

use of java.util.zip.ZipException in project bytecode-viewer by Konloch.

the class ProcyonDecompiler method doSaveJarDecompiled.

/**
 * @author DeathMarine
 */
private void doSaveJarDecompiled(File inFile, File outFile) throws Exception {
    try (JarFile jfile = new JarFile(inFile);
        FileOutputStream dest = new FileOutputStream(outFile);
        BufferedOutputStream buffDest = new BufferedOutputStream(dest);
        ZipOutputStream out = new ZipOutputStream(buffDest)) {
        byte[] data = new byte[1024];
        DecompilerSettings settings = getDecompilerSettings();
        LuytenTypeLoader typeLoader = new LuytenTypeLoader();
        MetadataSystem metadataSystem = new MetadataSystem(typeLoader);
        ITypeLoader jarLoader = new JarTypeLoader(jfile);
        typeLoader.getTypeLoaders().add(jarLoader);
        DecompilationOptions decompilationOptions = new DecompilationOptions();
        decompilationOptions.setSettings(settings);
        decompilationOptions.setFullDecompilation(true);
        Enumeration<JarEntry> ent = jfile.entries();
        Set<JarEntry> history = new HashSet<>();
        while (ent.hasMoreElements()) {
            JarEntry entry = ent.nextElement();
            if (entry.getName().endsWith(".class")) {
                JarEntry etn = new JarEntry(entry.getName().replace(".class", ".java"));
                if (history.add(etn)) {
                    out.putNextEntry(etn);
                    try {
                        String internalName = StringUtilities.removeRight(entry.getName(), ".class");
                        TypeReference type = metadataSystem.lookupType(internalName);
                        TypeDefinition resolvedType;
                        if ((type == null) || ((resolvedType = type.resolve()) == null)) {
                            throw new Exception("Unable to resolve type.");
                        }
                        Writer writer = new OutputStreamWriter(out);
                        settings.getLanguage().decompileType(resolvedType, new PlainTextOutput(writer), decompilationOptions);
                        writer.flush();
                    } finally {
                        out.closeEntry();
                    }
                }
            } else {
                try {
                    JarEntry etn = new JarEntry(entry.getName());
                    if (history.add(etn))
                        continue;
                    history.add(etn);
                    out.putNextEntry(etn);
                    try (InputStream in = jfile.getInputStream(entry)) {
                        if (in != null) {
                            int count;
                            while ((count = in.read(data, 0, 1024)) != -1) {
                                out.write(data, 0, count);
                            }
                        }
                    } finally {
                        out.closeEntry();
                    }
                } catch (ZipException ze) {
                    // some jars contain duplicate pom.xml entries: ignore it
                    if (!ze.getMessage().contains("duplicate")) {
                        throw ze;
                    }
                }
            }
        }
    }
}
Also used : PlainTextOutput(com.strobel.decompiler.PlainTextOutput) JarTypeLoader(com.strobel.assembler.metadata.JarTypeLoader) TypeDefinition(com.strobel.assembler.metadata.TypeDefinition) TypeReference(com.strobel.assembler.metadata.TypeReference) BufferedOutputStream(java.io.BufferedOutputStream) HashSet(java.util.HashSet) DecompilationOptions(com.strobel.decompiler.DecompilationOptions) InputStream(java.io.InputStream) ZipException(java.util.zip.ZipException) JarFile(java.util.jar.JarFile) MetadataSystem(com.strobel.assembler.metadata.MetadataSystem) JarEntry(java.util.jar.JarEntry) ITypeLoader(com.strobel.assembler.metadata.ITypeLoader) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) DecompilerSettings(com.strobel.decompiler.DecompilerSettings) OutputStreamWriter(java.io.OutputStreamWriter) OutputStreamWriter(java.io.OutputStreamWriter) PrintWriter(java.io.PrintWriter) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 58 with ZipException

use of java.util.zip.ZipException in project Conversations by siacs.

the class ImportBackupService method importBackup.

private boolean importBackup(final Uri uri, final String password) {
    Log.d(Config.LOGTAG, "importing backup from " + uri);
    final Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        final SQLiteDatabase db = mDatabaseBackend.getWritableDatabase();
        final InputStream inputStream;
        final String path = uri.getPath();
        final long fileSize;
        if ("file".equals(uri.getScheme()) && path != null) {
            final File file = new File(path);
            inputStream = new FileInputStream(file);
            fileSize = file.length();
        } else {
            final Cursor returnCursor = getContentResolver().query(uri, null, null, null, null);
            if (returnCursor == null) {
                fileSize = 0;
            } else {
                returnCursor.moveToFirst();
                fileSize = returnCursor.getLong(returnCursor.getColumnIndex(OpenableColumns.SIZE));
                returnCursor.close();
            }
            inputStream = getContentResolver().openInputStream(uri);
        }
        if (inputStream == null) {
            synchronized (mOnBackupProcessedListeners) {
                for (final OnBackupProcessed l : mOnBackupProcessedListeners) {
                    l.onBackupRestoreFailed();
                }
            }
            return false;
        }
        final CountingInputStream countingInputStream = new CountingInputStream(inputStream);
        final DataInputStream dataInputStream = new DataInputStream(countingInputStream);
        final BackupFileHeader backupFileHeader = BackupFileHeader.read(dataInputStream);
        Log.d(Config.LOGTAG, backupFileHeader.toString());
        if (mDatabaseBackend.getAccountJids(false).contains(backupFileHeader.getJid())) {
            synchronized (mOnBackupProcessedListeners) {
                for (OnBackupProcessed l : mOnBackupProcessedListeners) {
                    l.onAccountAlreadySetup();
                }
            }
            return false;
        }
        final byte[] key = ExportBackupService.getKey(password, backupFileHeader.getSalt());
        final AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
        cipher.init(false, new AEADParameters(new KeyParameter(key), 128, backupFileHeader.getIv()));
        final CipherInputStream cipherInputStream = new CipherInputStream(countingInputStream, cipher);
        final GZIPInputStream gzipInputStream = new GZIPInputStream(cipherInputStream);
        final BufferedReader reader = new BufferedReader(new InputStreamReader(gzipInputStream, Charsets.UTF_8));
        db.beginTransaction();
        String line;
        StringBuilder multiLineQuery = null;
        while ((line = reader.readLine()) != null) {
            int count = count(line, '\'');
            if (multiLineQuery != null) {
                multiLineQuery.append('\n');
                multiLineQuery.append(line);
                if (count % 2 == 1) {
                    db.execSQL(multiLineQuery.toString());
                    multiLineQuery = null;
                    updateImportBackupNotification(fileSize, countingInputStream.getCount());
                }
            } else {
                if (count % 2 == 0) {
                    db.execSQL(line);
                    updateImportBackupNotification(fileSize, countingInputStream.getCount());
                } else {
                    multiLineQuery = new StringBuilder(line);
                }
            }
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        final Jid jid = backupFileHeader.getJid();
        final Cursor countCursor = db.rawQuery("select count(messages.uuid) from messages join conversations on conversations.uuid=messages.conversationUuid join accounts on conversations.accountUuid=accounts.uuid where accounts.username=? and accounts.server=?", new String[] { jid.getEscapedLocal(), jid.getDomain().toEscapedString() });
        countCursor.moveToFirst();
        final int count = countCursor.getInt(0);
        Log.d(Config.LOGTAG, String.format("restored %d messages in %s", count, stopwatch.stop().toString()));
        countCursor.close();
        stopBackgroundService();
        synchronized (mOnBackupProcessedListeners) {
            for (OnBackupProcessed l : mOnBackupProcessedListeners) {
                l.onBackupRestored();
            }
        }
        return true;
    } catch (final Exception e) {
        final Throwable throwable = e.getCause();
        final boolean reasonWasCrypto = throwable instanceof BadPaddingException || e instanceof ZipException;
        synchronized (mOnBackupProcessedListeners) {
            for (OnBackupProcessed l : mOnBackupProcessedListeners) {
                if (reasonWasCrypto) {
                    l.onBackupDecryptionFailed();
                } else {
                    l.onBackupRestoreFailed();
                }
            }
        }
        Log.d(Config.LOGTAG, "error restoring backup " + uri, e);
        return false;
    }
}
Also used : KeyParameter(org.bouncycastle.crypto.params.KeyParameter) Stopwatch(com.google.common.base.Stopwatch) BadPaddingException(javax.crypto.BadPaddingException) Cursor(android.database.Cursor) GZIPInputStream(java.util.zip.GZIPInputStream) AEADBlockCipher(org.bouncycastle.crypto.modes.AEADBlockCipher) AESEngine(org.bouncycastle.crypto.engines.AESEngine) CipherInputStream(org.bouncycastle.crypto.io.CipherInputStream) InputStreamReader(java.io.InputStreamReader) Jid(eu.siacs.conversations.xmpp.Jid) GZIPInputStream(java.util.zip.GZIPInputStream) CountingInputStream(com.google.common.io.CountingInputStream) CipherInputStream(org.bouncycastle.crypto.io.CipherInputStream) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CountingInputStream(com.google.common.io.CountingInputStream) ZipException(java.util.zip.ZipException) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream) ZipException(java.util.zip.ZipException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) BackupFileHeader(eu.siacs.conversations.utils.BackupFileHeader) AEADParameters(org.bouncycastle.crypto.params.AEADParameters) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) BufferedReader(java.io.BufferedReader) File(java.io.File) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher)

Example 59 with ZipException

use of java.util.zip.ZipException in project dex-method-counts by mihaip.

the class Main method openInputFileAsZip.

/**
 * Tries to open an input file as a Zip archive (jar/apk) with a
 * "classes.dex" inside.
 */
void openInputFileAsZip(String fileName, List<RandomAccessFile> dexFiles) throws IOException {
    ZipFile zipFile;
    // Try it as a zip file.
    try {
        zipFile = new ZipFile(fileName);
    } catch (FileNotFoundException fnfe) {
        // not found, no point in retrying as non-zip.
        System.err.println("Unable to open '" + fileName + "': " + fnfe.getMessage());
        throw fnfe;
    } catch (ZipException ze) {
        // not a zip
        return;
    }
    // Open and add all files matching "classes.*\.dex" in the zip file.
    for (ZipEntry entry : Collections.list(zipFile.entries())) {
        if (entry.getName().matches("classes.*\\.dex")) {
            dexFiles.add(openDexFile(zipFile, entry));
        }
    }
    zipFile.close();
}
Also used : ZipFile(java.util.zip.ZipFile) ZipEntry(java.util.zip.ZipEntry) FileNotFoundException(java.io.FileNotFoundException) ZipException(java.util.zip.ZipException)

Example 60 with ZipException

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

the class ImportingUtilities method saveStreamToFile.

private static long saveStreamToFile(InputStream stream, File file, SavingUpdate update) throws IOException {
    long length = 0;
    FileOutputStream fos = new FileOutputStream(file);
    try {
        byte[] bytes = new byte[16 * 1024];
        int c;
        while ((update == null || !update.isCanceled()) && (c = stream.read(bytes)) > 0) {
            fos.write(bytes, 0, c);
            length += c;
            if (update != null) {
                update.totalRetrievedSize += c;
                update.savedMore();
            }
        }
        return length;
    } catch (ZipException e) {
        throw new IOException("Compression format not supported, " + e.getMessage());
    } finally {
        fos.close();
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) ZipException(java.util.zip.ZipException) IOException(java.io.IOException)

Aggregations

ZipException (java.util.zip.ZipException)197 IOException (java.io.IOException)96 File (java.io.File)74 ZipEntry (java.util.zip.ZipEntry)67 ZipFile (java.util.zip.ZipFile)63 InputStream (java.io.InputStream)50 FileInputStream (java.io.FileInputStream)39 ZipInputStream (java.util.zip.ZipInputStream)26 FileOutputStream (java.io.FileOutputStream)23 BufferedInputStream (java.io.BufferedInputStream)22 JarFile (java.util.jar.JarFile)21 FileNotFoundException (java.io.FileNotFoundException)19 JarEntry (java.util.jar.JarEntry)19 ArrayList (java.util.ArrayList)18 ByteArrayInputStream (java.io.ByteArrayInputStream)15 ZipOutputStream (java.util.zip.ZipOutputStream)15 URL (java.net.URL)14 GZIPInputStream (java.util.zip.GZIPInputStream)12 BufferedOutputStream (java.io.BufferedOutputStream)8 RandomAccessFile (java.io.RandomAccessFile)8