Search in sources :

Example 86 with BufferedSink

use of okio.BufferedSink in project Rocket.Chat.Android by RocketChat.

the class FileUploadingToUrlObserver method onUpdateResults.

@Override
public void onUpdateResults(List<FileUploading> results) {
    if (results.isEmpty()) {
        return;
    }
    List<FileUploading> uploadingList = realmHelper.executeTransactionForReadResults(realm -> realm.where(FileUploading.class).equalTo(FileUploading.SYNC_STATE, SyncState.SYNCING).findAll());
    if (uploadingList.size() >= 3) {
        // do not upload more than 3 files simultaneously
        return;
    }
    FileUploading fileUploading = results.get(0);
    final String roomId = fileUploading.getRoomId();
    final String uplId = fileUploading.getUplId();
    final String filename = fileUploading.getFilename();
    final long filesize = fileUploading.getFilesize();
    final String mimeType = fileUploading.getMimeType();
    final Uri fileUri = Uri.parse(fileUploading.getUri());
    final String storageType = fileUploading.getStorageType();
    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCING))).onSuccessTask(_task -> {
        if (FileUploading.STORAGE_TYPE_GOOGLE.equals(storageType)) {
            return methodCall.uploadGoogleRequest(filename, filesize, mimeType, roomId);
        } else {
            return methodCall.uploadS3Request(filename, filesize, mimeType, roomId);
        }
    }).onSuccessTask(task -> {
        final JSONObject info = task.getResult();
        final String uploadUrl = info.getString("upload");
        final String downloadUrl = info.getString("download");
        final JSONArray postDataList = info.getJSONArray("postData");
        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (int i = 0; i < postDataList.length(); i++) {
            JSONObject postData = postDataList.getJSONObject(i);
            bodyBuilder.addFormDataPart(postData.getString("name"), postData.getString("value"));
        }
        bodyBuilder.addFormDataPart("file", filename, new RequestBody() {

            private long numBytes = 0;

            @Override
            public MediaType contentType() {
                return MediaType.parse(mimeType);
            }

            @Override
            public long contentLength() throws IOException {
                return filesize;
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                InputStream inputStream = context.getContentResolver().openInputStream(fileUri);
                try (Source source = Okio.source(inputStream)) {
                    long readBytes;
                    while ((readBytes = source.read(sink.buffer(), 8192)) > 0) {
                        numBytes += readBytes;
                        realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.UPLOADED_SIZE, numBytes))).continueWith(new LogIfError());
                    }
                }
            }
        });
        Request request = new Request.Builder().url(uploadUrl).post(bodyBuilder.build()).build();
        Response response = OkHttpHelper.getClientForUploadFile().newCall(request).execute();
        if (response.isSuccessful()) {
            return Task.forResult(downloadUrl);
        } else {
            return Task.forError(new Exception(response.message()));
        }
    }).onSuccessTask(task -> {
        String downloadUrl = task.getResult();
        String storage = FileUploading.STORAGE_TYPE_GOOGLE.equals(storageType) ? storageType : "s3";
        return methodCall.sendFileMessage(roomId, storage, new JSONObject().put("_id", Uri.parse(downloadUrl).getLastPathSegment()).put("type", mimeType).put("size", filesize).put("name", filename).put("url", downloadUrl));
    }).onSuccessTask(task -> realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCED).put(FileUploading.ERROR, JSONObject.NULL)))).continueWithTask(task -> {
        if (task.isFaulted()) {
            RCLog.w(task.getError());
            return realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.FAILED).put(FileUploading.ERROR, task.getError().getMessage())));
        } else {
            return Task.forResult(null);
        }
    });
}
Also used : Context(android.content.Context) Okio(okio.Okio) Source(okio.Source) Uri(android.net.Uri) LogIfError(chat.rocket.android.helper.LogIfError) RequestBody(okhttp3.RequestBody) JSONObject(org.json.JSONObject) BufferedSink(okio.BufferedSink) SyncState(chat.rocket.core.SyncState) Response(okhttp3.Response) Task(bolts.Task) MediaType(okhttp3.MediaType) FileUploadingHelper(chat.rocket.android.api.FileUploadingHelper) Realm(io.realm.Realm) Request(okhttp3.Request) RealmResults(io.realm.RealmResults) IOException(java.io.IOException) RCLog(chat.rocket.android.log.RCLog) List(java.util.List) MultipartBody(okhttp3.MultipartBody) RealmHelper(chat.rocket.persistence.realm.RealmHelper) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) DDPClientRef(chat.rocket.android.service.DDPClientRef) OkHttpHelper(chat.rocket.android.helper.OkHttpHelper) JSONArray(org.json.JSONArray) InputStream(java.io.InputStream) InputStream(java.io.InputStream) JSONArray(org.json.JSONArray) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) Uri(android.net.Uri) Source(okio.Source) LogIfError(chat.rocket.android.helper.LogIfError) IOException(java.io.IOException) Response(okhttp3.Response) JSONObject(org.json.JSONObject) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) RequestBody(okhttp3.RequestBody)

