Search in sources :

Example 6 with GsonDecoder

use of feign.gson.GsonDecoder in project carbon-apimgt by wso2.

the class DefaultKeyManagerImpl method updateApplication.

@Override
public OAuthApplicationInfo updateApplication(OAuthApplicationInfo oAuthApplicationInfo) throws KeyManagementException {
    if (log.isDebugEnabled()) {
        log.debug("Updating OAuth2 application with : " + oAuthApplicationInfo.toString());
    }
    String applicationName = oAuthApplicationInfo.getClientName();
    String keyType = (String) oAuthApplicationInfo.getParameter(KeyManagerConstants.APP_KEY_TYPE);
    if (keyType != null) {
        // Derive oauth2 app name based on key type and user input for app name
        applicationName = applicationName + '_' + keyType;
    }
    DCRClientInfo dcrClientInfo = new DCRClientInfo();
    dcrClientInfo.setClientName(applicationName);
    dcrClientInfo.setClientId(oAuthApplicationInfo.getClientId());
    dcrClientInfo.setClientSecret(oAuthApplicationInfo.getClientSecret());
    dcrClientInfo.addCallbackUrl(oAuthApplicationInfo.getCallBackURL());
    dcrClientInfo.setGrantTypes(oAuthApplicationInfo.getGrantTypes());
    Response response = dcrmServiceStub.updateApplication(dcrClientInfo, dcrClientInfo.getClientId());
    if (response == null) {
        throw new KeyManagementException("Error occurred while updating DCR application. Response is null", ExceptionCodes.OAUTH2_APP_UPDATE_FAILED);
    }
    if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
        // 200 - Success
        try {
            OAuthApplicationInfo oAuthApplicationInfoResponse = getOAuthApplicationInfo(response);
            // setting original parameter list
            oAuthApplicationInfoResponse.setParameters(oAuthApplicationInfo.getParameters());
            if (log.isDebugEnabled()) {
                log.debug("OAuth2 application updated: " + oAuthApplicationInfoResponse.toString());
            }
            return oAuthApplicationInfoResponse;
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing the DCR application update response " + "message.", e, ExceptionCodes.OAUTH2_APP_UPDATE_FAILED);
        }
    } else if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_400_BAD_REQUEST) {
        // 400 - Known Error
        try {
            DCRError error = (DCRError) new GsonDecoder().decode(response, DCRError.class);
            throw new KeyManagementException("Error occurred while updating DCR application. Error: " + error.getError() + ". Error Description: " + error.getErrorDescription() + ". Status Code: " + response.status(), ExceptionCodes.OAUTH2_APP_UPDATE_FAILED);
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing the DCR error message.", e, ExceptionCodes.OAUTH2_APP_UPDATE_FAILED);
        }
    } else {
        // Unknown Error
        throw new KeyManagementException("Error occurred while updating DCR application. Error: " + response.body().toString() + " Status Code: " + response.status(), ExceptionCodes.OAUTH2_APP_UPDATE_FAILED);
    }
}
Also used : OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) Response(feign.Response) DCRError(org.wso2.carbon.apimgt.core.auth.dto.DCRError) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) DCRClientInfo(org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException)

Example 7 with GsonDecoder

use of feign.gson.GsonDecoder in project carbon-apimgt by wso2.

the class DefaultKeyManagerImpl method getNewAccessToken.

