Java Code Examples for org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO

The following examples show how to use org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO. 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
Source Project: carbon-apimgt   Source File: AlertTypesPublisherTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = APIManagementException.class)
public void saveAlertWhileDatabaseConnectionFailed() throws Exception {
    String checkedAlertList = "health-availability";
    String emailList = "[email protected]";
    String userName = "[email protected]";
    String agent = "publisher";
    String checkedAlertListValues = "true";
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    Mockito.doThrow(APIManagementException.class).when(apiMgtDAO).addAlertTypesConfigInfo(userName, emailList,
            checkedAlertList, agent);
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    AlertTypesPublisher alertTypesPublisher = new AlertTypePublisherWrapper(apiMgtDAO, apiMgtUsageDataPublisher);
    alertTypesPublisher.enabled = true;
    alertTypesPublisher.skipEventReceiverConnection = false;
    alertTypesPublisher.saveAndPublishAlertTypesEvent(checkedAlertList, emailList, userName, agent,
            checkedAlertListValues);
}
 
Example 2
Source Project: carbon-apimgt   Source File: LabelApiServiceImplTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method tests the functionality of labelsPost, for a successful add label
 *
 * @throws APIManagementException APIManagementException.
 */
@Test
public void testLabelsPost() throws APIManagementException {
    LabelDTO labelDTO = Mockito.mock(LabelDTO.class);
    List<String> urls = new ArrayList<>();
    urls.add("url1");
    urls.add("url2");

    Label label1 = new Label();
    label1.setLabelId("1111");
    label1.setName("TestLabel");
    label1.setAccessUrls(urls);
    PowerMockito.when(LabelMappingUtil.labelDTOToLabel(labelDTO)).thenReturn(label1);
    PowerMockito.mockStatic(ApiMgtDAO.class);
    apiMgtDAO =  PowerMockito.mock(ApiMgtDAO.class);
    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    Mockito.when(apiMgtDAO.addLabel(TENANT_DOMAIN, label1)).thenReturn(label1);

    PowerMockito.when(LabelMappingUtil.fromLabelToLabelDTO(label1)).thenReturn(labelDTO);
    Response response = labelsApiService.labelsPost(labelDTO);
    Assert.assertEquals(response.getStatus(), 201);
}
 
Example 3
Source Project: carbon-apimgt   Source File: APIMOAuthEventInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
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 4
Source Project: carbon-apimgt   Source File: AMDefaultKeyManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: carbon-apimgt   Source 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 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
@Override
public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowException {
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    SubscriptionWorkflowDTO subWorkflowDTO = (SubscriptionWorkflowDTO) workflowDTO;
    String errorMsg = null;

    try {
        APIIdentifier identifier = new APIIdentifier(subWorkflowDTO.getApiProvider(),
                subWorkflowDTO.getApiName(), subWorkflowDTO.getApiVersion());
        apiMgtDAO.removeSubscription(identifier, ((SubscriptionWorkflowDTO) workflowDTO).getApplicationId());
    } catch (APIManagementException e) {
        errorMsg = "Could not complete subscription deletion workflow for api: " + subWorkflowDTO.getApiName();
        throw new WorkflowException(errorMsg, e);
    }
    return new GeneralWorkflowResponse();
}
 
