Java Code Examples for com.linecorp.linesdk.LineApiResponse#createAsError()

The following examples show how to use com.linecorp.linesdk.LineApiResponse#createAsError() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TalkApiClientTest.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMessageToMultipleUsersUsingOtt_getOtt_failed() {
    final LineApiResponse<?> mockResponse = LineApiResponse.createAsError(
            LineApiResponseCode.NETWORK_ERROR, new LineApiError(""));
    givenPostWithJsonApiResponse(mockResponse);

    LineApiResponse<List<SendMessageResponse>> actualApiResponse =
            target.sendMessageToMultipleUsers(
                    ACCESS_TOKEN,
                    Collections.emptyList(),
                    Collections.emptyList(),
                    true);

    assertThat(actualApiResponse.getResponseCode(), sameInstance(mockResponse.getResponseCode()));
    assertThat(actualApiResponse.getErrorData(), sameInstance(mockResponse.getErrorData()));

    // Gets ott by target user ids
    verifyApiCallPostWithJson("/" + BASE_PATH_MESSAGE_API + "/" + PATH_OTT_ISSUE);
    responseParserInstanceShouldBe(TalkApiClient.StringParser.class);

    // Should not send message due to failure of getting ott
    verify(target, never()).sendMessageToMultipleUsersUsingOtt(any(), any(), any());
}
 
Example 2
Source File: LineApiClientImpl.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@Override
@NonNull
public LineApiResponse<LineAccessToken> getCurrentAccessToken() {
    InternalAccessToken internalAccessToken;
    try {
        internalAccessToken = accessTokenCache.getAccessToken();
    } catch (Exception exception) {
        return LineApiResponse.createAsError(
                LineApiResponseCode.INTERNAL_ERROR,
                new LineApiError("get access token fail:" + exception.getMessage())
        );
    }

    if (internalAccessToken == null) {
        return LineApiResponse.createAsError(
                LineApiResponseCode.INTERNAL_ERROR,
                new LineApiError("The cached access token does not exist."));
    }

    return LineApiResponse.createAsSuccess(new LineAccessToken(
            internalAccessToken.getAccessToken(),
            internalAccessToken.getExpiresInMillis(),
            internalAccessToken.getIssuedClientTimeMillis()));
}
 
Example 3
Source File: LineAuthenticationApiClient.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@NonNull
public LineApiResponse<JWKSet> getJWKSet() {
    final LineApiResponse<OpenIdDiscoveryDocument> discoveryDocResponse = getOpenIdDiscoveryDocument();

    if (!discoveryDocResponse.isSuccess()) {
        return LineApiResponse.createAsError(discoveryDocResponse.getResponseCode(),
                discoveryDocResponse.getErrorData());
    }

    final OpenIdDiscoveryDocument openIdDiscoveryDoc = discoveryDocResponse.getResponseData();
    final Uri jwksUri = Uri.parse(openIdDiscoveryDoc.getJwksUri());

    final LineApiResponse<JWKSet> jwkSetResponse =
            httpClient.get(jwksUri,
                    emptyMap(),
                    emptyMap(),
                    JWK_SET_PARSER);
    if (!jwkSetResponse.isSuccess()) {
        Log.e(TAG, "getJWKSet failed: " + jwkSetResponse);
    }

    return jwkSetResponse;
}
 
Example 4
Source File: LineApiClientImplTest.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testRefreshTokenWithApiError() {
    accessTokenCache.saveAccessToken(ACCESS_TOKEN);
    LineApiResponse<RefreshTokenResult> refreshTokenResponse =
            LineApiResponse.createAsError(
                    LineApiResponseCode.INTERNAL_ERROR, LineApiError.DEFAULT);
    doReturn(refreshTokenResponse)
            .when(internalOauthApiClient)
            .refreshToken(anyString(), any(InternalAccessToken.class));

    LineApiResponse<LineAccessToken> actualResponse = target.refreshAccessToken();

    verify(internalOauthApiClient, times(1)).refreshToken(CHANNEL_ID, ACCESS_TOKEN);
    assertFalse(actualResponse.isSuccess());
    assertEquals(ACCESS_TOKEN, accessTokenCache.getAccessToken());
}
 
