Java Code Examples for org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO#getInstance()

The following examples show how to use org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO#getInstance() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public WorkflowResponse execute(WorkflowDTO workFlowDTO) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Executing AbstractApplicationRegistrationWorkflowExecutor...");
    }
    ApiMgtDAO dao = ApiMgtDAO.getInstance();
    try {
        //dao.createApplicationRegistrationEntry((ApplicationRegistrationWorkflowDTO) workFlowDTO, false);
        ApplicationRegistrationWorkflowDTO appRegDTO;
        if (workFlowDTO instanceof ApplicationRegistrationWorkflowDTO) {
            appRegDTO = (ApplicationRegistrationWorkflowDTO)workFlowDTO;
        }else{
            String message = "Invalid workflow type found";
            log.error(message);
            throw new WorkflowException(message);
        }
        dao.createApplicationRegistrationEntry(appRegDTO,false);
       // appRegDTO.getAppInfoDTO().saveDTO();
        super.execute(workFlowDTO);
    } catch (APIManagementException e) {
        log.error("Error while creating Application Registration entry.", e);
        throw new WorkflowException("Error while creating Application Registration entry.", e);
    }
    return new GeneralWorkflowResponse();
}
 
Example 2
private void persistRevokedJWTSignature(String token, Long expiryTime) {

        ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
        try {
            String tokenSignature = APIUtil.getSignatureIfJWT(token);
            String tenantDomain = APIUtil.getTenantDomainIfJWT(token);
            int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
            apiMgtDAO.addRevokedJWTSignature(tokenSignature, APIConstants.DEFAULT, expiryTime, tenantId);

            // Cleanup expired revoked tokens from db.
            Runnable expiredJWTCleaner = new ExpiredJWTCleaner();
            Thread cleanupThread = new Thread(expiredJWTCleaner);
            cleanupThread.start();
        } catch (APIManagementException e) {
            log.error("Unable to add revoked JWT signature to the database");
        }
    }
 
Example 3
Source Project: carbon-apimgt   File: APIMgtDAOTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    String dbConfigPath = System.getProperty("APIManagerDBConfigurationPath");
    APIManagerConfiguration config = new APIManagerConfiguration();
    initializeDatabase(dbConfigPath);
    config.load(dbConfigPath);
    ServiceReferenceHolder.getInstance().setAPIManagerConfigurationService(new APIManagerConfigurationServiceImpl
            (config));
    List<Notifier> notifierList = new ArrayList<>();
    SubscriptionsNotifier subscriptionsNotifier = new SubscriptionsNotifier();
    notifierList.add(subscriptionsNotifier);
    ServiceReferenceHolder.getInstance().getNotifiersMap().put(subscriptionsNotifier.getType(), notifierList);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    keyManager = Mockito.mock(KeyManager.class);
    APIMgtDBUtil.initialize();
    apiMgtDAO = ApiMgtDAO.getInstance();
    IdentityTenantUtil.setRealmService(new TestRealmService());
    String identityConfigPath = System.getProperty("IdentityConfigurationPath");
    IdentityConfigParser.getInstance(identityConfigPath);
    OAuthServerConfiguration oAuthServerConfiguration = OAuthServerConfiguration.getInstance();
    ServiceReferenceHolder.getInstance().setOauthServerConfiguration(oAuthServerConfiguration);

}
 
Example 4
@Override
public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowException {
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    ApplicationWorkflowDTO applicationWorkflowDTO = (ApplicationWorkflowDTO) workflowDTO;
    Application application = applicationWorkflowDTO.getApplication();
    String errorMsg = null;

    try {
        apiMgtDAO.deleteApplication(application);
    } catch (APIManagementException e) {
        if (e.getMessage() == null) {
            errorMsg = "Couldn't complete simple application deletion workflow for application: " + application
                    .getName();
        } else {
            errorMsg = e.getMessage();
        }
        throw new WorkflowException(errorMsg, e);
    }

    return new GeneralWorkflowResponse();
}
 
Example 5
@Override
public Map<String, Set<Scope>> getScopesForAPIS(String apiIdsString)
        throws APIManagementException {

    Map<String, Set<Scope>> apiToScopeMapping = new HashMap<>();
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    Map<String, Set<String>> apiToScopeKeyMapping = apiMgtDAO.getScopesForAPIS(apiIdsString);
    for (String apiId : apiToScopeKeyMapping.keySet()) {
        Set<Scope> apiScopes = new LinkedHashSet<>();
        Set<String> scopeKeys = apiToScopeKeyMapping.get(apiId);
        for (String scopeKey : scopeKeys) {
            Scope scope = getScopeByName(scopeKey);
            apiScopes.add(scope);
        }
        apiToScopeMapping.put(apiId, apiScopes);
    }
    return apiToScopeMapping;
}
 
