Search in sources :

Example 21 with OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException in project openhab-addons by openhab.

the class OpenHabOAuthTokenRefresherTest method whenTokensAreRemovedThenTheRuntimeIsRequestedToDeleteServiceAndAccessToken.

@Test
public void whenTokensAreRemovedThenTheRuntimeIsRequestedToDeleteServiceAndAccessToken() throws org.openhab.core.auth.client.oauth2.OAuthException, IOException, OAuthResponseException {
    // given:
    OAuthClientService oauthClientService = mock(OAuthClientService.class);
    OAuthFactory oauthFactory = mock(OAuthFactory.class);
    when(oauthFactory.getOAuthClientService(MieleCloudBindingTestConstants.SERVICE_HANDLE)).thenReturn(oauthClientService);
    OpenHabOAuthTokenRefresher refresher = new OpenHabOAuthTokenRefresher(oauthFactory);
    OAuthTokenRefreshListener listener = mock(OAuthTokenRefreshListener.class);
    refresher.setRefreshListener(listener, MieleCloudBindingTestConstants.SERVICE_HANDLE);
    // when:
    refresher.removeTokensFromStorage(MieleCloudBindingTestConstants.SERVICE_HANDLE);
    // then:
    verify(oauthFactory).deleteServiceAndAccessToken(MieleCloudBindingTestConstants.SERVICE_HANDLE);
}
Also used : OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) OAuthFactory(org.openhab.core.auth.client.oauth2.OAuthFactory) Test(org.junit.jupiter.api.Test)

Example 22 with OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException in project openhab-addons by openhab.

the class OpenHabOAuthTokenRefresherTest method whenTokenIsRefreshedThenTheListenerIsCalledWithTheNewAccessToken.

@Test
public void whenTokenIsRefreshedThenTheListenerIsCalledWithTheNewAccessToken() throws org.openhab.core.auth.client.oauth2.OAuthException, IOException, OAuthResponseException {
    // given:
    AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
    accessTokenResponse.setAccessToken(ACCESS_TOKEN);
    OAuthClientService oauthClientService = mock(OAuthClientService.class);
    OAuthFactory oauthFactory = mock(OAuthFactory.class);
    when(oauthFactory.getOAuthClientService(MieleCloudBindingTestConstants.SERVICE_HANDLE)).thenReturn(oauthClientService);
    OpenHabOAuthTokenRefresher refresher = new OpenHabOAuthTokenRefresher(oauthFactory);
    when(oauthClientService.refreshToken()).thenAnswer(new Answer<@Nullable AccessTokenResponse>() {

        @Override
        @Nullable
        public AccessTokenResponse answer(@Nullable InvocationOnMock invocation) throws Throwable {
            getAccessTokenRefreshListenerByServiceHandle(refresher, MieleCloudBindingTestConstants.SERVICE_HANDLE).onAccessTokenResponse(accessTokenResponse);
            return accessTokenResponse;
        }
    });
    OAuthTokenRefreshListener listener = mock(OAuthTokenRefreshListener.class);
    refresher.setRefreshListener(listener, MieleCloudBindingTestConstants.SERVICE_HANDLE);
    // when:
    refresher.refreshToken(MieleCloudBindingTestConstants.SERVICE_HANDLE);
    // then:
    verify(listener).onNewAccessToken(ACCESS_TOKEN);
}
Also used : OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) InvocationOnMock(org.mockito.invocation.InvocationOnMock) OAuthFactory(org.openhab.core.auth.client.oauth2.OAuthFactory) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) Nullable(org.eclipse.jdt.annotation.Nullable) Test(org.junit.jupiter.api.Test)

Example 23 with OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException in project openhab-addons by openhab.

the class OAuthAuthorizationHandlerImplTest method whenRetrievingTheAccessTokenFailsDueToAnIllegalAnswerFromTheMieleServiceThenAnOAuthExceptionIsThrownAndAllResourcesAreCleanedUp.