Example 8
/**
 * 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 9
@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 10
/**
 * 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 11
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 12
/**
 * Handle cleanup task for subscription 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 = null;
    super.cleanUpPendingTask(workflowExtRef);
    if (log.isDebugEnabled()) {
        log.debug("Starting cleanup task for SubscriptionCreationApprovalWorkflowExecutor for :" + workflowExtRef);
    }
    try {
        ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
        apiMgtDAO.deleteWorkflowRequest(workflowExtRef);
    } catch (APIManagementException axisFault) {
        errorMsg = "Error sending out cancel pending subscription approval process message. cause: " + axisFault
                .getMessage();
        throw new WorkflowException(errorMsg, axisFault);
    }
}
 
Example 13
Source Project: carbon-apimgt   Source File: APIUtilTierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddDefaultSuperTenantAdvancedThrottlePoliciesAppLevel() throws Exception {
    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(1);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    String[] appPolicies = new String[]{APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN,
            APIConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN,
            APIConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_UNLIMITED};

    for (String policy : appPolicies) {
        Mockito.when(
                apiMgtDAO.isPolicyExist(eq(PolicyConstants.POLICY_LEVEL_APP), eq(MultitenantConstants.SUPER_TENANT_ID),
                        eq(policy))).thenReturn(false);
    }

    try {
        APIUtil.addDefaultSuperTenantAdvancedThrottlePolicies();
        Mockito.verify(apiMgtDAO, Mockito.times(appPolicies.length)).addApplicationPolicy(Mockito.any(ApplicationPolicy.class));
    } catch (APIManagementException e) {
        Assert.assertTrue("Exception thrown", false);
    }
}
 
Example 14
Source Project: carbon-apimgt   Source File: APIUtilTierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddDefaultSuperTenantAdvancedThrottlePoliciesAppLevelAlreadyAdded() throws Exception {
    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(1);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();


    String[] appPolicies = new String[]{APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN,
            APIConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN,
            APIConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_UNLIMITED};


    // If policy added already
    for (String policy : appPolicies) {
        Mockito.when(
                apiMgtDAO.isPolicyExist(eq(PolicyConstants.POLICY_LEVEL_APP), eq(MultitenantConstants.SUPER_TENANT_ID),
                        eq(policy))).thenReturn(true);
    }

    try {
        APIUtil.addDefaultSuperTenantAdvancedThrottlePolicies();
        Mockito.verify(apiMgtDAO, Mockito.never()).addApplicationPolicy(Mockito.any(ApplicationPolicy.class));
    } catch (APIManagementException e) {
        Assert.assertTrue("Exception thrown", false);
    }
}
 
Example 15
Source Project: carbon-apimgt   Source File: APIUtilTierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddDefaultSuperTenantAdvancedThrottlePoliciesSubLevel() throws Exception {
    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(1);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    String[] subPolicies = new String[]{APIConstants.DEFAULT_SUB_POLICY_GOLD, APIConstants.DEFAULT_SUB_POLICY_SILVER,
            APIConstants.DEFAULT_SUB_POLICY_BRONZE, APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED,
            APIConstants.DEFAULT_SUB_POLICY_UNLIMITED};

    for (String policy : subPolicies) {
        Mockito.when(
                apiMgtDAO.isPolicyExist(eq(PolicyConstants.POLICY_LEVEL_SUB), eq(MultitenantConstants.SUPER_TENANT_ID),
                        eq(policy))).thenReturn(false);
    }

    try {
        APIUtil.addDefaultSuperTenantAdvancedThrottlePolicies();
        Mockito.verify(apiMgtDAO, Mockito.times(subPolicies.length)).addSubscriptionPolicy(Mockito.any(SubscriptionPolicy.class));
    } catch (APIManagementException e) {
        Assert.assertTrue("Exception thrown", false);
    }
}
 
Example 16
Source Project: carbon-apimgt   Source File: APIUtilTierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddDefaultSuperTenantAdvancedThrottlePoliciesSubLevelAlreadyAdded() throws Exception {
    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(1);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    String[] subPolicies = new String[]{APIConstants.DEFAULT_SUB_POLICY_GOLD, APIConstants.DEFAULT_SUB_POLICY_SILVER,
            APIConstants.DEFAULT_SUB_POLICY_BRONZE, APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED,
            APIConstants.DEFAULT_SUB_POLICY_UNLIMITED};

    for (String policy : subPolicies) {
        Mockito.when(
                apiMgtDAO.isPolicyExist(eq(PolicyConstants.POLICY_LEVEL_SUB), eq(MultitenantConstants.SUPER_TENANT_ID),
                        eq(policy))).thenReturn(true);
    }

    try {
        APIUtil.addDefaultSuperTenantAdvancedThrottlePolicies();
        Mockito.verify(apiMgtDAO, Mockito.never()).addSubscriptionPolicy(Mockito.any(SubscriptionPolicy.class));
    } catch (APIManagementException e) {
        Assert.assertTrue("Exception thrown", false);
    }
}
 
Example 17
Source Project: carbon-apimgt   Source File: APIUtilTierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddDefaultSuperTenantAdvancedThrottlePoliciesApiLevel() throws Exception {
    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(1);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    String[] apiPolicies = new String[]{APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN,
            APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN,
            APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_UNLIMITED};

    for (String policy : apiPolicies) {
        Mockito.when(
                apiMgtDAO.isPolicyExist(eq(PolicyConstants.POLICY_LEVEL_API), eq(MultitenantConstants.SUPER_TENANT_ID),
                        eq(policy))).thenReturn(false);
    }

    try {
        APIUtil.addDefaultSuperTenantAdvancedThrottlePolicies();
        Mockito.verify(apiMgtDAO, Mockito.times(apiPolicies.length)).addAPIPolicy(Mockito.any(APIPolicy.class));
    } catch (APIManagementException e) {
        Assert.assertTrue("Exception thrown", false);
    }
}
 
Example 18
Source Project: carbon-apimgt   Source File: APIUtilTierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddDefaultSuperTenantAdvancedThrottlePoliciesApiLevelAlreadyAdded() throws Exception {
    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(1);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    String[] apiPolicies = new String[]{APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN,
            APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN,
            APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_UNLIMITED};

    for (String policy : apiPolicies) {
        Mockito.when(
                apiMgtDAO.isPolicyExist(eq(PolicyConstants.POLICY_LEVEL_API), eq(MultitenantConstants.SUPER_TENANT_ID),
                        eq(policy))).thenReturn(true);
    }

    try {
        APIUtil.addDefaultSuperTenantAdvancedThrottlePolicies();
        Mockito.verify(apiMgtDAO, Mockito.never()).addAPIPolicy(Mockito.any(APIPolicy.class));
    } catch (APIManagementException e) {
        Assert.assertTrue("Exception thrown", false);
    }
}
 
Example 19
@Before
public void init() throws APIManagementException {
    PowerMockito.mockStatic(ApiMgtDAO.class);
    PowerMockito.mockStatic(KeyManagerHolder.class);
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    keyManager = Mockito.mock(KeyManager.class);
    application = new Application("test", new Subscriber("testUser"));
    oAuthAppRequest = new OAuthAppRequest();
    oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthAppRequest.setOAuthApplicationInfo(oAuthApplicationInfo);
    workflowDTO = new ApplicationRegistrationWorkflowDTO();
    workflowDTO.setWorkflowReference("1");
    workflowDTO.setApplication(application);
    workflowDTO.setAppInfoDTO(oAuthAppRequest);
    workflowDTO.setKeyManager("default");

    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    PowerMockito.when(KeyManagerHolder.getKeyManagerInstance("carbon.super", "default")).thenReturn(keyManager);
    KeyManagerConfiguration keyManagerConfiguration = new KeyManagerConfiguration();
    Mockito.when(keyManager.getKeyManagerConfiguration()).thenReturn(keyManagerConfiguration);
    applicationRegistrationSimpleWorkflowExecutor = new ApplicationRegistrationSimpleWorkflowExecutor();

}
 
Example 20
Source Project: docs-apim   Source File: 103334717.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void complete(WorkflowDTO workflowDTO) throws WorkflowException{
	workflowDTO.setUpdatedTime(System.currentTimeMillis());
       super.complete(workflowDTO);

	ApiMgtDAO apiMgtDAO = new ApiMgtDAO();
	try {
		apiMgtDAO.updateSubscriptionStatus(
				Integer.parseInt(workflowDTO.getWorkflowReference()),
				APIConstants.SubscriptionStatus.UNBLOCKED);
	} catch (APIManagementException e) {
		throw new WorkflowException(
				"Could not complete subscription creation workflow", e);
	}
}
 
Example 21
Source Project: carbon-apimgt   Source File: AlertTypesPublisher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param checkedAlertList Comma separated checked list ids.
 * @param emailList Comma separated email list.
 * @param userName user name
 * @param agent publisher "publisher" store "store" admin dashboard "admin-dashboard".
 * @param checkedAlertListValues alert type name lists.
 * @throws APIManagementException
 */