Example 5
Source File: LineApiClientImpl.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@NonNull
private <T> LineApiResponse<T> callWithAccessToken(@NonNull final APIWithAccessToken<T> api) {
    InternalAccessToken accessToken;

    try {
        accessToken = accessTokenCache.getAccessToken();
    } catch (Exception exception) {
        return LineApiResponse.createAsError(
                LineApiResponseCode.INTERNAL_ERROR,
                new LineApiError("get access token fail:" + exception.getMessage())
        );
    }

    if (accessToken == null) {
        return ERROR_RESPONSE_NO_TOKEN;
    } else {
        return api.call(accessToken);
    }
}
 
Example 6
Source File: TalkApiClient.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@NonNull
public LineApiResponse<List<SendMessageResponse>> sendMessageToMultipleUsers(
        @NonNull InternalAccessToken accessToken,
        @NonNull List<String> targetUserIds,
        @NonNull List<MessageData> messages,
        boolean isOttUsed) {
    if (isOttUsed) {
        LineApiResponse<String> ottResponse = getOtt(accessToken, targetUserIds);
        if (ottResponse.isSuccess()) {
            return sendMessageToMultipleUsersUsingOtt(accessToken, ottResponse.getResponseData(), messages);
        } else {
            return LineApiResponse.createAsError(
                    ottResponse.getResponseCode(),
                    ottResponse.getErrorData());
        }
    } else {
        return sendMessageToMultipleUsersUsingUserIds(accessToken, targetUserIds, messages);
    }
}
 
Example 7
Source File: TalkApiClient.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@NonNull
private LineApiResponse<String> getOtt(
        @NonNull InternalAccessToken accessToken,
        @NonNull List<String> targetUserIds) {
    String postData;
    try {
        postData = new OttRequest(targetUserIds).toJsonString();
    } catch (JSONException e) {
        return LineApiResponse.createAsError(
                LineApiResponseCode.INTERNAL_ERROR,
                new LineApiError(e));
    }

    return httpClient.postWithJson(
            buildUri(apiBaseUrl, BASE_PATH_MESSAGE_API, PATH_OTT_ISSUE),
            buildRequestHeaders(accessToken),
            postData,
            new StringParser("token"));
}
 
Example 8
Source File: ChannelServiceHttpClient.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@NonNull
private static <T> LineApiResponse<T> getChannelServiceResponse(
        @NonNull HttpURLConnection conn,
        @Nullable ResponseDataParser<T> responseDataParser,
        @NonNull ResponseDataParser<String> errorResponseParser) throws IOException {
    InputStream inputStream = getInputStreamFrom(conn);
    int httpResponseCode = conn.getResponseCode();
    try {
        if (httpResponseCode != HttpURLConnection.HTTP_OK
                && httpResponseCode != HttpURLConnection.HTTP_NO_CONTENT) {
            return LineApiResponse.createAsError(
                    LineApiResponseCode.SERVER_ERROR,
                    new LineApiError(
                            httpResponseCode,
                            errorResponseParser.getResponseData(inputStream)));
        }

        if (responseDataParser == null) {
            return LineApiResponse.createAsSuccess(null);
        }

        return LineApiResponse.createAsSuccess(responseDataParser.getResponseData(inputStream));
    } catch (IOException e) {
        // Evaluates response data parsing error as INTERNAL_ERROR
        return LineApiResponse.createAsError(
                LineApiResponseCode.INTERNAL_ERROR,
                new LineApiError(httpResponseCode, e));
    }
}
 