@Test
public void whenRetrievingTheAccessTokenFailsDueToAnIllegalAnswerFromTheMieleServiceThenAnOAuthExceptionIsThrownAndAllResourcesAreCleanedUp() throws Exception {
    // given:
    when(getClientService().extractAuthCodeFromAuthResponse(anyString())).thenReturn(AUTH_CODE);
    when(getClientService().getAccessTokenResponseByAuthorizationCode(anyString(), anyString())).thenThrow(new OAuthResponseException());
    getAuthorizationHandler().beginAuthorization(CLIENT_ID, CLIENT_SECRET, BRIDGE_UID, EMAIL);
    getAuthorizationHandler().getAuthorizationUrl(REDIRECT_URL);
    // when:
    assertThrows(OAuthException.class, () -> {
        try {
            getAuthorizationHandler().completeAuthorization("http://127.0.0.1:8080/mielecloud/result?code=abc&state=def");
        } catch (OAuthException e) {
            assertNull(getPrivate(getAuthorizationHandler(), "timer"));
            assertNull(getPrivate(getAuthorizationHandler(), "oauthClientService"));
            assertNull(getPrivate(getAuthorizationHandler(), "bridgeUid"));
            assertNull(getPrivate(getAuthorizationHandler(), "email"));
            assertNull(getPrivate(getAuthorizationHandler(), "redirectUri"));
            throw e;
        }
    });
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) OAuthException(org.openhab.binding.mielecloud.internal.auth.OAuthException) Test(org.junit.jupiter.api.Test)

Example 24 with OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException in project openhab-addons by openhab.

the class OpenHabOAuthTokenRefresher method refreshAccessToken.

