Search in sources :

Example 16 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class APILoggerManager method invokeService.

private String invokeService(String path, String tenantDomain) throws IOException, APIManagementException {
    String serviceURLStr = eventHubConfigurationDto.getServiceUrl().concat(APIConstants.INTERNAL_WEB_APP_EP);
    HttpGet method = new HttpGet(serviceURLStr + path);
    URL serviceURL = new URL(serviceURLStr + path);
    byte[] credentials = getServiceCredentials(eventHubConfigurationDto);
    int servicePort = serviceURL.getPort();
    String serviceProtocol = serviceURL.getProtocol();
    method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, StandardCharsets.UTF_8));
    if (tenantDomain != null) {
        method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
    }
    HttpClient httpClient = APIUtil.getHttpClient(servicePort, serviceProtocol);
    HttpResponse httpResponse = null;
    int retryCount = 0;
    boolean retry;
    do {
        try {
            httpResponse = httpClient.execute(method);
            retry = false;
        } catch (IOException ex) {
            retryCount++;
            if (retryCount < RETRIEVAL_RETRIES) {
                retry = true;
                log.warn("Failed retrieving " + path + " from remote endpoint: " + ex.getMessage() + ". Retrying after " + RETRIEVAL_TIMEOUT_IN_SECONDS + " seconds.");
                try {
                    Thread.sleep(RETRIEVAL_TIMEOUT_IN_SECONDS * 1000L);
                } catch (InterruptedException e) {
                // Ignore
                }
            } else {
                throw new APIManagementException("Error while calling internal service", ex);
            }
        }
    } while (retry);
    if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
        log.error("Could not retrieve subscriptions for tenantDomain : " + tenantDomain);
        throw new APIManagementException("Error while retrieving subscription from " + path);
    }
    return EntityUtils.toString(httpResponse.getEntity(), UTF8);
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpGet(org.apache.http.client.methods.HttpGet) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URL(java.net.URL)

Example 17 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class EndpointCertificateDeployer method invokeService.

private CloseableHttpResponse invokeService(String endpoint, String tenantDomain) throws IOException, ArtifactSynchronizerException {
    HttpGet method = new HttpGet(endpoint);
    URL url = new URL(endpoint);
    String username = eventHubConfigurationDto.getUsername();
    String password = eventHubConfigurationDto.getPassword();
    byte[] credentials = Base64.encodeBase64((username + APIConstants.DELEM_COLON + password).getBytes(APIConstants.DigestAuthConstants.CHARSET));
    int port = url.getPort();
    String protocol = url.getProtocol();
    method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, APIConstants.DigestAuthConstants.CHARSET));
    if (tenantDomain != null) {
        method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
    }
    HttpClient httpClient = APIUtil.getHttpClient(port, protocol);
    try {
        return APIUtil.executeHTTPRequest(method, httpClient);
    } catch (APIManagementException e) {
        throw new ArtifactSynchronizerException(e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) HttpGet(org.apache.http.client.methods.HttpGet) HttpClient(org.apache.http.client.HttpClient) URL(java.net.URL)

Example 18 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class SystemApplicationDAO method getApplications.

/**
 * Method to retrieve all the system Applications for the given tenant
 *
 * @param tenantDomain required parameter
 * @return SystemApplicationDTO which hold the retrieved client credentials
 * @throws APIMgtDAOException
 */
public SystemApplicationDTO[] getApplications(String tenantDomain) throws APIMgtDAOException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    SystemApplicationDTO systemApplicationDTO = null;
    List<SystemApplicationDTO> systemApplicationDTOS = new ArrayList<>();
    String getCredentialsQuery = SQLConstants.SystemApplicationConstants.GET_APPLICATIONS;
    try {
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        connection.commit();
        preparedStatement = connection.prepareStatement(getCredentialsQuery);
        preparedStatement.setString(1, tenantDomain);
        resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            systemApplicationDTO = new SystemApplicationDTO();
            systemApplicationDTO.setName(resultSet.getString("NAME"));
            systemApplicationDTO.setConsumerKey(resultSet.getString("CONSUMER_KEY"));
            systemApplicationDTO.setConsumerSecret(resultSet.getString("CONSUMER_SECRET"));
            systemApplicationDTOS.add(systemApplicationDTO);
        }
    } catch (SQLException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while retrieving system applications for tenant: " + tenantDomain);
        }
        handleException("Error while retrieving system applications for tenant: " + tenantDomain, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
    }
    return systemApplicationDTOS.toArray(new SystemApplicationDTO[systemApplicationDTOS.size()]);
}
Also used : SQLException(java.sql.SQLException) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement)

