Search in sources :

Example 11 with APIProvider

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

the class ThrottlingApiServiceImpl method throttlingPoliciesApplicationPolicyIdGet.

/**
 * Get a specific Application Policy by its uuid
 *
 * @param policyId        uuid of the policy
 * @return Matched Application Throttle Policy by the given name
 */
@Override
public Response throttlingPoliciesApplicationPolicyIdGet(String policyId, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String username = RestApiCommonUtil.getLoggedInUsername();
        // This will give PolicyNotFoundException if there's no policy exists with UUID
        ApplicationPolicy appPolicy = apiProvider.getApplicationPolicyByUUID(policyId);
        if (!RestApiAdminUtils.isPolicyAccessibleToUser(username, appPolicy)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APP_POLICY, policyId, log);
        }
        ApplicationThrottlePolicyDTO policyDTO = ApplicationThrottlePolicyMappingUtil.fromApplicationThrottlePolicyToDTO(appPolicy);
        return Response.ok().entity(policyDTO).build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_POLICY, policyId, e, log);
        } else {
            String errorMessage = "Error while retrieving Application level policy: " + policyId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 12 with APIProvider

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

the class APIProviderImplTest method testGetApplicationPolicyByUUID.

@Test
public void testGetApplicationPolicyByUUID() throws APIManagementException {
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    ApplicationPolicy applicationPolicy = Mockito.mock(ApplicationPolicy.class);
    Mockito.when(apimgtDAO.getApplicationPolicyByUUID("1111")).thenReturn(applicationPolicy, null);
    apiProvider.getApplicationPolicyByUUID("1111");
    try {
        assertNotNull(apiProvider.getApplicationPolicyByUUID("1111"));
    } catch (APIManagementException e) {
        assertEquals("Application Policy: 1111 was not found.", e.getMessage());
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 13 with APIProvider

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

the class APIProviderImplTest method testUpdateAPIforStateChange_ToPublished.

@Test
public void testUpdateAPIforStateChange_ToPublished() throws RegistryException, UserStoreException, APIManagementException, FaultGatewaysException, APIPersistenceException, XMLStreamException {
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
    Set<String> environments = new HashSet<String>();
    environments.add("Production");
    environments.add("Sandbox");
    API api = new API(apiId);
    api.setContext("/test");
    api.setStatus(APIConstants.CREATED);
    api.setAsDefaultVersion(true);
    api.setEnvironments(environments);
    api.setOrganization("carbon.super");
    Mockito.when(apimgtDAO.getPublishedDefaultVersion(apiId)).thenReturn("1.0.0");
    Map<String, String> failedGWEnv = new HashMap<String, String>();
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, null, null);
    Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
    ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
    PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
    apiProvider.addAPI(api);
    // Mock Updating API
    Resource apiSourceArtifact = Mockito.mock(Resource.class);
    Mockito.when(apiSourceArtifact.getUUID()).thenReturn("12640983654");
    String apiSourcePath = "path";
    PowerMockito.when(APIUtil.getAPIPath(api.getId())).thenReturn(apiSourcePath);
    PowerMockito.when(apiProvider.registry.get(apiSourcePath)).thenReturn(apiSourceArtifact);
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("CREATED");
    Mockito.when(artifactManager.getGenericArtifact(apiSourceArtifact.getUUID())).thenReturn(artifact);
    PowerMockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
    Mockito.when(artifact.getId()).thenReturn("12640983654");
    PowerMockito.when(GovernanceUtils.getArtifactPath(apiProvider.registry, "12640983654")).thenReturn(apiSourcePath);
    Mockito.doNothing().when(artifactManager).updateGenericArtifact(artifact);
    apiProvider.updateAPIforStateChange(api, APIConstants.CREATED, APIConstants.PUBLISHED);
    // From the 2 environments, only 1 was successful
    Assert.assertEquals(2, api.getEnvironments().size());
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) RealmService(org.wso2.carbon.user.core.service.RealmService) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) HashSet(java.util.HashSet) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 14 with APIProvider

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

the class APIProviderImplTest method testGetCustomApiFaultSequences.

@Test
public void testGetCustomApiFaultSequences() throws Exception {
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.1");
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    mockSequences(APIConstants.API_CUSTOM_FAULTSEQUENCE_LOCATION, APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT, apiId);
    List<String> sequenceList = apiProvider.getCustomApiFaultSequences(apiId);
    Assert.assertNotNull(sequenceList);
    Assert.assertEquals(1, sequenceList.size());
    // OMException when building OMElement
    PowerMockito.when(APIUtil.buildOMElement(any(InputStream.class))).thenThrow(new OMException());
    apiProvider.getCustomApiFaultSequences(apiId);
    // org.wso2.carbon.registry.api.RegistryException
    ServiceReferenceHolder sh = PowerMockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(sh);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
    UserRegistry registry = Mockito.mock(UserRegistry.class);
    PowerMockito.when(registryService.getGovernanceSystemRegistry(Matchers.anyInt())).thenReturn(registry);
    Mockito.when(registry.resourceExists(APIUtil.getSequencePath(apiId, APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT))).thenThrow(org.wso2.carbon.registry.api.RegistryException.class);
    String msg = "Error while processing the " + APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT + " sequences of " + apiId + " in the registry";
    try {
        apiProvider.getCustomApiFaultSequences(apiId);
    } catch (APIManagementException e) {
        Assert.assertEquals(msg, e.getMessage());
    }
    // Registry Exception
    PowerMockito.when(registryService.getGovernanceSystemRegistry(Matchers.anyInt())).thenThrow(RegistryException.class);
    String msg1 = "Error while retrieving registry for tenant -1";
    try {
        apiProvider.getCustomApiFaultSequences(apiId);
    } catch (APIManagementException e) {
        Assert.assertEquals(msg1, e.getMessage());
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) InputStream(java.io.InputStream) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) OMException(org.apache.axiom.om.OMException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 15 with APIProvider

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

the class WorkflowUtils method completeStateChangeWorkflow.

/**
 * Complete the lifecycle state change workflow
 *
 * @param workflowDTO Workflow DTO object
 * @throws WorkflowException Exception when completing the workflow
 */
protected static void completeStateChangeWorkflow(WorkflowDTO workflowDTO) throws WorkflowException {
    String externalWorkflowRef = workflowDTO.getExternalWorkflowReference();
    try {
        ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
        Workflow workflow = apiMgtDAO.getworkflowReferenceByExternalWorkflowReference(externalWorkflowRef);
        String apiName = workflow.getMetadata("ApiName");
        String action = workflow.getMetadata("Action");
        String providerName = workflow.getMetadata("ApiProvider");
        String version = workflow.getMetadata("ApiVersion");
        String invoker = workflow.getMetadata("Invoker");
        String currentStatus = workflow.getMetadata("CurrentState");
        int tenantId = workflowDTO.getTenantId();
        try {
            // tenant flow is already started from the rest api service impl. no need to start from here
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(invoker);
            Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(invoker, tenantId);
            APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, version);
            GenericArtifact apiArtifact = APIUtil.getAPIArtifact(apiIdentifier, registry);
            if (WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) {
                String targetStatus;
                apiArtifact.invokeAction(action, APIConstants.API_LIFE_CYCLE);
                targetStatus = apiArtifact.getLifecycleState();
                if (!currentStatus.equals(targetStatus)) {
                    apiMgtDAO.recordAPILifeCycleEvent(apiArtifact.getId(), currentStatus.toUpperCase(), targetStatus.toUpperCase(), invoker, tenantId);
                }
                if (log.isDebugEnabled()) {
                    String logMessage = "API Status changed successfully. API Name: " + apiIdentifier.getApiName() + ", API " + "Version " + apiIdentifier.getVersion() + ", New Status : " + targetStatus;
                    log.debug(logMessage);
                }
            }
        } catch (RegistryException e) {
            String errorMsg = "Could not complete api state change workflow";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        }
    } catch (APIManagementException e) {
        String errorMsg = "Could not complete api state change workflow";
        log.error(errorMsg, e);
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Workflow(org.wso2.carbon.apimgt.api.model.Workflow) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)207 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)198 API (org.wso2.carbon.apimgt.api.model.API)92 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)83 Test (org.junit.Test)82 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)82 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)73 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)65 IOException (java.io.IOException)40 ArrayList (java.util.ArrayList)36 URISyntaxException (java.net.URISyntaxException)34 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)32 URI (java.net.URI)31 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)31 JSONObject (org.json.simple.JSONObject)29 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)29 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)29 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)28 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)28 Documentation (org.wso2.carbon.apimgt.api.model.Documentation)23