Search in sources :

Example 41 with Response

use of com.yahoo.vespa.clustercontroller.core.restapiv2.Response in project Tusky by Vavassor.

the class BaseActivity method enablePushNotifications.

protected void enablePushNotifications() {
    Callback<ResponseBody> callback = new Callback<ResponseBody>() {

        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            if (response.isSuccessful()) {
                pushNotificationClient.subscribeToTopic(getPushNotificationTopic());
                pushNotificationClient.connect(BaseActivity.this);
            } else {
                onEnablePushNotificationsFailure(response.message());
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            onEnablePushNotificationsFailure(t.getMessage());
        }
    };
    String deviceToken = pushNotificationClient.getDeviceToken();
    Session session = new Session(getDomain(), getAccessToken(), deviceToken);
    tuskyApi.register(session).enqueue(callback);
}
Also used : Response(okhttp3.Response) Call(retrofit2.Call) Callback(retrofit2.Callback) ResponseBody(okhttp3.ResponseBody) Session(com.keylesspalace.tusky.entity.Session)

Example 42 with Response

use of com.yahoo.vespa.clustercontroller.core.restapiv2.Response in project Tusky by Vavassor.

the class LoginActivity method onStart.

@Override
protected void onStart() {
    super.onStart();
    /* Check if we are resuming during authorization by seeing if the intent contains the
         * redirect that was given to the server. If so, its response is here! */
    Uri uri = getIntent().getData();
    String redirectUri = getOauthRedirectUri();
    preferences = getSharedPreferences(getString(R.string.preferences_file_key), Context.MODE_PRIVATE);
    if (preferences.getString("accessToken", null) != null && preferences.getString("domain", null) != null) {
        // We are already logged in, go to MainActivity
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
        return;
    }
    if (uri != null && uri.toString().startsWith(redirectUri)) {
        // This should either have returned an authorization code or an error.
        String code = uri.getQueryParameter("code");
        String error = uri.getQueryParameter("error");
        if (code != null) {
            /* During the redirect roundtrip this Activity usually dies, which wipes out the
                 * instance variables, so they have to be recovered from where they were saved in
                 * SharedPreferences. */
            domain = preferences.getString("domain", null);
            clientId = preferences.getString("clientId", null);
            clientSecret = preferences.getString("clientSecret", null);
            setLoading(true);
            /* Since authorization has succeeded, the final step to log in is to exchange
                 * the authorization code for an access token. */
            Callback<AccessToken> callback = new Callback<AccessToken>() {

                @Override
                public void onResponse(Call<AccessToken> call, Response<AccessToken> response) {
                    if (response.isSuccessful()) {
                        onLoginSuccess(response.body().accessToken);
                    } else {
                        setLoading(false);
                        editText.setError(getString(R.string.error_retrieving_oauth_token));
                        Log.e(TAG, String.format("%s %s", getString(R.string.error_retrieving_oauth_token), response.message()));
                    }
                }

                @Override
                public void onFailure(Call<AccessToken> call, Throwable t) {
                    setLoading(false);
                    editText.setError(getString(R.string.error_retrieving_oauth_token));
                    Log.e(TAG, String.format("%s %s", getString(R.string.error_retrieving_oauth_token), t.getMessage()));
                }
            };
            getApiFor(domain).fetchOAuthToken(clientId, clientSecret, redirectUri, code, "authorization_code").enqueue(callback);
        } else if (error != null) {
            /* Authorization failed. Put the error response where the user can read it and they
                 * can try again. */
            setLoading(false);
            editText.setError(getString(R.string.error_authorization_denied));
            Log.e(TAG, getString(R.string.error_authorization_denied) + error);
        } else {
            setLoading(false);
            // This case means a junk response was received somehow.
            editText.setError(getString(R.string.error_authorization_unknown));
        }
    }
}
Also used : Response(retrofit2.Response) Call(retrofit2.Call) Callback(retrofit2.Callback) AccessToken(com.keylesspalace.tusky.entity.AccessToken) CustomTabsIntent(android.support.customtabs.CustomTabsIntent) Intent(android.content.Intent) Uri(android.net.Uri)

Example 43 with Response

use of com.yahoo.vespa.clustercontroller.core.restapiv2.Response in project Rocket.Chat.Android by RocketChat.

the class RxWebSocket method connect.

public ConnectableFlowable<RxWebSocketCallback.Base> connect(String url) {
    final Request request = new Request.Builder().url(url).build();
    return Flowable.create((FlowableOnSubscribe<RxWebSocketCallback.Base>) emitter -> httpClient.newWebSocket(request, new WebSocketListener() {

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            RxWebSocket.this.webSocket = webSocket;
            emitter.onNext(new RxWebSocketCallback.Open(RxWebSocket.this.webSocket, response));
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable err, Response response) {
            try {
                emitter.onError(new RxWebSocketCallback.Failure(webSocket, err, response));
            } catch (OnErrorNotImplementedException ex) {
                RCLog.w(ex, "OnErrorNotImplementedException ignored");
            }
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            emitter.onNext(new RxWebSocketCallback.Message(webSocket, text));
        }

        @Override
        public void onClosed(WebSocket webSocket, int code, String reason) {
            emitter.onNext(new RxWebSocketCallback.Close(webSocket, code, reason));
            emitter.onComplete();
        }
    }), BackpressureStrategy.BUFFER).publish();
}
Also used : FlowableOnSubscribe(io.reactivex.FlowableOnSubscribe) WebSocketListener(okhttp3.WebSocketListener) Request(okhttp3.Request) OnErrorNotImplementedException(io.reactivex.exceptions.OnErrorNotImplementedException) WebSocket(okhttp3.WebSocket) Response(okhttp3.Response)

