Search in sources :

Example 6 with OAuthResponseException

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

the class HydrawiseAccountHandler method configure.

private void configure() {
    HydrawiseAccountConfiguration config = getConfig().as(HydrawiseAccountConfiguration.class);
    try {
        if (!config.userName.isEmpty() && !config.password.isEmpty()) {
            if (!config.savePassword) {
                Configuration editedConfig = editConfiguration();
                editedConfig.remove("password");
                updateConfiguration(editedConfig);
            }
            oAuthService.getAccessTokenByResourceOwnerPasswordCredentials(config.userName, config.password, SCOPE);
        } else if (oAuthService.getAccessTokenResponse() == null) {
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Login credentials required.");
            return;
        }
        this.refresh = Math.max(config.refreshInterval, MIN_REFRESH_SECONDS);
        initPolling(0, refresh);
    } catch (OAuthException | IOException e) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
    } catch (OAuthResponseException e) {
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Login credentials required.");
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) Configuration(org.openhab.core.config.core.Configuration) HydrawiseAccountConfiguration(org.openhab.binding.hydrawise.internal.config.HydrawiseAccountConfiguration) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException) HydrawiseAccountConfiguration(org.openhab.binding.hydrawise.internal.config.HydrawiseAccountConfiguration)

Example 7 with OAuthResponseException

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

the class HydrawiseGraphQLClient method sendGraphQLRequest.

private String sendGraphQLRequest(String content) throws HydrawiseConnectionException, HydrawiseAuthenticationException {
    logger.trace("Sending Request: {}", content);
    ContentResponse response;
    final AtomicInteger responseCode = new AtomicInteger(0);
    final StringBuilder responseMessage = new StringBuilder();
    try {
        AccessTokenResponse token = oAuthService.getAccessTokenResponse();
        if (token == null) {
            throw new HydrawiseAuthenticationException("Login required");
        }
        response = httpClient.newRequest(GRAPH_URL).method(HttpMethod.POST).content(new StringContentProvider(content), "application/json").header("Authorization", token.getTokenType() + " " + token.getAccessToken()).onResponseFailure(new Response.FailureListener() {

            @Override
            public void onFailure(@Nullable Response response, @Nullable Throwable failure) {
                int status = response != null ? response.getStatus() : -1;
                String reason = response != null ? response.getReason() : "Null response";
                logger.trace("onFailure code: {} message: {}", status, reason);
                responseCode.set(status);
                responseMessage.append(reason);
            }
        }).send();
        String stringResponse = response.getContentAsString();
        logger.trace("Received Response: {}", stringResponse);
        return stringResponse;
    } catch (InterruptedException | TimeoutException | OAuthException | IOException e) {
        logger.debug("Could not send request", e);
        throw new HydrawiseConnectionException(e);
    } catch (OAuthResponseException e) {
        throw new HydrawiseAuthenticationException(e.getMessage());
    } catch (ExecutionException e) {
        // this allows us to catch this in a callback and handle accordingly
        switch(responseCode.get()) {
            case 401:
            case 403:
                throw new HydrawiseAuthenticationException(responseMessage.toString());
            default:
                throw new HydrawiseConnectionException(e);
        }
    }
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) OAuthException(org.openhab.core.auth.client.oauth2.OAuthException) IOException(java.io.IOException) MutationResponse(org.openhab.binding.hydrawise.internal.api.graphql.dto.MutationResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) QueryResponse(org.openhab.binding.hydrawise.internal.api.graphql.dto.QueryResponse) HydrawiseConnectionException(org.openhab.binding.hydrawise.internal.api.HydrawiseConnectionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HydrawiseAuthenticationException(org.openhab.binding.hydrawise.internal.api.HydrawiseAuthenticationException) ExecutionException(java.util.concurrent.ExecutionException) AccessTokenResponse(org.openhab.core.auth.client.oauth2.AccessTokenResponse) TimeoutException(java.util.concurrent.TimeoutException)

Example 8 with OAuthResponseException

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

the class OpenHabOAuthTokenRefresherTest method whenTokenRefreshFailsDueToAnIllegalResponseThenTheListenerIsNotNotified.

@Test
public void whenTokenRefreshFailsDueToAnIllegalResponseThenTheListenerIsNotNotified() throws org.openhab.core.auth.client.oauth2.OAuthException, IOException, OAuthResponseException {
    // given:
    OAuthClientService oauthClientService = mock(OAuthClientService.class);
    when(oauthClientService.refreshToken()).thenThrow(new OAuthResponseException());
    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:
    assertThrows(OAuthException.class, () -> {
        try {
            refresher.refreshToken(MieleCloudBindingTestConstants.SERVICE_HANDLE);
        } catch (OAuthException e) {
            verifyNoInteractions(listener);
            throw e;
        }
    });
}
Also used : OAuthResponseException(org.openhab.core.auth.client.oauth2.OAuthResponseException) OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) OAuthFactory(org.openhab.core.auth.client.oauth2.OAuthFactory) Test(org.junit.jupiter.api.Test)

Example 9 with OAuthResponseException

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

the class OpenHabOAuthTokenRefresherTest method whenTokenIsRefreshedAndNoAccessTokenIsProvidedThenTheListenerIsNotNotified.

@Test
public void whenTokenIsRefreshedAndNoAccessTokenIsProvidedThenTheListenerIsNotNotified() throws org.openhab.core.auth.client.oauth2.OAuthException, IOException, OAuthResponseException {
    // given:
    AccessTokenResponse accessTokenResponse = new AccessTokenResponse();
    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:
    assertThrows(OAuthException.class, () -> {
        try {
            refresher.refreshToken(MieleCloudBindingTestConstants.SERVICE_HANDLE);
        } catch (OAuthException e) {
            verifyNoInteractions(listener);
            throw e;
        }
    });
}
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 10 with OAuthResponseException

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

the class OpenHabOAuthTokenRefresherTest method whenTokenRefreshFailsWithOAuthExceptionThenTheListenerIsNotNotified.

@Test
public void whenTokenRefreshFailsWithOAuthExceptionThenTheListenerIsNotNotified() throws org.openhab.core.auth.client.oauth2.OAuthException, IOException, OAuthResponseException {
    // given:
    OAuthClientService oauthClientService = mock(OAuthClientService.class);
    when(oauthClientService.refreshToken()).thenThrow(new org.openhab.core.auth.client.oauth2.OAuthException());
    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:
    assertThrows(OAuthException.class, () -> {
        try {
            refresher.refreshToken(MieleCloudBindingTestConstants.SERVICE_HANDLE);
        } catch (OAuthException e) {
            verifyNoInteractions(listener);
            throw e;
        }
    });
}
Also used : OAuthClientService(org.openhab.core.auth.client.oauth2.OAuthClientService) OAuthFactory(org.openhab.core.auth.client.oauth2.OAuthFactory) Test(org.junit.jupiter.api.Test)

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