Search in sources :

Example 1 with CountingInputStream

use of com.google.common.io.CountingInputStream in project GeoGig by boundlessgeo.

the class SendObjectResource method post.

@Override
public void post(Representation entity) {
    InputStream input = null;
    Request request = getRequest();
    try {
        LOGGER.info("Receiving objects from {}", request.getClientInfo().getAddress());
        Representation representation = request.getEntity();
        input = representation.getStream();
        final GeoGIG ggit = getGeogig(request).get();
        final BinaryPackedObjects unpacker = new BinaryPackedObjects(ggit.getRepository().objectDatabase());
        CountingInputStream countingStream = new CountingInputStream(input);
        Stopwatch sw = Stopwatch.createStarted();
        IngestResults ingestResults = unpacker.ingest(countingStream);
        sw.stop();
        LOGGER.info(String.format("SendObjectResource: Processed %,d objects.\nInserted: %,d.\nExisting: %,d.\nTime to process: %s.\nStream size: %,d bytes.\n", ingestResults.total(), ingestResults.getInserted(), ingestResults.getExisting(), sw, countingStream.getCount()));
    } catch (IOException e) {
        LOGGER.warn("Error processing incoming objects from {}", request.getClientInfo().getAddress(), e);
        throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL, e);
    } finally {
        if (input != null)
            Closeables.closeQuietly(input);
    }
}
Also used : CountingInputStream(com.google.common.io.CountingInputStream) InputStream(java.io.InputStream) RestletException(org.locationtech.geogig.rest.RestletException) Request(org.restlet.data.Request) CountingInputStream(com.google.common.io.CountingInputStream) Stopwatch(com.google.common.base.Stopwatch) Representation(org.restlet.resource.Representation) IngestResults(org.locationtech.geogig.remote.BinaryPackedObjects.IngestResults) IOException(java.io.IOException) GeoGIG(org.locationtech.geogig.api.GeoGIG) BinaryPackedObjects(org.locationtech.geogig.remote.BinaryPackedObjects)

Example 2 with CountingInputStream

use of com.google.common.io.CountingInputStream in project POL-POM-5 by PhoenicisOrg.

the class Zip method uncompressZipFile.

List<File> uncompressZipFile(File inputFile, File outputDir, Consumer<ProgressEntity> stateCallback) {
    try (CountingInputStream inputStream = new CountingInputStream(new FileInputStream(inputFile))) {
        final long finalSize = FileUtils.sizeOf(inputFile);
        List<File> files = uncompress(inputStream, inputStream, outputDir, finalSize, stateCallback);
        return files;
    } catch (IOException e) {
        throw new ArchiveException(ZIP_ERROR_MESSAGE, e);
    }
}
Also used : CountingInputStream(com.google.common.io.CountingInputStream)

Example 3 with CountingInputStream

use of com.google.common.io.CountingInputStream in project jackrabbit-oak by apache.

the class StatsCollectingStreams method wrap.

public static InputStream wrap(final BlobStatsCollector collector, final String blobId, InputStream in) {
    final CountingInputStream cin = new CountingInputStream(in);
    return new FilterInputStream(cin) {

        final long startTime = System.nanoTime();

        @Override
        public void close() throws IOException {
            super.close();
            // We rely on close to determine how much was downloaded
            // as once an InputStream is exposed its not possible to
            // determine if the stream is actually used
            // Download time might not be accurate as reading code might
            // be processing also as it moved further in stream. So that
            // overhead would add to the download time
            collector.downloaded(blobId, System.nanoTime() - startTime, TimeUnit.NANOSECONDS, cin.getCount());
            collector.downloadCompleted(blobId);
        }
    };
}
Also used : FilterInputStream(java.io.FilterInputStream) CountingInputStream(com.google.common.io.CountingInputStream)

Example 4 with CountingInputStream

use of com.google.common.io.CountingInputStream in project openscoring by openscoring.

the class ModelRegistry method load.

@SuppressWarnings(value = { "resource" })
public Model load(InputStream is) throws Exception {
    CountingInputStream countingIs = new CountingInputStream(is);
    HashingInputStream hashingIs = new HashingInputStream(Hashing.md5(), countingIs);
    PMML pmml = unmarshal(hashingIs, this.validate);
    this.visitorBattery.applyTo(pmml);
    ModelEvaluatorFactory modelEvaluatorFactory = this.modelEvaluatorFactory;
    Evaluator evaluator = modelEvaluatorFactory.newModelEvaluator(pmml);
    evaluator.verify();
    Model model = new Model(evaluator);
    model.putProperty(Model.PROPERTY_FILE_SIZE, countingIs.getCount());
    model.putProperty(Model.PROPERTY_FILE_MD5SUM, (hashingIs.hash()).toString());
    return model;
}
Also used : CountingInputStream(com.google.common.io.CountingInputStream) PMML(org.dmg.pmml.PMML) HasPMML(org.jpmml.evaluator.HasPMML) ModelEvaluatorFactory(org.jpmml.evaluator.ModelEvaluatorFactory) Evaluator(org.jpmml.evaluator.Evaluator) HashingInputStream(com.google.common.hash.HashingInputStream)

Example 5 with CountingInputStream

use of com.google.common.io.CountingInputStream 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)

Aggregations

CountingInputStream (com.google.common.io.CountingInputStream)16 IOException (java.io.IOException)7 InputStream (java.io.InputStream)3 Stopwatch (com.google.common.base.Stopwatch)2 DataInputStream (java.io.DataInputStream)2 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 LazyInputStream (org.apache.jackrabbit.oak.commons.io.LazyInputStream)2 ParseContext (org.apache.tika.parser.ParseContext)2 WriteOutContentHandler (org.apache.tika.sax.WriteOutContentHandler)2 Cursor (android.database.Cursor)1 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)1 HashingInputStream (com.google.common.hash.HashingInputStream)1 StreamMetadata (com.palantir.atlasdb.protos.generated.StreamPersistence.StreamMetadata)1 BackupFileHeader (eu.siacs.conversations.utils.BackupFileHeader)1 Jid (eu.siacs.conversations.xmpp.Jid)1 BufferedReader (java.io.BufferedReader)1 FilterInputStream (java.io.FilterInputStream)1 InputStreamReader (java.io.InputStreamReader)1