Search in sources :

Example 26 with FaultGatewaysException

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

the class ApisApiServiceImpl method updateAPISwagger.

/**
 * Updates the swagger definition of an existing API
 *
 * @param apiId             API identifier
 * @param apiDefinition     Swagger definition
 * @param url               Swagger definition URL
 * @param fileInputStream   Swagger definition input file content
 * @param fileDetail        file meta information as Attachment
 * @param ifMatch           If-match header value
 * @return updated swagger document of the API
 */
@Override
public Response updateAPISwagger(String apiId, String ifMatch, String apiDefinition, String url, InputStream fileInputStream, Attachment fileDetail, MessageContext messageContext) {
    try {
        String updatedSwagger;
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().getStatus());
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // Handle URL and file based definition imports
        if (url != null || fileInputStream != null) {
            // Validate and retrieve the OpenAPI definition
            Map validationResponseMap = validateOpenAPIDefinition(url, fileInputStream, fileDetail, null, true, false);
            APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
            if (!validationResponse.isValid()) {
                RestApiUtil.handleBadRequest(validationResponse.getErrorItems(), log);
            }
            updatedSwagger = PublisherCommonUtils.updateSwagger(apiId, validationResponse, false, organization);
        } else {
            updatedSwagger = updateSwagger(apiId, apiDefinition, organization);
        }
        return Response.ok().entity(updatedSwagger).build();
    } catch (APIManagementException e) {
        // to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while updating swagger definition of API: " + apiId, e, log);
        } else {
            String errorMessage = "Error while updating the swagger definition of the API: " + apiId + " - " + e.getMessage();
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (FaultGatewaysException e) {
        String errorMessage = "Error while updating API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 27 with FaultGatewaysException

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

the class ApisApiServiceImpl method updateAPIResourcePoliciesByPolicyId.

/**
 * Update the resource policies(inflow/outflow) given the resource id.
 *
 * @param apiId  API ID
 * @param resourcePolicyId resource policy id
 * @param body resource policy content
 * @param ifMatch If-Match header value
 * @return json response of the updated sequence content
 */
@Override
public Response updateAPIResourcePoliciesByPolicyId(String apiId, String resourcePolicyId, ResourcePolicyInfoDTO body, String ifMatch, MessageContext messageContext) {
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider provider = RestApiCommonUtil.getLoggedInUserProvider();
        API api = provider.getAPIbyUUID(apiId, organization);
        if (api == null) {
            throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
        }
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(api.getStatus());
        if (APIConstants.API_TYPE_SOAPTOREST.equals(api.getType())) {
            if (StringUtils.isEmpty(resourcePolicyId)) {
                String errorMessage = "Resource id should not be empty to update a resource policy.";
                RestApiUtil.handleBadRequest(errorMessage, log);
            }
            boolean isValidSchema = RestApiPublisherUtils.validateXMLSchema(body.getContent());
            if (isValidSchema) {
                List<SOAPToRestSequence> sequence = api.getSoapToRestSequences();
                for (SOAPToRestSequence soapToRestSequence : sequence) {
                    if (soapToRestSequence.getUuid().equals(resourcePolicyId)) {
                        soapToRestSequence.setContent(body.getContent());
                        break;
                    }
                }
                API originalAPI = provider.getAPIbyUUID(apiId, organization);
                provider.updateAPI(api, originalAPI);
                SequenceUtils.updateResourcePolicyFromRegistryResourceId(api.getId(), resourcePolicyId, body.getContent());
                String updatedPolicyContent = SequenceUtils.getResourcePolicyFromRegistryResourceId(api, resourcePolicyId);
                ResourcePolicyInfoDTO resourcePolicyInfoDTO = APIMappingUtil.fromResourcePolicyStrToInfoDTO(updatedPolicyContent);
                return Response.ok().entity(resourcePolicyInfoDTO).build();
            } else {
                String errorMessage = "Error while validating the resource policy xml content for the API : " + apiId;
                RestApiUtil.handleInternalServerError(errorMessage, log);
            }
        } else {
            String errorMessage = "The provided api with id: " + apiId + " is not a soap to rest converted api.";
            RestApiUtil.handleBadRequest(errorMessage, log);
        }
    } catch (APIManagementException | FaultGatewaysException e) {
        String errorMessage = "Error while retrieving the API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ResourcePolicyInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ResourcePolicyInfoDTO) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) SOAPToRestSequence(org.wso2.carbon.apimgt.api.model.SOAPToRestSequence)

Example 28 with FaultGatewaysException

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

the class APIProviderImplTest method testUpdateAPIforStateChange_ToRetiredWithFaultyGWs.

@Test
public void testUpdateAPIforStateChange_ToRetiredWithFaultyGWs() 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");
    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");
    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);
    Mockito.when(artifact.getId()).thenReturn("12640983654");
    PowerMockito.when(GovernanceUtils.getArtifactPath(apiProvider.registry, "12640983654")).thenReturn(apiSourcePath);
    Mockito.doNothing().when(artifactManager).updateGenericArtifact(artifact);
    WorkflowExecutorFactory wfe = PowerMockito.mock(WorkflowExecutorFactory.class);
    Mockito.when(WorkflowExecutorFactory.getInstance()).thenReturn(wfe);
    try {
        apiProvider.updateAPIforStateChange(api, APIConstants.CREATED, APIConstants.RETIRED);
    } catch (FaultGatewaysException e) {
        Assert.assertTrue(e.getFaultMap().contains("Failed to un-publish"));
    }
    Assert.assertEquals(1, api.getEnvironments().size());
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) QName(javax.xml.namespace.QName) WorkflowExecutorFactory(org.wso2.carbon.apimgt.impl.workflow.WorkflowExecutorFactory) Resource(org.wso2.carbon.registry.core.Resource) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) 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 29 with FaultGatewaysException

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

