Search in sources :

Example 1 with ApplicationInfo

use of org.wso2.carbon.apimgt.api.model.ApplicationInfo in project carbon-apimgt by wso2.

the class ApiMgtDAO method getLightweightApplicationByConsumerKey.

public ApplicationInfo getLightweightApplicationByConsumerKey(String consumerKey) throws APIManagementException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    try {
        connection = APIMgtDBUtil.getConnection();
        String query = SQLConstants.GET_APPLICATION_INFO_BY_CK;
        prepStmt = connection.prepareStatement(query);
        prepStmt.setString(1, consumerKey);
        rs = prepStmt.executeQuery();
        if (rs.next()) {
            ApplicationInfo applicationInfo = new ApplicationInfo();
            applicationInfo.setName(rs.getString("NAME"));
            applicationInfo.setUuid(rs.getString("UUID"));
            applicationInfo.setOrganizationId(rs.getString("ORGANIZATION"));
            applicationInfo.setOwner(rs.getString("OWNER"));
            return applicationInfo;
        }
    } catch (SQLException e) {
        handleException("Error while obtaining organisation of the application for client id " + consumerKey, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
    }
    return null;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ApplicationInfo(org.wso2.carbon.apimgt.api.model.ApplicationInfo) PreparedStatement(java.sql.PreparedStatement)

Example 2 with ApplicationInfo

use of org.wso2.carbon.apimgt.api.model.ApplicationInfo in project carbon-apimgt by wso2.

the class AbstractKeyManagerTestCase method buildFromJSONTest.

@Test
public void buildFromJSONTest() throws APIManagementException {
    AbstractKeyManager keyManager = new AMDefaultKeyManagerImpl();
    KeyManagerConnectorConfiguration keyManagerConnectorConfiguration = Mockito.mock(DefaultKeyManagerConnectorConfiguration.class);
    ServiceReferenceHolder serviceReferenceHolder = PowerMockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getKeyManagerConnectorConfiguration(APIConstants.KeyManager.DEFAULT_KEY_MANAGER_TYPE)).thenReturn(keyManagerConnectorConfiguration);
    // test with empty json payload
    assertNotNull(keyManager.buildFromJSON(new OAuthApplicationInfo(), "{}"));
    // test with valid json
    String jsonPayload2 = "{ \"callbackUrl\": \"www.google.lk\", \"client_id\": \"XBPcXSfGK47WiEX7enchoP2Dcvga\"," + "\"client_secret\": \"4UD8VX8NaQMtrHCwqzI1tHJLPoca\", \"owner\": \"admin\", \"grantType\": \"password" + "  refresh_token\", " + "\"validityPeriod\": \"3600\" }";
    OAuthApplicationInfo oAuthApplicationInfo1 = keyManager.buildFromJSON(new OAuthApplicationInfo(), jsonPayload2);
    assertEquals("XBPcXSfGK47WiEX7enchoP2Dcvga", oAuthApplicationInfo1.getClientId());
    // test with invalid json
    try {
        keyManager.buildFromJSON(new OAuthApplicationInfo(), "{invalid}");
        assertTrue(false);
    } catch (APIManagementException e) {
        assertEquals("Error occurred while parsing JSON String", e.getMessage());
    }
    // test with invalid additionalProperties
    OAuthApplicationInfo applicationInfo = new OAuthApplicationInfo();
    applicationInfo.addParameter("additionalProperties", "{invalid}");
    try {
        keyManager.buildFromJSON(applicationInfo, "{}");
        fail();
    } catch (APIManagementException e) {
        assertEquals("Error while parsing the addition properties of OAuth application", e.getMessage());
    }
}
Also used : KeyManagerConnectorConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration) ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) Test(org.junit.Test) ModelKeyManagerForTest(org.wso2.carbon.apimgt.impl.factory.ModelKeyManagerForTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 3 with ApplicationInfo

use of org.wso2.carbon.apimgt.api.model.ApplicationInfo in project carbon-apimgt by wso2.

the class RegistrationServiceImpl method createApplication.

/**
 * Create a new client application
 *
 * @param appRequest OAuthAppRequest object with client's payload content
 * @return created Application
 * @throws APIKeyMgtException if failed to create the a new application
 */
private OAuthApplicationInfo createApplication(String applicationName, OAuthAppRequest appRequest, String grantType) throws APIManagementException {
    String userName;
    OAuthApplicationInfo applicationInfo = appRequest.getOAuthApplicationInfo();
    String appName = applicationInfo.getClientName();
    String userId = (String) applicationInfo.getParameter(OAUTH_CLIENT_USERNAME);
    boolean isTenantFlowStarted = false;
    if (userId == null || userId.isEmpty()) {
        return null;
    }
    userName = MultitenantUtils.getTenantAwareUsername(userId);
    String tenantDomain = MultitenantUtils.getTenantDomain(userId);
    try {
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
        }
        // Creating the service provider
        ServiceProvider serviceProvider = new ServiceProvider();
        serviceProvider.setApplicationName(applicationName);
        serviceProvider.setDescription("Service Provider for application " + appName);
        serviceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
        ServiceProviderProperty[] serviceProviderProperties = new ServiceProviderProperty[4];
        ServiceProviderProperty serviceProviderProperty = new ServiceProviderProperty();
        serviceProviderProperty.setName(APP_DISPLAY_NAME);
        serviceProviderProperty.setValue(applicationName);
        serviceProviderProperties[0] = serviceProviderProperty;
        ServiceProviderProperty tokenTypeProviderProperty = new ServiceProviderProperty();
        tokenTypeProviderProperty.setName(APIConstants.APP_TOKEN_TYPE);
        tokenTypeProviderProperty.setValue(applicationInfo.getTokenType());
        serviceProviderProperties[1] = tokenTypeProviderProperty;
        ServiceProviderProperty consentProperty = new ServiceProviderProperty();
        consentProperty.setDisplayName(APIConstants.APP_SKIP_CONSENT_DISPLAY);
        consentProperty.setName(APIConstants.APP_SKIP_CONSENT_NAME);
        consentProperty.setValue(APIConstants.APP_SKIP_CONSENT_VALUE);
        serviceProviderProperties[2] = consentProperty;
        ServiceProviderProperty logoutConsentProperty = new ServiceProviderProperty();
        logoutConsentProperty.setDisplayName(APIConstants.APP_SKIP_LOGOUT_CONSENT_DISPLAY);
        logoutConsentProperty.setName(APIConstants.APP_SKIP_LOGOUT_CONSENT_NAME);
        logoutConsentProperty.setValue(APIConstants.APP_SKIP_LOGOUT_CONSENT_VALUE);
        serviceProviderProperties[3] = logoutConsentProperty;
        serviceProvider.setSpProperties(serviceProviderProperties);
        ApplicationManagementService appMgtService = ApplicationManagementService.getInstance();
        appMgtService.createApplication(serviceProvider, tenantDomain, userName);
        // Retrieving the created service provider
        ServiceProvider createdServiceProvider = appMgtService.getApplicationExcludingFileBasedSPs(applicationName, tenantDomain);
        if (createdServiceProvider == null) {
            throw new APIManagementException("Error occurred while creating Service Provider " + "Application" + appName);
        }
        // creating the OAuth app
        OAuthConsumerAppDTO createdOauthApp = this.createOAuthApp(applicationName, applicationInfo, grantType, userName);
        // Set the OAuthApp in InboundAuthenticationConfig
        InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig();
        InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = new InboundAuthenticationRequestConfig[1];
        InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new InboundAuthenticationRequestConfig();
        String oAuthType = APIConstants.SWAGGER_12_OAUTH2;
        inboundAuthenticationRequestConfig.setInboundAuthType(oAuthType);
        inboundAuthenticationRequestConfig.setInboundAuthKey(createdOauthApp.getOauthConsumerKey());
        String oauthConsumerSecret = createdOauthApp.getOauthConsumerSecret();
        if (oauthConsumerSecret != null && !oauthConsumerSecret.isEmpty()) {
            Property property = new Property();
            property.setName(ApplicationConstants.INBOUNT_AUTH_CONSUMER_SECRET);
            property.setValue(oauthConsumerSecret);
            Property[] properties = { property };
            inboundAuthenticationRequestConfig.setProperties(properties);
        }
        inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig;
        inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs(inboundAuthenticationRequestConfigs);
        createdServiceProvider.setInboundAuthenticationConfig(inboundAuthenticationConfig);
        // Setting the SaasApplication attribute to created service provider
        createdServiceProvider.setSaasApp(applicationInfo.getIsSaasApplication());
        createdServiceProvider.setSpProperties(serviceProviderProperties);
        // Updating the service provider with Inbound Authentication Configs and SaasApplication
        appMgtService.updateApplication(createdServiceProvider, tenantDomain, userName);
        Map<String, String> valueMap = new HashMap<String, String>();
        valueMap.put(OAUTH_REDIRECT_URIS, createdOauthApp.getCallbackUrl());
        valueMap.put(OAUTH_CLIENT_NAME, createdOauthApp.getApplicationName());
        valueMap.put(OAUTH_CLIENT_GRANT, createdOauthApp.getGrantTypes());
        return this.fromAppDTOToApplicationInfo(createdOauthApp.getOauthConsumerKey(), applicationName, createdOauthApp.getCallbackUrl(), createdOauthApp.getOauthConsumerSecret(), createdServiceProvider.isSaasApp(), userId, valueMap);
    } catch (IdentityApplicationManagementException e) {
        log.error("Error occurred while creating the client application " + appName, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.getThreadLocalCarbonContext().endTenantFlow();
        }
    }
    return null;
}
Also used : InboundAuthenticationConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig) HashMap(java.util.HashMap) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) InboundAuthenticationRequestConfig(org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ApplicationManagementService(org.wso2.carbon.identity.application.mgt.ApplicationManagementService) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) Property(org.wso2.carbon.identity.application.common.model.Property)