@Override
public AccessTokenInfo getNewAccessToken(AccessTokenRequest tokenRequest) throws KeyManagementException {
    if (tokenRequest == null) {
        throw new KeyManagementException("No information available to generate Token. AccessTokenRequest is null", ExceptionCodes.INVALID_TOKEN_REQUEST);
    }
    // Call the /revoke only if there's a token to be revoked.
    if (!StringUtils.isEmpty(tokenRequest.getTokenToRevoke())) {
        this.revokeAccessToken(tokenRequest.getTokenToRevoke(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
    }
    // When validity time set to a negative value, a token is considered never to expire.
    if (tokenRequest.getValidityPeriod() == -1L) {
        // Setting a different negative value if the set value is -1 (-1 will be ignored by TokenValidator)
        tokenRequest.setValidityPeriod(-2L);
    }
    Response response;
    try {
        if (KeyManagerConstants.CLIENT_CREDENTIALS_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
            response = oAuth2ServiceStubs.getTokenServiceStub().generateClientCredentialsGrantAccessToken(tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
        } else if (KeyManagerConstants.PASSWORD_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
            response = oAuth2ServiceStubs.getTokenServiceStub().generatePasswordGrantAccessToken(tokenRequest.getResourceOwnerUsername(), tokenRequest.getResourceOwnerPassword(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
        } else if (KeyManagerConstants.AUTHORIZATION_CODE_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
            response = oAuth2ServiceStubs.getTokenServiceStub().generateAuthCodeGrantAccessToken(tokenRequest.getAuthorizationCode(), tokenRequest.getCallbackURI(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
        } else if (KeyManagerConstants.REFRESH_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
            response = oAuth2ServiceStubs.getTokenServiceStub().generateRefreshGrantAccessToken(tokenRequest.getRefreshToken(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
        } else if (KeyManagerConstants.JWT_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
            response = oAuth2ServiceStubs.getTokenServiceStub().generateJWTGrantAccessToken(tokenRequest.getAssertion(), KeyManagerConstants.JWT_GRANT_TYPE, tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
        } else {
            throw new KeyManagementException("Invalid access token request. Unsupported grant type: " + tokenRequest.getGrantType(), ExceptionCodes.INVALID_TOKEN_REQUEST);
        }
    } catch (APIManagementException ex) {
        throw new KeyManagementException("Token generation request failed. Error: " + ex.getMessage(), ex, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
    }
    if (response == null) {
        throw new KeyManagementException("Error occurred while generating an access token. " + "Response is null", ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
    }
    if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
        // 200 - Success
        log.debug("A new access token is successfully generated.");
        try {
            OAuth2TokenInfo oAuth2TokenInfo = (OAuth2TokenInfo) new GsonDecoder().decode(response, OAuth2TokenInfo.class);
            AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
            accessTokenInfo.setAccessToken(oAuth2TokenInfo.getAccessToken());
            accessTokenInfo.setScopes(oAuth2TokenInfo.getScope());
            accessTokenInfo.setRefreshToken(oAuth2TokenInfo.getRefreshToken());
            accessTokenInfo.setIdToken(oAuth2TokenInfo.getIdToken());
            accessTokenInfo.setValidityPeriod(oAuth2TokenInfo.getExpiresIn());
            return accessTokenInfo;
        } catch (IOException e) {
            throw new KeyManagementException("Error occurred while parsing token response", e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
        }
    } else {
        // Error case
        throw new KeyManagementException("Token generation request failed. HTTP error code: " + response.status() + " Error Response Body: " + response.body().toString(), ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
    }
}
Also used : OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) Response(feign.Response) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) OAuth2TokenInfo(org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo)

Example 8 with GsonDecoder

use of feign.gson.GsonDecoder in project mesosFramework by zhizuqiu.

the class EtcdClient method getEnableUrl.

public static String getEnableUrl(List<String> urls) {
    String url;
    Etcd etcd;
    GsonDecoder decoder = new GsonDecoder(GSON);
    GsonEncoder encoder = new GsonEncoder(GSON);
    if (urls == null) {
        return null;
    }
    for (String url1 : urls) {
        url = url1;
        etcd = Feign.builder().encoder(encoder).decoder(decoder).errorDecoder(new EtcdErrorDecoder()).requestInterceptor(new EtcdHeadersInterceptor()).target(Etcd.class, url);
        try {
            etcd.getEtcdVersion();
            return url;
        } catch (Exception e) {
            logger.info("connect url[" + url1 + "] error! message:" + e.getMessage());
        }
    }
    return null;
}
Also used : GsonEncoder(feign.gson.GsonEncoder) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) ClientException(com.chinaunicom.etcd.v2.exception.ClientException) ServerException(com.chinaunicom.etcd.v2.exception.ServerException)

Example 9 with GsonDecoder

use of feign.gson.GsonDecoder in project mesosFramework by zhizuqiu.

the class EtcdClient method getInstance.

public static Etcd getInstance(List<String> urls) {
    if (urls == null) {
        return null;
    }
    Etcd etcd;
    GsonDecoder decoder = new GsonDecoder(GSON);
    GsonEncoder encoder = new GsonEncoder(GSON);
    for (String url : urls) {
        etcd = Feign.builder().encoder(encoder).decoder(decoder).errorDecoder(new EtcdErrorDecoder()).requestInterceptor(new EtcdHeadersInterceptor()).target(Etcd.class, url);
        try {
            etcd.getEtcdVersion();
            return etcd;
        } catch (Exception e) {
            logger.info("connect url[" + url + "] error! message:" + e.getMessage());
        }
    }
    logger.error("get etcd instance error!");
    return null;
}
Also used : GsonEncoder(feign.gson.GsonEncoder) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) ClientException(com.chinaunicom.etcd.v2.exception.ClientException) ServerException(com.chinaunicom.etcd.v2.exception.ServerException)

Example 10 with GsonDecoder

use of feign.gson.GsonDecoder in project feign by OpenFeign.

the class MockClientTest method setup.

@Before
public void setup() throws IOException {
    try (InputStream input = getClass().getResourceAsStream("/fixtures/contributors.json")) {
        byte[] data = toByteArray(input);
        RequestKey postContributorKey = RequestKey.builder(HttpMethod.POST, "/repos/netflix/feign/contributors").charset(UTF_8).headers(RequestHeaders.builder().add("Content-Length", "55").add("Content-Type", "application/json").build()).body("{\"login\":\"velo_at_github\",\"type\":\"preposterous hacker\"}").build();
        mockClient = new MockClient();
        github = Feign.builder().decoder(new AssertionDecoder(new GsonDecoder())).client(mockClient.ok(HttpMethod.GET, "/repos/netflix/feign/contributors", data).ok(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=55").ok(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=7 7", new ByteArrayInputStream(data)).ok(postContributorKey, "{\"login\":\"velo\",\"contributions\":0}").noContent(HttpMethod.PATCH, "/repos/velo/feign-mock/contributors").add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=1234567890", HttpsURLConnection.HTTP_NOT_FOUND).add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", HttpsURLConnection.HTTP_INTERNAL_ERROR, new ByteArrayInputStream(data)).add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", HttpsURLConnection.HTTP_INTERNAL_ERROR, "").add(HttpMethod.GET, "/repos/netflix/feign/contributors?client_id=123456789", HttpsURLConnection.HTTP_INTERNAL_ERROR, data)).target(new MockTarget<>(GitHub.class));
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) GsonDecoder(feign.gson.GsonDecoder) Before(org.junit.Before)

Aggregations

GsonDecoder (feign.gson.GsonDecoder)25 IOException (java.io.IOException)11 Response (feign.Response)9 GsonEncoder (feign.gson.GsonEncoder)9 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)5 DCRClientInfo (org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo)4 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)4 Gson (com.google.gson.Gson)3 GsonBuilder (com.google.gson.GsonBuilder)3 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)3 IdentityProviderException (org.wso2.carbon.apimgt.core.exception.IdentityProviderException)3 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)3 ClientException (com.chinaunicom.etcd.v2.exception.ClientException)2 ServerException (com.chinaunicom.etcd.v2.exception.ServerException)2 Feign (feign.Feign)2 Slf4jLogger (feign.slf4j.Slf4jLogger)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 Before (org.junit.Before)2