private void refreshAccessToken(OAuthClientService clientService) {
    try {
        final AccessTokenResponse accessTokenResponse = clientService.refreshToken();
        final String accessToken = accessTokenResponse.getAccessToken();
        if (accessToken == null) {
            throw new OAuthException("Access token is not available.");
        }
    } catch (org.openhab.core.auth.client.oauth2.OAuthException e) {
        throw new OAuthException("An error occured during token refresh: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new OAuthException("A network error occured during token refresh: " + e.getMessage(), e);
    } catch (OAuthResponseException e) {
        throw new OAuthException("Miele cloud service returned an illegal response: " + e.getMessage(), e);
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) IOException(java.io.IOException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse)

Example 25 with OAuthResponseException

use of org.openhab.core.auth.client.oauth2.OAuthResponseException in project openhab-addons by openhab.

the class SpotifyApi method request.

/**
 * Calls the Spotify Web Api with the given method and given url as parameters of the call to Spotify.
 *
 * @param method Http method to perform
 * @param url url path to call to Spotify
 * @param requestData data to pass along with the call as content
 * @param clazz data type of return data, if null no data is expected to be returned.
 * @return the response give by Spotify
 */
@Nullable
private <T> T request(HttpMethod method, String url, String requestData, Class<T> clazz) {
    logger.debug("Request: ({}) {} - {}", method, url, requestData);
    final Function<HttpClient, Request> call = httpClient -> httpClient.newRequest(url).method(method).header("Accept", CONTENT_TYPE).content(new StringContentProvider(requestData), CONTENT_TYPE);
    try {
        final AccessTokenResponse accessTokenResponse = oAuthClientService.getAccessTokenResponse();
        final String accessToken = accessTokenResponse == null ? null : accessTokenResponse.getAccessToken();
        if (accessToken == null || accessToken.isEmpty()) {
            throw new SpotifyAuthorizationException("No Spotify accesstoken. Did you authorize Spotify via /connectspotify ?");
        } else {
            final String response = requestWithRetry(call, accessToken).getContentAsString();
            return clazz == String.class ? (@Nullable T) response : fromJson(response, clazz);
        }
    } catch (final IOException e) {
        throw new SpotifyException(e.getMessage(), e);
    } catch (OAuthException | OAuthResponseException e) {
        throw new SpotifyAuthorizationException(e.getMessage(), e);
    }
}
Also used : Arrays(java.util.Arrays) GET(org.eclipse.jetty.http.HttpMethod.GET) Devices(org.openhab.binding.spotify.internal.api.model.Devices) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) LoggerFactory(org.slf4j.LoggerFactory) OnOffType(org.openhab.core.library.types.OnOffType) Request(org.eclipse.jetty.client.api.Request) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) Function(java.util.function.Function) SPOTIFY_API_PLAYER_URL(org.openhab.binding.spotify.internal.SpotifyBindingConstants.SPOTIFY_API_PLAYER_URL) HttpClient(org.eclipse.jetty.client.HttpClient) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Playlist(org.openhab.binding.spotify.internal.api.model.Playlist) Nullable(org.eclipse.jdt.annotation.Nullable) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) PUT(org.eclipse.jetty.http.HttpMethod.PUT) CurrentlyPlayingContext(org.openhab.binding.spotify.internal.api.model.CurrentlyPlayingContext) NonNullByDefault(org.eclipse.jdt.annotation.NonNullByDefault) SpotifyAuthorizationException(org.openhab.binding.spotify.internal.api.exception.SpotifyAuthorizationException) Logger(org.slf4j.Logger) POST(org.eclipse.jetty.http.HttpMethod.POST) OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) JsonSyntaxException(com.google.gson.JsonSyntaxException) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) ModelUtil(org.openhab.binding.spotify.internal.api.model.ModelUtil) Objects(java.util.Objects) Device(org.openhab.binding.spotify.internal.api.model.Device) SPOTIFY_API_URL(org.openhab.binding.spotify.internal.SpotifyBindingConstants.SPOTIFY_API_URL) List(java.util.List) HttpMethod(org.eclipse.jetty.http.HttpMethod) SpotifyTokenExpiredException(org.openhab.binding.spotify.internal.api.exception.SpotifyTokenExpiredException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) Playlists(org.openhab.binding.spotify.internal.api.model.Playlists) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) SpotifyException(org.openhab.binding.spotify.internal.api.exception.SpotifyException) Collections(java.util.Collections) Me(org.openhab.binding.spotify.internal.api.model.Me) OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) Request(org.eclipse.jetty.client.api.Request) IOException(java.io.IOException) SpotifyException(org.openhab.binding.spotify.internal.api.exception.SpotifyException) HttpClient(org.eclipse.jetty.client.HttpClient) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) SpotifyAuthorizationException(org.openhab.binding.spotify.internal.api.exception.SpotifyAuthorizationException) Nullable(org.eclipse.jdt.annotation.Nullable) Nullable(org.eclipse.jdt.annotation.Nullable)

Aggregations

AccessTokenResponse (org.openhab.core.auth.client.oauth2.AccessTokenResponse)21 IOException (java.io.IOException)19 OAuthException (org.openhab.core.auth.client.oauth2.OAuthException)19 OAuthResponseException (org.openhab.core.auth.client.oauth2.OAuthResponseException)19 OAuthClientService (org.openhab.core.auth.client.oauth2.OAuthClientService)11 Test (org.junit.jupiter.api.Test)7 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)6 OAuthFactory (org.openhab.core.auth.client.oauth2.OAuthFactory)6 Nullable (org.eclipse.jdt.annotation.Nullable)5 Request (org.eclipse.jetty.client.api.Request)5 JsonSyntaxException (com.google.gson.JsonSyntaxException)4 ExecutionException (java.util.concurrent.ExecutionException)4 TimeoutException (java.util.concurrent.TimeoutException)3 NonNullByDefault (org.eclipse.jdt.annotation.NonNullByDefault)3 StringContentProvider (org.eclipse.jetty.client.util.StringContentProvider)3 PrivilegedActionException (java.security.PrivilegedActionException)2 Collections (java.util.Collections)2 List (java.util.List)2 Objects (java.util.Objects)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2