Example 6
/**
 * Handle cleanup task for api state change workflow Approval executor.
 * Use workflow external reference  to delete the pending workflow request
 *
 * @param workflowExtRef External Workflow Reference of pending workflow process
 */
@Override
public void cleanUpPendingTask(String workflowExtRef) throws WorkflowException {

    if (log.isDebugEnabled()) {
        log.debug("Starting cleanup task for APIStateChangeWSWorkflowExecutor for :" + workflowExtRef);
    }
    String errorMsg;
    super.cleanUpPendingTask(workflowExtRef);
    try {
        ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
        apiMgtDAO.deleteWorkflowRequest(workflowExtRef);
    } catch (APIManagementException axisFault) {
        errorMsg = "Error sending out cancel pending application approval process message. cause: " + axisFault
                .getMessage();
        throw new WorkflowException(errorMsg, axisFault);
    }
}
 
Example 7
/**
 * Handle cleanup task for application creation Approval workflow executor.
 * Use workflow external reference  to delete the pending workflow request
 *
 * @param workflowExtRef Workflow external reference of pending workflow request
 */
@Override
public void cleanUpPendingTask(String workflowExtRef) throws WorkflowException {

    String errorMsg;
    if (log.isDebugEnabled()) {
        log.debug("Starting cleanup task for ApplicationCreationApprovalWorkflowExecutor for :" + workflowExtRef);
    }
    super.cleanUpPendingTask(workflowExtRef);
    try {
        ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
        apiMgtDAO.deleteWorkflowRequest(workflowExtRef);
    } catch (APIManagementException axisFault) {
        errorMsg = "Error sending out cancel pending application approval process message. cause: " + axisFault
                .getMessage();
        throw new WorkflowException(errorMsg, axisFault);
    }
}
 
Example 8
/**
 * This method completes subscription update simple workflow and return workflow response back to the caller
 *
 * @param workflowDTO The WorkflowDTO which contains workflow contextual information related to the workflow
 * @return workflow response back to the caller
 * @throws WorkflowException
 */
@Override
public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowException {
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    SubscriptionWorkflowDTO subscriptionWorkflowDTO = (SubscriptionWorkflowDTO)workflowDTO;
    try {
        if (subscriptionWorkflowDTO.getStatus() == WorkflowStatus.APPROVED) {
            apiMgtDAO.updateSubscriptionStatusAndTier(Integer.parseInt(subscriptionWorkflowDTO.getWorkflowReference()),
                    APIConstants.SubscriptionStatus.UNBLOCKED, subscriptionWorkflowDTO.getRequestedTierName());
        } else if (subscriptionWorkflowDTO.getStatus() == WorkflowStatus.CREATED ||
                subscriptionWorkflowDTO.getStatus() == WorkflowStatus.REGISTERED) {
            apiMgtDAO.updateSubscriptionStatus(Integer.parseInt(subscriptionWorkflowDTO.getWorkflowReference()),
                    APIConstants.SubscriptionStatus.TIER_UPDATE_PENDING);
        } else if (subscriptionWorkflowDTO.getStatus() == WorkflowStatus.REJECTED) {
            apiMgtDAO.updateSubscriptionStatusAndTier(Integer.parseInt(subscriptionWorkflowDTO.getWorkflowReference()),
                    APIConstants.SubscriptionStatus.UNBLOCKED, subscriptionWorkflowDTO.getTierName());
        }
    } catch (APIManagementException e) {
        log.error("Could not complete subscription update workflow", e);
        throw new WorkflowException("Could not complete subscription update workflow", e);
    }
    return new GeneralWorkflowResponse();
}
 
Example 9
/**
 * Handle cleanup task for application registration Approval workflow executor.
 * Use workflow external reference  to delete the pending workflow request
 *
 * @param workflowExtRef Workflow external reference of pending workflow request
 */