Example 44 with Response

use of com.yahoo.vespa.clustercontroller.core.restapiv2.Response in project Rocket.Chat.Android by RocketChat.

the class FileUploadingWithUfsObserver 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() >= 1) {
        // do not upload multiple files simultaneously
        return;
    }
    RealmUser currentUser = realmHelper.executeTransactionForRead(realm -> RealmUser.queryCurrentUser(realm).findFirst());
    RealmSession session = realmHelper.executeTransactionForRead(realm -> RealmSession.queryDefaultSession(realm).findFirst());
    if (currentUser == null || session == null) {
        return;
    }
    final String cookie = String.format("rc_uid=%s; rc_token=%s", currentUser.getId(), session.getToken());
    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 store = FileUploading.STORAGE_TYPE_GRID_FS.equals(fileUploading.getStorageType()) ? "rocketchat_uploads" : (FileUploading.STORAGE_TYPE_FILE_SYSTEM.equals(fileUploading.getStorageType()) ? "fileSystem" : null);
    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.SYNC_STATE, SyncState.SYNCING))).onSuccessTask(_task -> methodCall.ufsCreate(filename, filesize, mimeType, store, roomId)).onSuccessTask(task -> {
        final JSONObject info = task.getResult();
        final String fileId = info.getString("fileId");
        final String token = info.getString("token");
        final String url = info.getString("url");
        final int bufSize = 16384;
        final byte[] buffer = new byte[bufSize];
        int offset = 0;
        final MediaType contentType = MediaType.parse(mimeType);
        try (InputStream inputStream = context.getContentResolver().openInputStream(fileUri)) {
            int read;
            while ((read = inputStream.read(buffer)) > 0) {
                offset += read;
                double progress = 1.0 * offset / filesize;
                Request request = new Request.Builder().url(url + "&progress=" + progress).header("Cookie", cookie).post(RequestBody.create(contentType, buffer, 0, read)).build();
                Response response = OkHttpHelper.getClientForUploadFile().newCall(request).execute();
                if (response.isSuccessful()) {
                    final JSONObject obj = new JSONObject().put(FileUploading.ID, uplId).put(FileUploading.UPLOADED_SIZE, offset);
                    realmHelper.executeTransaction(realm -> realm.createOrUpdateObjectFromJson(FileUploading.class, obj));
                } else {
                    return Task.forError(new Exception(response.message()));
                }
            }
        }
        return methodCall.ufsComplete(fileId, token, store);
    }).onSuccessTask(task -> methodCall.sendFileMessage(roomId, null, task.getResult())).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) Realm(io.realm.Realm) Request(okhttp3.Request) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession) RealmResults(io.realm.RealmResults) Uri(android.net.Uri) RCLog(chat.rocket.android.log.RCLog) LogIfError(chat.rocket.android.helper.LogIfError) RequestBody(okhttp3.RequestBody) List(java.util.List) JSONObject(org.json.JSONObject) RealmHelper(chat.rocket.persistence.realm.RealmHelper) SyncState(chat.rocket.core.SyncState) Response(okhttp3.Response) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) DDPClientRef(chat.rocket.android.service.DDPClientRef) Task(bolts.Task) OkHttpHelper(chat.rocket.android.helper.OkHttpHelper) MediaType(okhttp3.MediaType) InputStream(java.io.InputStream) FileUploadingHelper(chat.rocket.android.api.FileUploadingHelper) InputStream(java.io.InputStream) RealmUser(chat.rocket.persistence.realm.models.ddp.RealmUser) Request(okhttp3.Request) Uri(android.net.Uri) Response(okhttp3.Response) JSONObject(org.json.JSONObject) FileUploading(chat.rocket.persistence.realm.models.internal.FileUploading) MediaType(okhttp3.MediaType) RealmSession(chat.rocket.persistence.realm.models.internal.RealmSession)

Example 45 with Response

use of com.yahoo.vespa.clustercontroller.core.restapiv2.Response in project yyl_example by Relucent.

the class OkhttpTest2 method main.

public static void main(String[] args) throws IOException {
    OkHttpClient client;
    (client = //
    new OkHttpClient.Builder().build()).newCall(//
    new Request.Builder().url(//
    "https://www.baidu.com/").header("Connection", //close | keep-alive
    "close").get().build()).enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            System.out.println(response.body().string());
        }

        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }
    });
    //应用关闭时候需要关闭线程池
    client.dispatcher().executorService().shutdown();
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Callback(okhttp3.Callback) IOException(java.io.IOException)

Aggregations

Response (okhttp3.Response)1083 Request (okhttp3.Request)814 IOException (java.io.IOException)434 Test (org.junit.Test)330 Response (retrofit2.Response)319 Call (okhttp3.Call)236 ResponseBody (okhttp3.ResponseBody)208 OkHttpClient (okhttp3.OkHttpClient)192 ServiceResponse (com.microsoft.rest.ServiceResponse)179 RequestBody (okhttp3.RequestBody)128 Observable (rx.Observable)116 Callback (okhttp3.Callback)111 MockResponse (okhttp3.mockwebserver.MockResponse)93 List (java.util.List)89 HttpUrl (okhttp3.HttpUrl)81 LinkHeaders (com.instructure.canvasapi2.utils.LinkHeaders)72 TypeToken (com.google.common.reflect.TypeToken)71 ArrayList (java.util.ArrayList)71 File (java.io.File)70 JSONObject (org.json.JSONObject)65