Example 19 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class APIManagerConfiguration method readChildElements.

private void readChildElements(OMElement serverConfig, Stack<String> nameStack) throws APIManagementException {
    for (Iterator childElements = serverConfig.getChildElements(); childElements.hasNext(); ) {
        OMElement element = (OMElement) childElements.next();
        String localName = element.getLocalName();
        nameStack.push(localName);
        if ("APIKeyValidator".equals(localName)) {
            OMElement keyManagerServiceUrl = element.getFirstChildWithName(new QName(APIConstants.AUTHSERVER_URL));
            if (keyManagerServiceUrl != null) {
                String serviceUrl = keyManagerServiceUrl.getText();
                addKeyManagerConfigsAsSystemProperties(APIUtil.replaceSystemProperty(serviceUrl));
            }
        } else if (TOKEN_REVOCATION_NOTIFIERS.equals(localName)) {
            tokenRevocationClassName = element.getAttributeValue(new QName("class"));
        } else if (REALTIME_NOTIFIER.equals(localName)) {
            Iterator revocationPropertiesIterator = element.getChildrenWithLocalName("Property");
            Properties properties = new Properties();
            while (revocationPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) revocationPropertiesIterator.next();
                properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
            }
            realtimeNotifierProperties = properties;
        } else if (PERSISTENT_NOTIFIER.equals(localName)) {
            Iterator revocationPropertiesIterator = element.getChildrenWithLocalName("Property");
            Properties properties = new Properties();
            while (revocationPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) revocationPropertiesIterator.next();
                if (propertyElem.getAttributeValue(new QName("name")).equalsIgnoreCase("password")) {
                    if (secretResolver.isInitialized() && secretResolver.isTokenProtected(TOKEN_REVOCATION_NOTIFIERS_PASSWORD)) {
                        properties.setProperty(propertyElem.getAttributeValue(new QName("name")), secretResolver.resolve(TOKEN_REVOCATION_NOTIFIERS_PASSWORD));
                    } else {
                        properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
                    }
                } else {
                    properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
                }
            }
            persistentNotifierProperties = properties;
        } else if ("Analytics".equals(localName)) {
            OMElement properties = element.getFirstChildWithName(new QName("Properties"));
            Iterator analyticsPropertiesIterator = properties.getChildrenWithLocalName("Property");
            Map<String, String> analyticsProps = new HashMap<>();
            while (analyticsPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) analyticsPropertiesIterator.next();
                String name = propertyElem.getAttributeValue(new QName("name"));
                String value = propertyElem.getText();
                analyticsProps.put(name, value);
            }
            OMElement authTokenElement = element.getFirstChildWithName(new QName("AuthToken"));
            String resolvedAuthToken = MiscellaneousUtil.resolve(authTokenElement, secretResolver);
            analyticsProps.put("auth.api.token", resolvedAuthToken);
            analyticsProperties = analyticsProps;
        } else if ("PersistenceConfigs".equals(localName)) {
            OMElement properties = element.getFirstChildWithName(new QName("Properties"));
            Iterator analyticsPropertiesIterator = properties.getChildrenWithLocalName("Property");
            Map<String, String> persistenceProps = new HashMap<>();
            while (analyticsPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) analyticsPropertiesIterator.next();
                String name = propertyElem.getAttributeValue(new QName("name"));
                String value = propertyElem.getText();
                persistenceProps.put(name, value);
            }
            persistenceProperties = persistenceProps;
        } else if (APIConstants.REDIS_CONFIG.equals(localName)) {
            OMElement redisHost = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_HOST));
            OMElement redisPort = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PORT));
            OMElement redisUser = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_USER));
            OMElement redisPassword = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PASSWORD));
            OMElement redisDatabaseId = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_DATABASE_ID));
            OMElement redisConnectionTimeout = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_CONNECTION_TIMEOUT));
            OMElement redisIsSslEnabled = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_IS_SSL_ENABLED));
            OMElement propertiesElement = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PROPERTIES));
            redisConfig.setRedisEnabled(true);
            redisConfig.setHost(redisHost.getText());
            redisConfig.setPort(Integer.parseInt(redisPort.getText()));
            if (redisUser != null && redisPassword != null && redisDatabaseId != null && redisConnectionTimeout != null && redisIsSslEnabled != null) {
                redisConfig.setUser(redisUser.getText());
                redisConfig.setPassword(MiscellaneousUtil.resolve(redisPassword, secretResolver).toCharArray());
                redisConfig.setDatabaseId(Integer.parseInt(redisDatabaseId.getText()));
                redisConfig.setConnectionTimeout(Integer.parseInt(redisConnectionTimeout.getText()));
                redisConfig.setSslEnabled(Boolean.parseBoolean(redisIsSslEnabled.getText()));
            }
            if (propertiesElement != null) {
                Iterator<OMElement> properties = propertiesElement.getChildElements();
                if (properties != null) {
                    while (properties.hasNext()) {
                        OMElement propertyNode = properties.next();
                        if (APIConstants.CONFIG_REDIS_MAX_TOTAL.equals(propertyNode.getLocalName())) {
                            redisConfig.setMaxTotal(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MAX_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setMaxIdle(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MIN_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setMinIdle(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_ON_BORROW.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestOnBorrow(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_ON_RETURN.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestOnReturn(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_WHILE_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestWhileIdle(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_BLOCK_WHEN_EXHAUSTED.equals(propertyNode.getLocalName())) {
                            redisConfig.setBlockWhenExhausted(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MIN_EVICTABLE_IDLE_TIME_IN_MILLIS.equals(propertyNode.getLocalName())) {
                            redisConfig.setMinEvictableIdleTimeMillis(Long.parseLong(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TIME_BETWEEN_EVICTION_RUNS_IN_MILLIS.equals(propertyNode.getLocalName())) {
                            redisConfig.setTimeBetweenEvictionRunsMillis(Long.parseLong(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_NUM_TESTS_PER_EVICTION_RUNS.equals(propertyNode.getLocalName())) {
                            redisConfig.setNumTestsPerEvictionRun(Integer.parseInt(propertyNode.getText()));
                        }
                    }
                }
            }
        } else if (elementHasText(element)) {
            String key = getKey(nameStack);
            String value = MiscellaneousUtil.resolve(element, secretResolver);
            addToConfiguration(key, APIUtil.replaceSystemProperty(value));
        } else if ("Environments".equals(localName)) {
            Iterator environmentIterator = element.getChildrenWithLocalName("Environment");
            apiGatewayEnvironments = new LinkedHashMap<String, Environment>();
            while (environmentIterator.hasNext()) {
                OMElement environmentElem = (OMElement) environmentIterator.next();
                setEnvironmentConfig(environmentElem);
            }
        } else if (APIConstants.EXTERNAL_API_STORES.equals(localName)) {
            // Initialize 'externalAPIStores' config elements
            Iterator apistoreIterator = element.getChildrenWithLocalName("ExternalAPIStore");
            externalAPIStores = new HashSet<APIStore>();
            while (apistoreIterator.hasNext()) {
                APIStore store = new APIStore();
                OMElement storeElem = (OMElement) apistoreIterator.next();
                String type = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_TYPE));
                // Set Store type [eg:wso2]
                store.setType(type);
                String className = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_CLASS_NAME));
                try {
                    store.setPublisher((APIPublisher) APIUtil.getClassInstance(className));
                } catch (InstantiationException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be instantiated";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                } catch (IllegalAccessException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be access";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                } catch (ClassNotFoundException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be found";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                }
                String name = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_ID));
                if (name == null) {
                    log.error("The ExternalAPIStore name attribute is not defined in api-manager.xml.");
                }
                // Set store name
                store.setName(name);
                OMElement configDisplayName = storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_DISPLAY_NAME));
                String displayName = (configDisplayName != null) ? APIUtil.replaceSystemProperty(configDisplayName.getText()) : name;
                // Set store display name
                store.setDisplayName(displayName);
                store.setEndpoint(APIUtil.replaceSystemProperty(storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_ENDPOINT)).getText()));
                store.setPublished(false);
                if (APIConstants.WSO2_API_STORE_TYPE.equals(type)) {
                    OMElement password = storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_PASSWORD));
                    if (password != null) {
                        String value = MiscellaneousUtil.resolve(password, secretResolver);
                        store.setPassword(APIUtil.replaceSystemProperty(value));
                        store.setUsername(APIUtil.replaceSystemProperty(storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_USERNAME)).getText()));
                    } else {
                        log.error("The user-credentials of API Publisher is not defined in the <ExternalAPIStore> " + "config of api-manager.xml.");
                    }
                }
                externalAPIStores.add(store);
            }
        } else if (APIConstants.LOGIN_CONFIGS.equals(localName)) {
            Iterator loginConfigIterator = element.getChildrenWithLocalName(APIConstants.LOGIN_CONFIGS);
            while (loginConfigIterator.hasNext()) {
                OMElement loginOMElement = (OMElement) loginConfigIterator.next();
                parseLoginConfig(loginOMElement);
            }
        } else if (APIConstants.AdvancedThrottleConstants.THROTTLING_CONFIGURATIONS.equals(localName)) {
            setThrottleProperties(serverConfig);
        } else if (APIConstants.WorkflowConfigConstants.WORKFLOW.equals(localName)) {
            setWorkflowProperties(serverConfig);
        } else if (APIConstants.ApplicationAttributes.APPLICATION_ATTRIBUTES.equals(localName)) {
            Iterator iterator = element.getChildrenWithLocalName(APIConstants.ApplicationAttributes.ATTRIBUTE);
            while (iterator.hasNext()) {
                OMElement omElement = (OMElement) iterator.next();
                Iterator attributes = omElement.getChildElements();
                JSONObject jsonObject = new JSONObject();
                boolean isHidden = Boolean.parseBoolean(omElement.getAttributeValue(new QName(APIConstants.ApplicationAttributes.HIDDEN)));
                boolean isRequired = Boolean.parseBoolean(omElement.getAttributeValue(new QName(APIConstants.ApplicationAttributes.REQUIRED)));
                jsonObject.put(APIConstants.ApplicationAttributes.HIDDEN, isHidden);
                while (attributes.hasNext()) {
                    OMElement attribute = (OMElement) attributes.next();
                    if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.NAME)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.ATTRIBUTE, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.DESCRIPTION)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.DESCRIPTION, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.TOOLTIP)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.TOOLTIP, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.TYPE)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.TYPE, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.DEFAULT) && isRequired) {
                        jsonObject.put(APIConstants.ApplicationAttributes.DEFAULT, attribute.getText());
                    }
                }
                if (isHidden && isRequired && !jsonObject.containsKey(APIConstants.ApplicationAttributes.DEFAULT)) {
                    log.error("A default value needs to be given for required, hidden application attributes.");
                }
                jsonObject.put(APIConstants.ApplicationAttributes.REQUIRED, isRequired);
                applicationAttributes.add(jsonObject);
            }
        } else if (APIConstants.Monetization.MONETIZATION_CONFIG.equals(localName)) {
            OMElement additionalAttributes = element.getFirstChildWithName(new QName(APIConstants.Monetization.ADDITIONAL_ATTRIBUTES));
            if (additionalAttributes != null) {
                setMonetizationAdditionalAttributes(additionalAttributes);
            }
        } else if (APIConstants.JWT_CONFIGS.equals(localName)) {
            setJWTConfiguration(element);
        } else if (APIConstants.TOKEN_ISSUERS.equals(localName)) {
            setJWTTokenIssuers(element);
        } else if (APIConstants.API_RECOMMENDATION.equals(localName)) {
            setRecommendationConfigurations(element);
        } else if (APIConstants.GlobalCacheInvalidation.GLOBAL_CACHE_INVALIDATION.equals(localName)) {
            setGlobalCacheInvalidationConfiguration(element);
        } else if (APIConstants.KeyManager.EVENT_HUB_CONFIGURATIONS.equals(localName)) {
            setEventHubConfiguration(element);
        } else if (APIConstants.GatewayArtifactSynchronizer.SYNC_RUNTIME_ARTIFACTS_PUBLISHER_CONFIG.equals(localName)) {
            setRuntimeArtifactsSyncPublisherConfig(element);
        } else if (APIConstants.GatewayArtifactSynchronizer.SYNC_RUNTIME_ARTIFACTS_GATEWAY_CONFIG.equals(localName)) {
            setRuntimeArtifactsSyncGatewayConfig(element);
        } else if (APIConstants.SkipListConstants.SKIP_LIST_CONFIG.equals(localName)) {
            setSkipListConfigurations(element);
        } else if (APIConstants.ExtensionListenerConstants.EXTENSION_LISTENERS.equals(localName)) {
            setExtensionListenerConfigurations(element);
        } else if (APIConstants.JWT_AUDIENCES.equals(localName)) {
            setRestApiJWTAuthAudiences(element);
        }
        readChildElements(element, nameStack);
        nameStack.pop();
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) GatewayArtifactSynchronizerProperties(org.wso2.carbon.apimgt.impl.dto.GatewayArtifactSynchronizerProperties) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) Properties(java.util.Properties) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) Iterator(java.util.Iterator) Environment(org.wso2.carbon.apimgt.api.model.Environment) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) APIPublisher(org.wso2.carbon.apimgt.api.model.APIPublisher) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet) APIStore(org.wso2.carbon.apimgt.api.model.APIStore)