@Override
public void cleanUpPendingTask(String workflowExtRef) throws WorkflowException {
    super.cleanUpPendingTask(workflowExtRef);
    String errorMsg = null;
    if (log.isDebugEnabled()) {
        log.debug("Starting cleanup task for ApplicationRegistrationApprovalWorkflowExecutor for :" + workflowExtRef);
    }
    try {
        ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
        apiMgtDAO.deleteWorkflowRequest(workflowExtRef);
    } catch (APIManagementException axisFault) {
        errorMsg = "Error sending out cancel pending registration approval process message. Cause: " + axisFault
                .getMessage();
        throw new WorkflowException(errorMsg, axisFault);
    }
}
 
Example 10
/**
 * Complete the external process status
 * Based on the workflow status we will update the status column of the
 * Application table
 *
 * @param workFlowDTO - WorkflowDTO
 */
public WorkflowResponse complete(WorkflowDTO workFlowDTO) throws WorkflowException {
	if (log.isDebugEnabled()) {
		log.info("Complete  Application creation Workflow..");
	}

	String status = null;
	if ("CREATED".equals(workFlowDTO.getStatus().toString())) {
		status = APIConstants.ApplicationStatus.APPLICATION_CREATED;
	} else if ("REJECTED".equals(workFlowDTO.getStatus().toString())) {
		status = APIConstants.ApplicationStatus.APPLICATION_REJECTED;
	} else if ("APPROVED".equals(workFlowDTO.getStatus().toString())) {
		status = APIConstants.ApplicationStatus.APPLICATION_APPROVED;
	}

	ApiMgtDAO dao = ApiMgtDAO.getInstance();

	try {
		dao.updateApplicationStatus(Integer.parseInt(workFlowDTO.getWorkflowReference()),status);
	} catch (APIManagementException e) {
		String msg = "Error occured when updating the status of the Application creation process";
		log.error(msg, e);
		throw new WorkflowException(msg, e);
	}
	return new GeneralWorkflowResponse();
}
 
Example 11
/**
 * find out whether the Default API version is invoked
 *
 * @param context context of API accessing
 * @return Default API version. return null if not default version
 * @throws APIManagementException
 */
private String isDefaultVersionInvoked(String context) throws APIManagementException {
    ApiMgtDAO dao = ApiMgtDAO.getInstance();
    String[] APIDetails = dao.getAPIDetailsByContext(context);
    String apiName = APIDetails[0];
    String apiProvider = APIDetails[1];
    if (!(apiName.equalsIgnoreCase("") || apiProvider.equalsIgnoreCase(""))) {
        return dao.getDefaultVersion(new APIIdentifier(apiProvider, apiName, ""));
    }
    return null;
}
 
Example 12
Source Project: carbon-apimgt   File: WorkflowExecutor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Implements the workflow completion logic.
 *
 * @param workflowDTO - The WorkflowDTO which contains workflow contextual information related to the workflow.
 * @throws WorkflowException - Thrown when the workflow completion was not fully performed.
 */
public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowException {

    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    try {
        apiMgtDAO.updateWorkflowStatus(workflowDTO);
        publishEvents(workflowDTO);
    } catch (APIManagementException e) {
        throw new WorkflowException("Error while updating workflow", e);
    }
    return new GeneralWorkflowResponse();
}
 
Example 13
Source Project: carbon-apimgt   File: WorkflowExecutor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method for persisting Workflow DTO
 *
 * @param workflowDTO
 * @throws WorkflowException
 */
public void persistWorkflow(WorkflowDTO workflowDTO) throws WorkflowException {
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    try {
        apiMgtDAO.addWorkflowEntry(workflowDTO);
    } catch (APIManagementException e) {
        throw new WorkflowException("Error while persisting workflow", e);
    }
}
 
Example 14
protected ApiMgtDAO getApiMgtdao() {
    return ApiMgtDAO.getInstance();
}
 
Example 15
Source Project: carbon-apimgt   File: APITokenValidator.java    License: Apache License 2.0 4 votes vote down vote up
public APIKeyValidationInfoDTO validateKey(String context, String version, String accessToken,
                                           String requiredAuthenticationLevel) throws APIManagementException {
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    return null;
}
 