Example 87 with BufferedSink

use of okio.BufferedSink in project Store by NYTimes.

the class FSFile method write.

public void write(@Nonnull BufferedSource source) throws IOException {
    File tmpFile = File.createTempFile("new", "tmp", file.getParentFile());
    BufferedSink sink = null;
    try {
        sink = Okio.buffer(Okio.sink(tmpFile));
        sink.writeAll(source);
        if (!tmpFile.renameTo(file)) {
            throw new IOException("unable to move tmp file to " + file.getPath());
        }
    } catch (Exception e) {
        throw new IOException("unable to write to file", e);
    } finally {
        tmpFile.delete();
        if (sink != null) {
            sink.close();
        }
        source.close();
    }
}
Also used : BufferedSink(okio.BufferedSink) IOException(java.io.IOException) File(java.io.File) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 88 with BufferedSink

use of okio.BufferedSink in project bitcoin-wallet by bitcoin-wallet.

the class RequestWalletBalanceTask method requestWalletBalance.

public void requestWalletBalance(final AssetManager assets, final Address address) {
    backgroundHandler.post(new Runnable() {

        @Override
        public void run() {
            org.bitcoinj.core.Context.propagate(Constants.CONTEXT);
            try {
                final List<ElectrumServer> servers = loadElectrumServers(assets.open(Constants.Files.ELECTRUM_SERVERS_FILENAME));
                final ElectrumServer server = servers.get(new Random().nextInt(servers.size()));
                log.info("trying to request wallet balance from {}: {}", server.socketAddress, address);
                final Socket socket;
                if (server.type == ElectrumServer.Type.TLS) {
                    final SocketFactory sf = sslTrustAllCertificates();
                    socket = sf.createSocket(server.socketAddress.getHostName(), server.socketAddress.getPort());
                    final SSLSession sslSession = ((SSLSocket) socket).getSession();
                    final Certificate certificate = sslSession.getPeerCertificates()[0];
                    final String certificateFingerprint = sslCertificateFingerprint(certificate);
                    if (server.certificateFingerprint == null) {
                        // signed by CA
                        if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(server.socketAddress.getHostName(), sslSession))
                            throw new SSLHandshakeException("Expected " + server.socketAddress.getHostName() + ", got " + sslSession.getPeerPrincipal());
                    } else {
                        // self-signed
                        if (!certificateFingerprint.equals(server.certificateFingerprint))
                            throw new SSLHandshakeException("Expected " + server.certificateFingerprint + ", got " + certificateFingerprint);
                    }
                } else if (server.type == ElectrumServer.Type.TCP) {
                    socket = new Socket();
                    socket.connect(server.socketAddress, 5000);
                } else {
                    throw new IllegalStateException("Cannot handle: " + server.type);
                }
                final BufferedSink sink = Okio.buffer(Okio.sink(socket));
                sink.timeout().timeout(5000, TimeUnit.MILLISECONDS);
                final BufferedSource source = Okio.buffer(Okio.source(socket));
                source.timeout().timeout(5000, TimeUnit.MILLISECONDS);
                final Moshi moshi = new Moshi.Builder().build();
                final JsonAdapter<JsonRpcRequest> requestAdapter = moshi.adapter(JsonRpcRequest.class);
                final JsonRpcRequest request = new JsonRpcRequest("blockchain.address.listunspent", new String[] { address.toBase58() });
                requestAdapter.toJson(sink, request);
                sink.writeUtf8("\n").flush();
                final JsonAdapter<JsonRpcResponse> responseAdapter = moshi.adapter(JsonRpcResponse.class);
                final JsonRpcResponse response = responseAdapter.fromJson(source);
                if (response.id == request.id) {
                    if (response.result == null)
                        throw new JsonDataException("empty response");
                    final Set<UTXO> utxos = new HashSet<>();
                    for (final JsonRpcResponse.Utxo responseUtxo : response.result) {
                        final Sha256Hash utxoHash = Sha256Hash.wrap(responseUtxo.tx_hash);
                        final int utxoIndex = responseUtxo.tx_pos;
                        final Coin utxoValue = Coin.valueOf(responseUtxo.value);
                        final Script script = ScriptBuilder.createOutputScript(address);
                        final UTXO utxo = new UTXO(utxoHash, utxoIndex, utxoValue, responseUtxo.height, false, script);
                        utxos.add(utxo);
                    }
                    log.info("fetched {} unspent outputs from {}", response.result.length, server.socketAddress);
                    onResult(utxos);
                } else {
                    log.info("id mismatch response:{} vs request:{}", response.id, request.id);
                    onFail(R.string.error_parse, server.socketAddress.toString());
                }
            } catch (final JsonDataException x) {
                log.info("problem parsing json", x);
                onFail(R.string.error_parse, x.getMessage());
            } catch (final IOException x) {
                log.info("problem querying unspent outputs", x);
                onFail(R.string.error_io, x.getMessage());
            }
        }
    });
}
Also used : Moshi(com.squareup.moshi.Moshi) HashSet(java.util.HashSet) Set(java.util.Set) ScriptBuilder(org.bitcoinj.script.ScriptBuilder) Sha256Hash(org.bitcoinj.core.Sha256Hash) BufferedSink(okio.BufferedSink) JsonAdapter(com.squareup.moshi.JsonAdapter) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Coin(org.bitcoinj.core.Coin) Random(java.util.Random) LinkedList(java.util.LinkedList) List(java.util.List) BufferedSource(okio.BufferedSource) Script(org.bitcoinj.script.Script) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) SocketFactory(javax.net.SocketFactory) SSLSession(javax.net.ssl.SSLSession) IOException(java.io.IOException) UTXO(org.bitcoinj.core.UTXO) JsonDataException(com.squareup.moshi.JsonDataException) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 89 with BufferedSink

