Search in sources :

Example 81 with BufferedSink

use of okio.BufferedSink in project android-priority-jobqueue by yigit.

the class FileStorage method save.

void save(String id, byte[] data) throws IOException {
    final File file = toFile(id);
    BufferedSink sink = Okio.buffer(Okio.sink(file));
    try {
        sink.write(data).flush();
    } finally {
        closeQuitely(sink);
    }
}
Also used : BufferedSink(okio.BufferedSink) File(java.io.File)

Example 82 with BufferedSink

use of okio.BufferedSink in project twitter4j by yusuke.

the class AlternativeHttpClientImpl method createInputStreamRequestBody.

public static RequestBody createInputStreamRequestBody(final MediaType mediaType, final InputStream inputStream) {
    return new RequestBody() {

        @Override
        public MediaType contentType() {
            return mediaType;
        }

        @Override
        public long contentLength() {
            try {
                return inputStream.available();
            } catch (IOException e) {
                return 0;
            }
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source = null;
            try {
                source = Okio.source(inputStream);
                sink.writeAll(source);
            } finally {
                Util.closeQuietly(source);
            }
        }
    };
}
Also used : BufferedSink(okio.BufferedSink) IOException(java.io.IOException) Source(okio.Source)

Example 83 with BufferedSink

use of okio.BufferedSink in project cw-omnibus by commonsguy.

the class DownloadCheckService method download.

private File download(String url) throws IOException {
    File output = new File(getFilesDir(), UPDATE_FILENAME);
    if (output.exists()) {
        output.delete();
    }
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();
    BufferedSink sink = Okio.buffer(Okio.sink(output));
    sink.writeAll(response.body().source());
    sink.close();
    return (output);
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) File(java.io.File)

Example 84 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)

Aggregations

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