Example 16
public static void dogenerateKeysForApplication(ApplicationRegistrationWorkflowDTO workflowDTO)
        throws APIManagementException{
    log.debug("Registering Application and creating an Access Token... ");
    Application application = workflowDTO.getApplication();
    Subscriber subscriber = application.getSubscriber();
    ApiMgtDAO dao = ApiMgtDAO.getInstance();
    if (subscriber == null || workflowDTO.getAllowedDomains() == null) {
        dao.populateAppRegistrationWorkflowDTO(workflowDTO);
    }

    try {
        //get new key manager
        String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
        String keyManagerName = workflowDTO.getKeyManager();
        KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
        if (keyManager == null){
            throw new APIManagementException("Key Manager " + keyManagerName + " not configured");
        }
        workflowDTO.getAppInfoDTO().getOAuthApplicationInfo()
                   .setClientName(application.getName());

        // set applications attributes to the oAuthApplicationInfo
        workflowDTO.getAppInfoDTO().getOAuthApplicationInfo()
                .putAllAppAttributes(application.getApplicationAttributes());

        //createApplication on oAuthorization server.
        OAuthApplicationInfo oAuthApplication = keyManager.createApplication(workflowDTO.getAppInfoDTO());

        //update associateApplication
        ApplicationUtils
                .updateOAuthAppAssociation(application, workflowDTO.getKeyType(), oAuthApplication, keyManagerName);

        //change create application status in to completed.
        dao.updateApplicationRegistration(APIConstants.AppRegistrationStatus.REGISTRATION_COMPLETED,
                workflowDTO.getKeyType(), workflowDTO.getApplication().getId(), keyManagerName);

        workflowDTO.setApplicationInfo(oAuthApplication);
        AccessTokenInfo tokenInfo;
        Object enableTokenGeneration = keyManager.getKeyManagerConfiguration()
                .getParameter(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
            if (enableTokenGeneration != null && (Boolean) enableTokenGeneration &&
                    oAuthApplication.getJsonString().contains(APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS)) {
                AccessTokenRequest tokenRequest = ApplicationUtils.createAccessTokenRequest(keyManager,
                        oAuthApplication, null);
                tokenInfo = keyManager.getNewApplicationAccessToken(tokenRequest);
            } else {
                tokenInfo = new AccessTokenInfo();
                tokenInfo.setAccessToken("");
                tokenInfo.setValidityPeriod(0L);
                String[] noScopes = new String[] {"N/A"};
                tokenInfo.setScope(noScopes);
                oAuthApplication.addParameter("tokenScope", Arrays.toString(noScopes));
            }
        workflowDTO.setAccessTokenInfo(tokenInfo);
    } catch (Exception e) {
        APIUtil.handleException("Error occurred while executing SubscriberKeyMgtClient.", e);
    }
}
 
Example 17
private APIKeyRevokeServiceImpl() {
    revocationRequestPublisher = RevocationRequestPublisher.getInstance();
    dao = ApiMgtDAO.getInstance();
}
 
Example 18
public static void registerDefaultKeyManager(String tenantDomain) throws APIManagementException {

        ApiMgtDAO instance = ApiMgtDAO.getInstance();
        if (instance.getKeyManagerConfigurationByName(tenantDomain, APIConstants.KeyManager.DEFAULT_KEY_MANAGER) ==
                null) {

            APIManagerConfigurationService apiManagerConfigurationService =
                    ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService();

            KeyManagerConfigurationDTO keyManagerConfigurationDTO = new KeyManagerConfigurationDTO();
            keyManagerConfigurationDTO.setName(APIConstants.KeyManager.DEFAULT_KEY_MANAGER);
            keyManagerConfigurationDTO.setEnabled(true);
            keyManagerConfigurationDTO.setUuid(UUID.randomUUID().toString());
            keyManagerConfigurationDTO.setTenantDomain(tenantDomain);
            keyManagerConfigurationDTO.setType(APIConstants.KeyManager.DEFAULT_KEY_MANAGER_TYPE);
            keyManagerConfigurationDTO.setDescription(APIConstants.KeyManager.DEFAULT_KEY_MANAGER_DESCRIPTION);
            if (apiManagerConfigurationService != null &&
                    apiManagerConfigurationService.getAPIManagerConfiguration() != null) {
                String username = apiManagerConfigurationService.getAPIManagerConfiguration()
                        .getFirstProperty(APIConstants.API_KEY_VALIDATOR_USERNAME);
                String password = apiManagerConfigurationService.getAPIManagerConfiguration()
                        .getFirstProperty(APIConstants.API_KEY_VALIDATOR_PASSWORD);
                String serviceURl = apiManagerConfigurationService.getAPIManagerConfiguration()
                        .getFirstProperty(APIConstants.KEYMANAGER_SERVERURL);
                OAuthApplicationInfo oAuthApplicationInfo =
                        registerKeyMgtApplication(tenantDomain, serviceURl, username, password);
                if (oAuthApplicationInfo != null) {
                    keyManagerConfigurationDTO.addProperty(APIConstants.KEY_MANAGER_CONSUMER_KEY,
                            oAuthApplicationInfo.getClientId());
                    keyManagerConfigurationDTO.addProperty(APIConstants.KEY_MANAGER_CONSUMER_SECRET,
                            oAuthApplicationInfo.getClientSecret());
                }
            }
            TokenHandlingDto tokenHandlingDto = new TokenHandlingDto();
            tokenHandlingDto.setEnable(true);
            tokenHandlingDto.setType(TokenHandlingDto.TypeEnum.REFERENCE);
            tokenHandlingDto.setValue(APIConstants.KeyManager.UUID_REGEX);
            keyManagerConfigurationDTO.addProperty(APIConstants.KeyManager.TOKEN_FORMAT_STRING,
                    new Gson().toJson(Arrays.asList(tokenHandlingDto)));
            instance.addKeyManagerConfiguration(keyManagerConfigurationDTO);
        }
    }
 
Example 19
/**
 * validate access token for websocket handshake
 *
 * @param context context of the API
 * @param version version of the API
 * @param accessToken access token of the request
 * @return api information
 * @throws APIKeyMgtException
 * @throws APIManagementException
 */
public APIKeyValidationInfoDTO validateKeyforHandshake(String context, String version,
                                                       String accessToken, String tenantDomain,
                                                       List<String> keyManagers)
        throws APIKeyMgtException, APIManagementException {
    boolean defaultVersionInvoked = false;
    APIKeyValidationInfoDTO info = new APIKeyValidationInfoDTO();
    info.setAuthorized(false);
    TokenValidationContext validationContext = new TokenValidationContext();
    validationContext.setAccessToken(accessToken);
    validationContext.setContext(context);
    validationContext.setValidationInfoDTO(new APIKeyValidationInfoDTO());
    validationContext.setVersion(version);
    validationContext.setTenantDomain(tenantDomain);
    validationContext.setRequiredAuthenticationLevel("Any");
    validationContext.setKeyManagers(keyManagers);
    KeyValidationHandler keyValidationHandler =
            ServiceReferenceHolder.getInstance().getKeyValidationHandler(tenantDomain);
    boolean state = keyValidationHandler.validateToken(validationContext);
    ApiMgtDAO dao = ApiMgtDAO.getInstance();
    if (state) {
        info.setAuthorized(true);
        info.setValidityPeriod(validationContext.getTokenInfo().getValidityPeriod());
        info.setIssuedTime(validationContext.getTokenInfo().getIssuedTime());
        info.setKeyManager(validationContext.getValidationInfoDTO().getKeyManager());
        String def_version = isDefaultVersionInvoked(validationContext.getContext());
        if (def_version != null) {
            defaultVersionInvoked = true;
            version = def_version;
            context += "/" + def_version;
            validationContext.setVersion(version);
            validationContext.setContext(context);
        }
        info = dao.validateSubscriptionDetails(info, validationContext.getContext(), validationContext.getVersion(),
                validationContext.getTokenInfo().getConsumerKey(), info.getKeyManager(),
                defaultVersionInvoked);

        if (defaultVersionInvoked) {
            info.setApiName(info.getApiName() + "*" + version);
        }

        if (APIKeyMgtDataHolder.isJwtGenerationEnabled() &&
                validationContext.getValidationInfoDTO().getEndUserName() != null
                && !validationContext.isCacheHit()) {
            Application application = APIUtil.getApplicationByClientId(validationContext.getValidationInfoDTO()
                    .getConsumerKey());
            validationContext.getValidationInfoDTO().setApplicationId(String.valueOf(application.getId()));
            validationContext.getValidationInfoDTO().setApplicationTier(application.getTier());
            keyValidationHandler.generateConsumerToken(validationContext);
            info.setEndUserToken(validationContext.getValidationInfoDTO().getEndUserToken());
        }
    }

    info.setConsumerKey(validationContext.getTokenInfo().getConsumerKey());
    info.setEndUserName(validationContext.getTokenInfo().getEndUserName());
    return info;
}
 
Example 20
protected ApiMgtDAO getDAOInstance() {

        return ApiMgtDAO.getInstance();
    }