public void saveAndPublishAlertTypesEvent(String checkedAlertList, String emailList, String userName, String agent,
        String checkedAlertListValues) throws APIManagementException {

    if (!enabled) {
        throw new APIManagementException("Data publisher is not enabled");
    }

    if (publisher == null) {
        this.initializeDataPublisher();
    }

    ApiMgtDAO apiMgtDAO = getApiMgtdao();
    //data persist in the database.
    apiMgtDAO.addAlertTypesConfigInfo(userName, emailList, checkedAlertList, agent);
    //set DTO
    AlertTypeDTO alertTypeDTO = new AlertTypeDTO();
    alertTypeDTO.setAlertTypes(checkedAlertListValues);
    alertTypeDTO.setEmails(emailList);
    alertTypeDTO.setUserName(userName);
    if ("publisher".equals(agent)) {
        alertTypeDTO.setPublisher(true);
        alertTypeDTO.setSubscriber(false);
        alertTypeDTO.setAdmin(false);
    } else if ("subscriber".equals(agent)) {
        alertTypeDTO.setSubscriber(true);
        alertTypeDTO.setPublisher(false);
        alertTypeDTO.setAdmin(false);
    } else if ("admin-dashboard".equals(agent)) {
        alertTypeDTO.setSubscriber(false);
        alertTypeDTO.setPublisher(false);
        alertTypeDTO.setAdmin(true);
    }
    publisher.publishEvent(alertTypeDTO);

}
 