use of okio.BufferedSink in project java by kubernetes-client.

the class ApiClient method downloadFileFromResponse.

/**
 * Download file from the given response.
 *
 * @param response An instance of the Response object
 * @throws ApiException If fail to read file content from response and write to disk
 * @return Downloaded file
 */
public File downloadFileFromResponse(Response response) throws ApiException {
    try {
        File file = prepareDownloadFile(response);
        BufferedSink sink = Okio.buffer(Okio.sink(file));
        sink.writeAll(response.body().source());
        sink.close();
        return file;
    } catch (IOException e) {
        throw new ApiException(e);
    }
}
Also used : BufferedSink(okio.BufferedSink) IOException(java.io.IOException) File(java.io.File)

Example 90 with BufferedSink

use of okio.BufferedSink in project java by kubernetes-client.

the class GzipRequestInterceptor method gzip.

private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {

        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            // We don't know the compressed length in advance!
            return -1;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
Also used : GzipSink(okio.GzipSink) BufferedSink(okio.BufferedSink)

Aggregations

BufferedSink (okio.BufferedSink)91 Test (org.junit.Test)31 IOException (java.io.IOException)30 Buffer (okio.Buffer)19 File (java.io.File)15 RequestBody (okhttp3.RequestBody)14 GzipSink (okio.GzipSink)12 Source (okio.Source)11 Response (okhttp3.Response)10 BufferedSource (okio.BufferedSource)10 Request (okhttp3.Request)9 InFrame (okhttp3.internal.http2.MockHttp2Peer.InFrame)9 MediaType (okhttp3.MediaType)7 InterruptedIOException (java.io.InterruptedIOException)6 MockResponse (okhttp3.mockwebserver.MockResponse)5 Sink (okio.Sink)5 InputStream (java.io.InputStream)4 Socket (java.net.Socket)4 OkHttpClient (okhttp3.OkHttpClient)4 Request (com.squareup.okhttp.Request)3