Example 9
Source File: LineApiClientImplTest.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFriendshipStatusWithApiCallError() {
    LineApiResponse<LineFriendshipStatus> expectedResponse = LineApiResponse.createAsError(
            LineApiResponseCode.INTERNAL_ERROR, LineApiError.DEFAULT);
    doReturn(expectedResponse)
            .when(internalTalkApiClient)
            .getFriendshipStatus(any(InternalAccessToken.class));
    accessTokenCache.saveAccessToken(ACCESS_TOKEN);

    LineApiResponse<LineFriendshipStatus> actualResponse = target.getFriendshipStatus();

    assertSame(expectedResponse, actualResponse);
    verify(internalTalkApiClient, times(1)).getFriendshipStatus(ACCESS_TOKEN);
}
 
Example 10
Source File: LineApiClientImplTest.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetProfileWithApiCallError() {
    LineApiResponse<LineProfile> expectedResponse = LineApiResponse.createAsError(
            LineApiResponseCode.INTERNAL_ERROR, LineApiError.DEFAULT);
    doReturn(expectedResponse)
            .when(internalTalkApiClient)
            .getProfile(any(InternalAccessToken.class));
    accessTokenCache.saveAccessToken(ACCESS_TOKEN);

    LineApiResponse<LineProfile> actualResponse = target.getProfile();

    assertSame(expectedResponse, actualResponse);
    verify(internalTalkApiClient, times(1)).getProfile(ACCESS_TOKEN);
}
 
Example 11
Source File: LineApiClientImplTest.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogoutWithApiCallError() {
    LineApiResponse<?> expectedResponse = LineApiResponse.createAsError(
            LineApiResponseCode.INTERNAL_ERROR, LineApiError.DEFAULT);
    doReturn(expectedResponse)
            .when(internalOauthApiClient)
            .revokeRefreshToken(anyString(), any(InternalAccessToken.class));
    accessTokenCache.saveAccessToken(ACCESS_TOKEN);

    LineApiResponse<?> actualResponse = target.logout();

    assertSame(expectedResponse, actualResponse);
    verify(internalOauthApiClient, times(1)).revokeRefreshToken(CHANNEL_ID, ACCESS_TOKEN);
    assertEquals(ACCESS_TOKEN, accessTokenCache.getAccessToken());
}
 