Example 4 with ApplicationInfo

use of org.wso2.carbon.apimgt.api.model.ApplicationInfo in project carbon-apimgt by wso2.

the class RegistrationServiceImpl method createOAuthApp.

/**
 * Method to create a OAuth App with client credentials
 *
 * @param appName    application name
 * @param grantTypes grant types
 * @param userName   username of the application
 * @return created Oauth App
 */
private OAuthConsumerAppDTO createOAuthApp(String appName, OAuthApplicationInfo applicationInfo, String grantTypes, String userName) {
    OAuthConsumerAppDTO createdApp = null;
    OAuthAdminService oauthAdminService = new OAuthAdminService();
    OAuthConsumerAppDTO oauthConsumerAppDTO = new OAuthConsumerAppDTO();
    oauthConsumerAppDTO.setApplicationName(appName);
    if (StringUtils.isNotBlank(applicationInfo.getCallBackURL())) {
        oauthConsumerAppDTO.setCallbackUrl(applicationInfo.getCallBackURL());
    }
    oauthConsumerAppDTO.setUsername(userName);
    oauthConsumerAppDTO.setOAuthVersion(OAuthConstants.OAuthVersions.VERSION_2);
    oauthConsumerAppDTO.setGrantTypes(grantTypes.trim());
    try {
        boolean isHashDisabled = OAuth2Util.isHashDisabled();
        if (isHashDisabled) {
            // Creating the Oauth app
            oauthAdminService.registerOAuthApplicationData(oauthConsumerAppDTO);
            // Retrieving the created OAuth application
            createdApp = oauthAdminService.getOAuthApplicationDataByAppName(oauthConsumerAppDTO.getApplicationName());
        } else {
            createdApp = oauthAdminService.registerAndRetrieveOAuthApplicationData(oauthConsumerAppDTO);
        }
    } catch (IdentityOAuthAdminException e) {
        log.error("Error occurred while creating the OAuth app", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Created OAuth App " + appName);
    }
    return createdApp;
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) OAuthAdminService(org.wso2.carbon.identity.oauth.OAuthAdminService) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO)