Example 20 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testCreateApplication.

@Test
public void testCreateApplication() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    // happy path - 201
    // //request object to key manager
    List<String> grantTypesList = new ArrayList<>();
    grantTypesList.add("password");
    grantTypesList.add("client-credentials");
    OAuthAppRequest oauthAppRequest = new OAuthAppRequest("app1", "https://sample.callback/url", "PRODUCTION", grantTypesList);
    // //request object to dcr api
    DCRClientInfo dcrClientInfo = new DCRClientInfo();
    dcrClientInfo.setClientName(oauthAppRequest.getClientName() + '_' + oauthAppRequest.getKeyType());
    dcrClientInfo.setGrantTypes(oauthAppRequest.getGrantTypes());
    dcrClientInfo.addCallbackUrl(oauthAppRequest.getCallBackURL());
    /*
        dcrClientInfo.setUserinfoSignedResponseAlg(ServiceReferenceHolder.getInstance().getAPIMConfiguration()
                .getKeyManagerConfigs().getOidcUserinfoJWTSigningAlgo());
*/
    // //mocked response object from dcr api
    DCRClientInfo dcrClientInfoResponse = new DCRClientInfo();
    dcrClientInfoResponse.setClientName(oauthAppRequest.getClientName());
    dcrClientInfoResponse.setGrantTypes(oauthAppRequest.getGrantTypes());
    dcrClientInfoResponse.addCallbackUrl(oauthAppRequest.getCallBackURL());
    /*
        dcrClientInfoResponse.setUserinfoSignedResponseAlg(ServiceReferenceHolder.getInstance().getAPIMConfiguration()
                .getKeyManagerConfigs().getOidcUserinfoJWTSigningAlgo());
*/
    dcrClientInfoResponse.setClientId("xxx-xxx-xxx-xxx");
    dcrClientInfoResponse.setClientSecret("yyy-yyy-yyy-yyy");
    dcrClientInfoResponse.setClientIdIssuedAt("now");
    dcrClientInfoResponse.setClientSecretExpiresAt("future");
    dcrClientInfoResponse.setRegistrationClientUri("https://localhost:9443/oauth/xxx-xxx-xxx-xxx");
    // //expected response object from key manager
    OAuthApplicationInfo oAuthApplicationInfoResponse = new OAuthApplicationInfo();
    oAuthApplicationInfoResponse.setClientName(dcrClientInfoResponse.getClientName());
    oAuthApplicationInfoResponse.setGrantTypes(dcrClientInfoResponse.getGrantTypes());
    oAuthApplicationInfoResponse.setCallBackURL(dcrClientInfoResponse.getRedirectURIs().get(0));
    oAuthApplicationInfoResponse.setClientId(dcrClientInfoResponse.getClientId());
    oAuthApplicationInfoResponse.setClientSecret(dcrClientInfoResponse.getClientSecret());
    Response dcrResponse = Response.builder().status(201).headers(new HashMap<>()).body(new Gson().toJson(dcrClientInfoResponse), feign.Util.UTF_8).build();
    Mockito.when(dcrmServiceStub.registerApplication(dcrClientInfo)).thenReturn(dcrResponse);
    try {
        OAuthApplicationInfo app = kmImpl.createApplication(oauthAppRequest);
        Assert.assertEquals(app, oAuthApplicationInfoResponse);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - 400
    int errorSc = 400;
    String errorMsg = "{\"error\": \"invalid_redirect_uri\", \"error_description\": \"One or more " + "redirect_uri values are invalid\"}";
    Response errorResponse = Response.builder().status(errorSc).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.registerApplication(any(DCRClientInfo.class))).thenReturn(errorResponse);
    try {
        kmImpl.createApplication(oauthAppRequest);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while DCR application creation."));
    }
    // error case - non-400
    errorSc = 500;
    errorMsg = "unknown error occurred";
    errorResponse = Response.builder().status(errorSc).headers(new HashMap<>()).body(errorMsg.getBytes()).build();
    Mockito.when(dcrmServiceStub.registerApplication(any(DCRClientInfo.class))).thenReturn(errorResponse);
    try {
        kmImpl.createApplication(oauthAppRequest);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Error occurred while DCR application creation."));
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) OAuth2ServiceStubs(org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) OAuthAppRequest(org.wso2.carbon.apimgt.core.models.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) DCRClientInfo(org.wso2.carbon.apimgt.core.auth.dto.DCRClientInfo) Test(org.testng.annotations.Test)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)18 HttpClient (org.apache.http.client.HttpClient)12 URL (java.net.URL)10 ArrayList (java.util.ArrayList)9 HttpGet (org.apache.http.client.methods.HttpGet)9 IOException (java.io.IOException)8 HashMap (java.util.HashMap)8 HttpResponse (org.apache.http.HttpResponse)8 Gson (com.google.gson.Gson)6 JSONObject (org.json.simple.JSONObject)6 Test (org.junit.Test)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 Test (org.testng.annotations.Test)6 Response (feign.Response)4 WorkflowProperties (org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)4 JSONParser (org.json.simple.parser.JSONParser)3 ParseException (org.json.simple.parser.ParseException)3 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)3 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)3 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)3