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);
}
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;
}
}
}
}
}
}
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;
}
}
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();
}
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();
}
}
Aggregations