Example 22
Source Project: carbon-apimgt   Source File: AlertTypesPublisher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method will delete all the data relating to the alert subscription by given user Name.
 * @param userName logged in users name.
 */
public void unSubscribe(String userName, String agent) throws APIManagementException {

    if (!enabled) {
        throw new APIManagementException("Data publisher is not enabled");
    }

    if (publisher == null) {
        this.initializeDataPublisher();
    }

    ApiMgtDAO apiMgtDAO = getApiMgtdao();
    //data persist in the database.
    apiMgtDAO.unSubscribeAlerts(userName, agent);
    //set DTO
    AlertTypeDTO alertTypeDTO = new AlertTypeDTO();
    alertTypeDTO.setAlertTypes("");
    alertTypeDTO.setEmails("");
    alertTypeDTO.setUserName(userName);
    if ("publisher".equals(agent)) {
        alertTypeDTO.setPublisher(true);
        alertTypeDTO.setSubscriber(false);
        alertTypeDTO.setAdmin(false);
    } else if ("subscriber".equals(agent)) {
        alertTypeDTO.setSubscriber(true);
        alertTypeDTO.setPublisher(false);
        alertTypeDTO.setAdmin(false);
    } else if ("admin-dashboard".equals(agent)) {
        alertTypeDTO.setSubscriber(false);
        alertTypeDTO.setPublisher(false);
        alertTypeDTO.setAdmin(true);
    }
    publisher.publishEvent(alertTypeDTO);

}
 
Example 23
Source Project: carbon-apimgt   Source File: AlertTypesPublisherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void saveAndPublishAlertTypesEvent() throws Exception {
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    AlertTypesPublisher alertTypesPublisher = new AlertTypePublisherWrapper(apiMgtDAO);
    alertTypesPublisher.enabled = true;
    alertTypesPublisher.skipEventReceiverConnection = false;
    alertTypesPublisher.publisher = apiMgtUsageDataPublisher;
    alertTypesPublisher.saveAndPublishAlertTypesEvent("abc", "[email protected]", "admin", "subscriber", "aa");
}
 