Example 12
Source File: ChannelServiceHttpClient.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@WorkerThread
@NonNull
public <T> LineApiResponse<T> delete(
        @NonNull Uri uri,
        @NonNull Map<String, String> requestHeaders,
        @Nullable ResponseDataParser<T> responseDataParser) {
    HttpURLConnection conn = null;
    try {
        conn = openDeleteConnection(uri);
        setRequestHeaders(conn, requestHeaders);
        if (BuildConfig.DEBUG) {
            logRequestForDebug(conn, null /* requestBody */);
        }
        conn.connect();
        if (BuildConfig.DEBUG) {
            logResponseHeadersForDebug(conn);
        }
        return getChannelServiceResponse(conn, responseDataParser, errorResponseParser);
    } catch (IOException e) {
        LineApiResponse<T> response = LineApiResponse.createAsError(
                LineApiResponseCode.NETWORK_ERROR, new LineApiError(e));
        logExceptionForDebug(response, e);
        return response;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}
 
Example 13
Source File: ChannelServiceHttpClient.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@WorkerThread
@NonNull
public <T> LineApiResponse<T> get(
        @NonNull Uri uri,
        @NonNull Map<String, String> requestHeaders,
        @NonNull Map<String, String> queryParameters,
        @Nullable ResponseDataParser<T> responseDataParser) {
    final Uri fullUri = appendQueryParams(uri, queryParameters);

    HttpURLConnection conn = null;
    try {
        conn = openGetConnection(fullUri);
        setRequestHeaders(conn, requestHeaders);
        if (BuildConfig.DEBUG) {
            logRequestForDebug(conn, null /* requestBody */);
        }
        conn.connect();
        if (BuildConfig.DEBUG) {
            logResponseHeadersForDebug(conn);
        }
        return getChannelServiceResponse(conn, responseDataParser, errorResponseParser);
    } catch (IOException e) {
        LineApiResponse<T> response = LineApiResponse.createAsError(
                LineApiResponseCode.NETWORK_ERROR, new LineApiError(e));
        logExceptionForDebug(response, e);
        return response;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}
 
Example 14
Source File: ChannelServiceHttpClient.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@WorkerThread
@NonNull
private <T> LineApiResponse<T> sendRequestWithJson(
        @NonNull HttpMethod method,
        @NonNull Uri uri,
        @NonNull Map<String, String> requestHeaders,
        @NonNull String postData,
        @Nullable ResponseDataParser<T> responseDataParser) {
    byte[] postDataBytes = postData.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = openConnectionWithJson(uri, postDataBytes.length, method);
        setRequestHeaders(conn, requestHeaders);
        if (BuildConfig.DEBUG) {
            logRequestForDebug(conn, postDataBytes);
        }
        conn.connect();

        OutputStream os = conn.getOutputStream();
        os.write(postDataBytes);
        os.flush();
        if (BuildConfig.DEBUG) {
            logResponseHeadersForDebug(conn);
        }

        return getChannelServiceResponse(conn, responseDataParser, errorResponseParser);
    } catch (IOException e) {
        LineApiResponse<T> response = LineApiResponse.createAsError(
                LineApiResponseCode.NETWORK_ERROR, new LineApiError(e));
        logExceptionForDebug(response, e);
        return response;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}
 
Example 15
Source File: ChannelServiceHttpClient.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@WorkerThread
@NonNull
public <T> LineApiResponse<T> post(
        @NonNull Uri uri,
        @NonNull Map<String, String> requestHeaders,
        @NonNull Map<String, String> postData,
        @NonNull ResponseDataParser<T> responseDataParser) {
    byte[] postDataBytes = convertPostDataToBytes(postData);
    HttpURLConnection conn = null;
    try {
        conn = openPostConnection(uri, postDataBytes.length);
        setRequestHeaders(conn, requestHeaders);
        if (BuildConfig.DEBUG) {
            logRequestForDebug(conn, postDataBytes);
        }
        conn.connect();

        OutputStream os = conn.getOutputStream();
        os.write(postDataBytes);
        os.flush();
        if (BuildConfig.DEBUG) {
            logResponseHeadersForDebug(conn);
        }

        return getChannelServiceResponse(conn, responseDataParser, errorResponseParser);
    } catch (IOException e) {
        LineApiResponse<T> response = LineApiResponse.createAsError(
                LineApiResponseCode.NETWORK_ERROR, new LineApiError(e));
        logExceptionForDebug(response, e);
        return response;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}
 
Example 16
Source File: LineApiClientImpl.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@NonNull
private LineApiResponse<LineCredential> verifyToken(@NonNull InternalAccessToken accessToken) {
    LineApiResponse<AccessTokenVerificationResult> response =
            oauthApiClient.verifyAccessToken(accessToken);
    if (!response.isSuccess()) {
        return LineApiResponse.createAsError(
                response.getResponseCode(), response.getErrorData());
    }
    AccessTokenVerificationResult verificationResult = response.getResponseData();
    long verifiedClientTimeMillis = System.currentTimeMillis();

    try {
        accessTokenCache.saveAccessToken(
                new InternalAccessToken(
                        accessToken.getAccessToken(),
                        verificationResult.getExpiresInMillis(),
                        verifiedClientTimeMillis,
                        accessToken.getRefreshToken()));
    } catch(Exception exception) {
        return LineApiResponse.createAsError(
                LineApiResponseCode.INTERNAL_ERROR,
                new LineApiError("save access token fail:" + exception.getMessage())
        );
    }

    return LineApiResponse.createAsSuccess(
            new LineCredential(
                    new LineAccessToken(
                            accessToken.getAccessToken(),
                            verificationResult.getExpiresInMillis(),
                            verifiedClientTimeMillis),
                    verificationResult.getScopes()));
}
 
Example 17
Source File: TalkApiClient.java    From line-sdk-android with Apache License 2.0 4 votes vote down vote up
private <T> LineApiResponse<T> createInternalErrorResponse(Exception exception) {
    return LineApiResponse.createAsError(LineApiResponseCode.INTERNAL_ERROR, new LineApiError(exception));
}