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