Example 24
Source Project: carbon-apimgt   Source File: AlertTypesPublisherTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void saveAlertFromAdminDashboard() throws Exception {
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    AlertTypesPublisher alertTypesPublisher = new AlertTypePublisherWrapper(apiMgtDAO, apiMgtUsageDataPublisher);
    alertTypesPublisher.enabled = true;
    alertTypesPublisher.skipEventReceiverConnection = false;
    alertTypesPublisher.saveAndPublishAlertTypesEvent("abc", "[email protected]", "admin", "admin-dashboard", "aa");
}
 
Example 25
Source Project: carbon-apimgt   Source File: APIKeyValidationService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 26
Source Project: carbon-apimgt   Source File: AlertTypesPublisher1Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void saveAndPublishAlertTypesEvent() throws Exception {
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    APIManagerAnalyticsConfiguration apiManagerAnalyticsConfiguration = Mockito.mock
            (APIManagerAnalyticsConfiguration.class);
    PowerMockito.mockStatic(APIManagerAnalyticsConfiguration.class);
    PowerMockito.mockStatic(DataPublisherUtil.class);
    PowerMockito.mockStatic(APIUtil.class);
    BDDMockito.given(APIManagerAnalyticsConfiguration.getInstance()).willReturn(apiManagerAnalyticsConfiguration);
    BDDMockito.given(DataPublisherUtil.getApiManagerAnalyticsConfiguration()).willReturn
            (apiManagerAnalyticsConfiguration);
    JSONObject obj = null; //retun obj is not validated.
    String query1 = "select 'admin' as userId, 'abc' as alertTypes, '[email protected]' as emails, true as isSubscriber, "
            + "false as isPublisher, false as isAdmin update or insert into ApimAlertStakeholderInfo"
            + " set ApimAlertStakeholderInfo.userId = userId, "
            + "ApimAlertStakeholderInfo.alertTypes = alertTypes , ApimAlertStakeholderInfo.emails = emails ,"
            + " ApimAlertStakeholderInfo.isSubscriber = isSubscriber, ApimAlertStakeholderInfo.isPublisher = isPublisher, "
            + "ApimAlertStakeholderInfo.isAdmin = isAdmin on ApimAlertStakeholderInfo.userId == userId and "
            + "ApimAlertStakeholderInfo.isSubscriber == isSubscriber";
    String query2 = "select 'admin' as userId, 'abc' as alertTypes, '[email protected]' as emails, false as isSubscriber, "
            + "false as isPublisher, true as isAdmin update or insert into ApimAlertStakeholderInfo set "
            + "ApimAlertStakeholderInfo.userId = userId, "
            + "ApimAlertStakeholderInfo.alertTypes = alertTypes , ApimAlertStakeholderInfo.emails = emails ,"
            + " ApimAlertStakeholderInfo.isSubscriber = isSubscriber, ApimAlertStakeholderInfo.isPublisher = isPublisher, "
            + "ApimAlertStakeholderInfo.isAdmin = isAdmin on ApimAlertStakeholderInfo.userId == userId and "
            + "ApimAlertStakeholderInfo.isAdmin == isAdmin";
    BDDMockito.given(APIUtil.executeQueryOnStreamProcessor("APIM_STAKEHOLDER_ALERT", query1)).willReturn(obj);
    BDDMockito.given(APIUtil.executeQueryOnStreamProcessor("APIM_STAKEHOLDER_ALERT", query2)).willReturn(obj);
    AlertTypesPublisher alertTypesPublisher = new AlertTypesPublisherWrapper(apiMgtDAO);
    alertTypesPublisher.publisher = apiMgtUsageDataPublisher;
    alertTypesPublisher.enabled = true;
    alertTypesPublisher.skipEventReceiverConnection = false;
    alertTypesPublisher.saveAndPublishAlertTypesEvent("abc", "[email protected]", "admin", "subscriber", "aa");
    alertTypesPublisher.saveAndPublishAlertTypesEvent("abc", "[email protected]", "admin", "admin-dashboard", "aa");
}
 