the class APIProviderImplTest method testChangeLifeCycleStatusAPIMgtException.

@Test(expected = APIManagementException.class)
public void testChangeLifeCycleStatusAPIMgtException() throws RegistryException, UserStoreException, APIManagementException, FaultGatewaysException, WorkflowException, XMLStreamException {
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    prepareForChangeLifeCycleStatus(apiProvider, apimgtDAO, apiId, artifact);
    GovernanceException exception = new GovernanceException(new APIManagementException("APIManagementException:" + "Error while retrieving Life cycle state"));
    Mockito.when(artifact.getLifecycleState()).thenThrow(exception);
    apiProvider.changeLifeCycleStatus(apiId, APIConstants.API_LC_ACTION_DEPRECATE, "org1");
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 30 with FaultGatewaysException

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

the class APIProviderImplTest method testUpdateAPI_WithStatusChange.

@Test(expected = APIManagementException.class)
public void testUpdateAPI_WithStatusChange() throws RegistryException, UserStoreException, APIManagementException, FaultGatewaysException, APIPersistenceException, XMLStreamException {
    APIIdentifier identifier = new APIIdentifier("admin", "API1", "1.0.0");
    API api = new API(identifier);
    api.setStatus(APIConstants.PUBLISHED);
    api.setVisibility("public");
    // API status change is not allowed in UpdateAPI(). Should throw an exception.
    API oldApi = new API(identifier);
    oldApi.setStatus(APIConstants.CREATED);
    oldApi.setVisibility("public");
    oldApi.setContext("/api1");
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, null, null);
    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);
    Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, oldApi)).thenReturn(artifact);
    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(oldApi);
    // mock has permission
    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);
    // API Status is CREATED and user has permission
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("CREATED");
    Mockito.when(artifactManager.getGenericArtifact(apiSourceArtifact.getUUID())).thenReturn(artifact);
    PowerMockito.when(APIUtil.hasPermission(null, APIConstants.Permissions.API_PUBLISH)).thenReturn(true);
    PowerMockito.when(APIUtil.hasPermission(null, APIConstants.Permissions.API_CREATE)).thenReturn(true);
    apiProvider.updateAPI(api, oldApi);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) 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) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

API (org.wso2.carbon.apimgt.api.model.API)26 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)25 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)20 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)18 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)18 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)16 HashMap (java.util.HashMap)11 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)11 Test (org.junit.Test)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)10 Map (java.util.Map)8 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)8 ArrayList (java.util.ArrayList)7 List (java.util.List)7 JSONObject (org.json.simple.JSONObject)6 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)6 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)6 HashSet (java.util.HashSet)5