Example 5 with ApplicationInfo

use of org.wso2.carbon.apimgt.api.model.ApplicationInfo in project carbon-apimgt by wso2.

the class APIConsumerImpl method requestApprovalForApplicationRegistration.

/**
 * This method specifically implemented for REST API by removing application and data access logic
 * from host object layer. So as per new implementation we need to pass requested scopes to this method
 * as tokenScope. So we will do scope related other logic here in this method.
 * So host object should only pass required 9 parameters.
 */
@Override
public Map<String, Object> requestApprovalForApplicationRegistration(String userId, Application application, String tokenType, String callbackUrl, String[] allowedDomains, String validityTime, String tokenScope, String jsonString, String keyManagerName, String tenantDomain, boolean isImportMode) throws APIManagementException {
    boolean isTenantFlowStarted = false;
    if (StringUtils.isEmpty(tenantDomain)) {
        tenantDomain = MultitenantUtils.getTenantDomain(userId);
    } else {
        int tenantId = APIUtil.getInternalOrganizationId(tenantDomain);
        // To handle choreo scenario.
        if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
    }
    String keyManagerId = null;
    if (keyManagerName != null) {
        KeyManagerConfigurationDTO keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByName(tenantDomain, keyManagerName);
        if (keyManagerConfiguration == null) {
            keyManagerConfiguration = apiMgtDAO.getKeyManagerConfigurationByUUID(keyManagerName);
            if (keyManagerConfiguration != null) {
                keyManagerId = keyManagerName;
                keyManagerName = keyManagerConfiguration.getName();
            }
        } else {
            keyManagerId = keyManagerConfiguration.getUuid();
        }
        if (keyManagerConfiguration == null || !keyManagerConfiguration.isEnabled()) {
            throw new APIManagementException("Key Manager " + keyManagerName + " doesn't exist in Tenant " + tenantDomain, ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
        }
        if (KeyManagerConfiguration.TokenType.EXCHANGED.toString().equals(keyManagerConfiguration.getTokenType())) {
            throw new APIManagementException("Key Manager " + keyManagerName + " doesn't support to generate" + " Client Application", ExceptionCodes.KEY_MANAGER_NOT_SUPPORT_OAUTH_APP_CREATION);
        }
        Object enableOauthAppCreation = keyManagerConfiguration.getProperty(APIConstants.KeyManager.ENABLE_OAUTH_APP_CREATION);
        if (enableOauthAppCreation != null && !(Boolean) enableOauthAppCreation) {
            if (isImportMode) {
                log.debug("Importing application when KM OAuth App creation is disabled. Trying to map keys");
                // in the `jsonString` and ApplicationUtils#createOauthAppRequest logic handles it.
                return mapExistingOAuthClient(jsonString, userId, null, application.getName(), tokenType, APIConstants.DEFAULT_TOKEN_TYPE, keyManagerName, tenantDomain);
            } else {
                throw new APIManagementException("Key Manager " + keyManagerName + " doesn't support to generate" + " Client Application", ExceptionCodes.KEY_MANAGER_NOT_SUPPORT_OAUTH_APP_CREATION);
            }
        }
    }
    try {
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = startTenantFlowForTenantDomain(tenantDomain);
        }
        // check if there are any existing key mappings set for the application and the key manager.
        if (apiMgtDAO.isKeyMappingExistsForApplication(application.getId(), keyManagerName, keyManagerId, tokenType)) {
            throw new APIManagementException("Key Mappings already exists for application " + application.getName(), ExceptionCodes.KEY_MAPPING_ALREADY_EXIST);
        }
        // initiate WorkflowExecutor
        WorkflowExecutor appRegistrationWorkflow = null;
        // initiate ApplicationRegistrationWorkflowDTO
        ApplicationRegistrationWorkflowDTO appRegWFDto = null;
        ApplicationKeysDTO appKeysDto = new ApplicationKeysDTO();
        boolean isCaseInsensitiveComparisons = Boolean.parseBoolean(getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_FORCE_CI_COMPARISIONS));
        boolean isUserAppOwner;
        if (isCaseInsensitiveComparisons) {
            isUserAppOwner = application.getSubscriber().getName().equalsIgnoreCase(userId);
        } else {
            isUserAppOwner = application.getSubscriber().getName().equals(userId);
        }
        if (!isUserAppOwner) {
            throw new APIManagementException("user: " + application.getSubscriber().getName() + ", " + "attempted to generate tokens for application owned by: " + userId);
        }
        // if its a PRODUCTION application.
        if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(tokenType)) {
            // initiate workflow type. By default simple work flow will be
            // executed.
            appRegistrationWorkflow = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
            appRegWFDto = (ApplicationRegistrationWorkflowDTO) WorkflowExecutorFactory.getInstance().createWorkflowDTO(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
        } else // if it is a sandBox application.
        if (APIConstants.API_KEY_TYPE_SANDBOX.equals(tokenType)) {
            // if its a SANDBOX application.
            appRegistrationWorkflow = getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
            appRegWFDto = (ApplicationRegistrationWorkflowDTO) WorkflowExecutorFactory.getInstance().createWorkflowDTO(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
        } else {
            throw new APIManagementException("Invalid Token Type '" + tokenType + "' requested.");
        }
        // check whether callback url is empty and set null
        if (StringUtils.isBlank(callbackUrl)) {
            callbackUrl = null;
        }
        String applicationTokenType = application.getTokenType();
        if (StringUtils.isEmpty(application.getTokenType())) {
            applicationTokenType = APIConstants.DEFAULT_TOKEN_TYPE;
        }
        // Build key manager instance and create oAuthAppRequest by jsonString.
        OAuthAppRequest request = ApplicationUtils.createOauthAppRequest(application.getName(), null, callbackUrl, tokenScope, jsonString, applicationTokenType, tenantDomain, keyManagerName);
        request.getOAuthApplicationInfo().addParameter(ApplicationConstants.VALIDITY_PERIOD, validityTime);
        request.getOAuthApplicationInfo().addParameter(ApplicationConstants.APP_KEY_TYPE, tokenType);
        request.getOAuthApplicationInfo().addParameter(ApplicationConstants.APP_CALLBACK_URL, callbackUrl);
        request.getOAuthApplicationInfo().setApplicationUUID(application.getUUID());
        // Setting request values in WorkflowDTO - In future we should keep
        // Application/OAuthApplication related
        // information in the respective entities not in the workflowDTO.
        appRegWFDto.setStatus(WorkflowStatus.CREATED);
        appRegWFDto.setCreatedTime(System.currentTimeMillis());
        appRegWFDto.setTenantDomain(tenantDomain);
        appRegWFDto.setTenantId(tenantId);
        appRegWFDto.setExternalWorkflowReference(appRegistrationWorkflow.generateUUID());
        appRegWFDto.setWorkflowReference(appRegWFDto.getExternalWorkflowReference());
        appRegWFDto.setApplication(application);
        appRegWFDto.setKeyManager(keyManagerId);
        request.setMappingId(appRegWFDto.getWorkflowReference());
        if (!application.getSubscriber().getName().equals(userId)) {
            appRegWFDto.setUserName(application.getSubscriber().getName());
        } else {
            appRegWFDto.setUserName(userId);
        }
        appRegWFDto.setCallbackUrl(appRegistrationWorkflow.getCallbackURL());
        appRegWFDto.setAppInfoDTO(request);
        appRegWFDto.setDomainList(allowedDomains);
        appRegWFDto.setKeyDetails(appKeysDto);
        appRegistrationWorkflow.execute(appRegWFDto);
        Map<String, Object> keyDetails = new HashMap<String, Object>();
        keyDetails.put(APIConstants.FrontEndParameterNames.KEY_STATE, appRegWFDto.getStatus().toString());
        OAuthApplicationInfo applicationInfo = appRegWFDto.getApplicationInfo();
        String keyMappingId = apiMgtDAO.getKeyMappingIdFromApplicationIdKeyTypeAndKeyManager(application.getId(), tokenType, keyManagerId);
        keyDetails.put(APIConstants.FrontEndParameterNames.KEY_MAPPING_ID, keyMappingId);
        if (applicationInfo != null) {
            keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_KEY, applicationInfo.getClientId());
            keyDetails.put(APIConstants.FrontEndParameterNames.CONSUMER_SECRET, applicationInfo.getClientSecret());
            keyDetails.put(ApplicationConstants.OAUTH_APP_DETAILS, applicationInfo.getJsonString());
            keyDetails.put(APIConstants.FrontEndParameterNames.MODE, APIConstants.OAuthAppMode.CREATED.name());
        }
        // There can be instances where generating the Application Token is
        // not required. In those cases,
        // token info will have nothing.
        AccessTokenInfo tokenInfo = appRegWFDto.getAccessTokenInfo();
        if (tokenInfo != null) {
            keyDetails.put("accessToken", tokenInfo.getAccessToken());
            keyDetails.put("validityTime", tokenInfo.getValidityPeriod());
            keyDetails.put("tokenDetails", tokenInfo.getJSONString());
            keyDetails.put("tokenScope", tokenInfo.getScopes());
        }
        JSONObject appLogObject = new JSONObject();
        appLogObject.put("Generated keys for application", application.getName());
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.APPLICATION, appLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
        // if its a PRODUCTION application.
        if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(tokenType)) {
            // get the workflow state once the executor is executed.
            WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(appRegWFDto.getExternalWorkflowReference(), WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION);
            // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
            if (wfDTO != null) {
                if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                    ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                    APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
                }
            } else {
                ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
            }
        } else if (APIConstants.API_KEY_TYPE_SANDBOX.equals(tokenType)) {
            // get the workflow state once the executor is executed.
            WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(appRegWFDto.getExternalWorkflowReference(), WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX);
            // wfDTO is null when simple wf executor is used because wf state is not stored in the db and is always approved.
            if (wfDTO != null) {
                if (WorkflowStatus.APPROVED.equals(wfDTO.getStatus())) {
                    ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                    APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
                }
            } else {
                ApplicationRegistrationEvent applicationRegistrationEvent = new ApplicationRegistrationEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.APPLICATION_REGISTRATION_CREATE.name(), tenantId, tenantDomain, application.getId(), application.getUUID(), applicationInfo.getClientId(), tokenType, keyManagerName);
                APIUtil.sendNotification(applicationRegistrationEvent, APIConstants.NotifierType.APPLICATION_REGISTRATION.name());
            }
        }
        return keyDetails;
    } catch (WorkflowException e) {
        log.error("Could not execute Workflow", e);
        throw new APIManagementException(e);
    } finally {
        if (isTenantFlowStarted) {
            endTenantFlow();
        }
    }
}
Also used : KeyManagerConfigurationDTO(org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) ApplicationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationWorkflowDTO) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) SubscriptionWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.SubscriptionWorkflowDTO) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) ApplicationRegistrationEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationRegistrationEvent) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) ApplicationKeysDTO(org.wso2.carbon.apimgt.api.model.ApplicationKeysDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) OAuthAppRequest(org.wso2.carbon.apimgt.api.model.OAuthAppRequest) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) JSONObject(org.json.simple.JSONObject) WorkflowExecutor(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutor)

Aggregations

OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)5 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 HashMap (java.util.HashMap)2 OAuthAppRequest (org.wso2.carbon.apimgt.api.model.OAuthAppRequest)2 OAuthConsumerAppDTO (org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO)2 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 JSONObject (org.json.simple.JSONObject)1 Test (org.junit.Test)1 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)1 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)1 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)1 ApplicationInfo (org.wso2.carbon.apimgt.api.model.ApplicationInfo)1 ApplicationKeysDTO (org.wso2.carbon.apimgt.api.model.ApplicationKeysDTO)1 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)1 KeyManagerConnectorConfiguration (org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration)1 ApplicationRegistrationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO)1