Example 27
Source Project: carbon-apimgt   Source File: AlertTypesPublisher1Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void saveAlertWhileDatabaseConnectionFailed() throws APIManagementException {
    String checkedAlertList = "health-availability";
    String emailList = "[email protected]";
    String userName = "[email protected]";
    String agent = "publisher";
    String checkedAlertListValues = "true";
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    APIMgtUsageDataPublisher apiMgtUsageDataPublisher = Mockito.mock(APIMgtUsageDataPublisher.class);
    APIManagerAnalyticsConfiguration apiManagerAnalyticsConfiguration = Mockito.mock
            (APIManagerAnalyticsConfiguration.class);
    PowerMockito.mockStatic(APIManagerAnalyticsConfiguration.class);
    PowerMockito.mockStatic(DataPublisherUtil.class);
    BDDMockito.given(APIManagerAnalyticsConfiguration.getInstance()).willReturn(apiManagerAnalyticsConfiguration);
    BDDMockito.given(DataPublisherUtil.getApiManagerAnalyticsConfiguration()).willReturn
            (apiManagerAnalyticsConfiguration);
    AlertTypesPublisher alertTypesPublisher = new AlertTypesPublisherWrapper(apiMgtDAO);
    alertTypesPublisher.publisher = apiMgtUsageDataPublisher;
    alertTypesPublisher.enabled = true;
    alertTypesPublisher.skipEventReceiverConnection = false;
    Mockito.doThrow(APIManagementException.class).when(apiMgtDAO).addAlertTypesConfigInfo(userName, emailList,
            checkedAlertList, agent);
    try{
        alertTypesPublisher.saveAndPublishAlertTypesEvent(checkedAlertList, emailList, userName, agent,
                checkedAlertListValues);
    }catch (Exception e){
        if (e instanceof APIManagementException){
            Assert.assertTrue(true);
        }else{
            Assert.assertTrue(false);
        }
    }
}
 
Example 28
Source Project: carbon-apimgt   Source File: ExpiredJWTCleaner.java    License: Apache License 2.0 5 votes vote down vote up
private void cleanExpiredTokens() {

        ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
        try {
            //Remove expired JWTs from revoke table
            apiMgtDAO.removeExpiredJWTs();
            lastUpdatedTime = System.currentTimeMillis();
            if (log.isDebugEnabled()) {
                log.debug("Last JWT token cleanup performed at :" + new Date(lastUpdatedTime));

            }
        } catch (APIManagementException e) {
            log.error("Unable to cleanup expired JWT tokens from revoke table", e);
        }
    }
 
Example 29
@Before
public void init() {
    applicationDeletionSimpleWorkflowExecutor = new ApplicationDeletionSimpleWorkflowExecutor();
    PowerMockito.mockStatic(ApiMgtDAO.class);
    apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    PowerMockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    workflowDTO = new ApplicationWorkflowDTO();
    workflowDTO.setWorkflowReference("1");
    application = new Application("test", new Subscriber("testUser"));
    workflowDTO.setApplication(application);
}
 
Example 30
Source Project: carbon-apimgt   Source File: AMDefaultKeyManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method will be used to attach a Scope in the authorization server to a API resource.
 *
 * @param api          API
 * @param uriTemplates URITemplate set with attached scopes
 * @throws APIManagementException if an error occurs while attaching scope to resource
 */
@Override
public void attachResourceScopes(API api, Set<URITemplate> uriTemplates)
        throws APIManagementException {

    //TODO: remove after scope validation from swagger completes
    ApiMgtDAO.getInstance().addResourceScopes(api, uriTemplates, tenantDomain);
}