Search in sources :

Example 41 with ApiTypeWrapper

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

the class ApisApiServiceImpl method changeAPILifecycle.

@Override
public Response changeAPILifecycle(String action, String apiId, String lifecycleChecklist, String ifMatch, MessageContext messageContext) {
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        ApiTypeWrapper apiWrapper = new ApiTypeWrapper(apiProvider.getAPIbyUUID(apiId, organization));
        APIStateChangeResponse stateChangeResponse = PublisherCommonUtils.changeApiOrApiProductLifecycle(action, apiWrapper, lifecycleChecklist, organization);
        // returns the current lifecycle state
        // todo try to prevent this call
        LifecycleStateDTO stateDTO = getLifecycleState(apiId, organization);
        WorkflowResponseDTO workflowResponseDTO = APIMappingUtil.toWorkflowResponseDTO(stateDTO, stateChangeResponse);
        return Response.ok().entity(workflowResponseDTO).build();
    } catch (APIManagementException e) {
        // Auth failure occurs when cross tenant accessing APIs. Sends 404, since we don't need 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 the lifecycle of API " + apiId, e, log);
        } else {
            RestApiUtil.handleInternalServerError("Error while updating lifecycle of API " + apiId, e, log);
        }
    }
    return null;
}
Also used : WorkflowResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.WorkflowResponseDTO) LifecycleStateDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.LifecycleStateDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 42 with ApiTypeWrapper

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

the class APIProviderImplTest method testChangeLifeCycleStatusOfAPIProduct.

@Test
public void testChangeLifeCycleStatusOfAPIProduct() throws APIManagementException, FaultGatewaysException {
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    String provider = "admin";
    PrivilegedCarbonContext carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.doNothing().when(carbonContext).setUsername(Mockito.anyString());
    PowerMockito.doNothing().when(carbonContext).setTenantDomain(Mockito.anyString(), Mockito.anyBoolean());
    APIProduct product = createMockAPIProduct(provider);
    Mockito.when(apimgtDAO.getAPIProductId(product.getId())).thenReturn(1);
    WorkflowDTO workflowDTO = Mockito.mock(WorkflowDTO.class);
    Mockito.when(workflowDTO.getStatus()).thenReturn(WorkflowStatus.CREATED);
    Mockito.when(apimgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(1), WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)).thenReturn(workflowDTO);
    APIStateChangeResponse response = apiProvider.changeLifeCycleStatus("carbon.super", new ApiTypeWrapper(product), "Publish", null);
    Assert.assertNotNull(response);
}
Also used : PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 43 with ApiTypeWrapper

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

the class ImportUtils method updateWithThumbnail.

/**
 * This method update the API Product with the thumbnail image from imported API Product.
 *
 * @param imageFile      Image file
 * @param apiTypeWrapper API or API Product to update
 * @param apiProvider    API Provider
 * @throws APIManagementException If an error occurs when uploading the thumbnail of the API/API Product
 */
private static void updateWithThumbnail(File imageFile, ApiTypeWrapper apiTypeWrapper, APIProvider apiProvider) throws APIManagementException {
    Identifier identifier = apiTypeWrapper.getId();
    String fileName = imageFile.getName();
    String mimeType = URLConnection.guessContentTypeFromName(fileName);
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    if (StringUtils.isBlank(mimeType)) {
        try {
            // Check whether the icon is in .json format (UI icons are stored as .json)
            new JsonParser().parse(new FileReader(imageFile));
            mimeType = APIConstants.APPLICATION_JSON_MEDIA_TYPE;
        } catch (JsonParseException e) {
            // Here the exceptions were handled and logged that may arise when parsing the .json file,
            // and this will not break the flow of importing the API.
            // If the .json is wrong or cannot be found the API import process will still be carried out.
            log.error("Failed to read the thumbnail file. ", e);
        } catch (FileNotFoundException e) {
            log.error("Failed to find the thumbnail file. ", e);
        }
    }
    try (FileInputStream inputStream = new FileInputStream(imageFile.getAbsolutePath())) {
        String apiOrApiProductId = (!apiTypeWrapper.isAPIProduct()) ? apiTypeWrapper.getApi().getUuid() : apiTypeWrapper.getApiProduct().getUuid();
        PublisherCommonUtils.updateThumbnail(inputStream, mimeType, apiProvider, apiOrApiProductId, tenantDomain);
    } catch (FileNotFoundException e) {
        throw new APIManagementException("Icon for API/API Product: " + identifier.getName() + " is not found.", e, ExceptionCodes.from(ExceptionCodes.ERROR_UPLOADING_THUMBNAIL, identifier.getName(), identifier.getVersion()));
    } catch (IOException e) {
        throw new APIManagementException("Failed to read the image file of API/API Product: " + identifier.getName() + " from the archive.", e, ExceptionCodes.from(ExceptionCodes.ERROR_UPLOADING_THUMBNAIL, identifier.getName(), identifier.getVersion()));
    }
}
Also used : APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) FileNotFoundException(java.io.FileNotFoundException) FileReader(java.io.FileReader) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) FileInputStream(java.io.FileInputStream) JsonParser(com.google.gson.JsonParser)

Example 44 with ApiTypeWrapper

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

the class APIProviderImpl method makeAPIKeysForwardCompatible.

public void makeAPIKeysForwardCompatible(API api) throws APIManagementException {
    String provider = api.getId().getProviderName();
    String apiName = api.getId().getApiName();
    Set<String> versions = getAPIVersions(provider, apiName, api.getOrganization());
    APIVersionComparator comparator = new APIVersionComparator();
    List<API> sortedAPIs = new ArrayList<API>();
    for (String version : versions) {
        if (version.equals(api.getId().getVersion())) {
            continue;
        }
        // getAPI(new APIIdentifier(provider, apiName, version));
        API otherApi = new API(new APIIdentifier(provider, apiName, version));
        if (comparator.compare(otherApi, api) < 0 && !APIConstants.RETIRED.equals(otherApi.getStatus())) {
            sortedAPIs.add(otherApi);
        }
    }
    // Get the subscriptions from the latest api version first
    Collections.sort(sortedAPIs, comparator);
    apiMgtDAO.makeKeysForwardCompatible(new ApiTypeWrapper(api), sortedAPIs);
}
Also used : APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) ArrayList(java.util.ArrayList) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 45 with ApiTypeWrapper

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

the class APIProviderImpl method changeLifeCycleStatus.

/**
 * This method is to change registry lifecycle states for an API or API Product artifact
 *
 * @param orgId          UUID of the organization
 * @param apiTypeWrapper API Type Wrapper
 * @param action         Action which need to execute from registry lifecycle
 * @param checklist      checklist items
 * @return APIStateChangeResponse API workflow state and WorkflowResponse
 */
@Override
public APIStateChangeResponse changeLifeCycleStatus(String orgId, ApiTypeWrapper apiTypeWrapper, String action, Map<String, Boolean> checklist) throws APIManagementException, FaultGatewaysException {
    APIStateChangeResponse response = new APIStateChangeResponse();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(this.tenantDomain, true);
        String targetStatus;
        String providerName;
        String apiName;
        String apiContext;
        String apiType;
        String apiVersion;
        String currentStatus;
        String uuid;
        int apiOrApiProductId;
        boolean isApiProduct = apiTypeWrapper.isAPIProduct();
        String workflowType;
        if (isApiProduct) {
            APIProduct apiProduct = apiTypeWrapper.getApiProduct();
            providerName = apiProduct.getId().getProviderName();
            apiName = apiProduct.getId().getName();
            apiContext = apiProduct.getContext();
            apiType = apiProduct.getType();
            apiVersion = apiProduct.getId().getVersion();
            currentStatus = apiProduct.getState();
            uuid = apiProduct.getUuid();
            apiOrApiProductId = apiMgtDAO.getAPIProductId(apiTypeWrapper.getApiProduct().getId());
            workflowType = WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE;
        } else {
            API api = apiTypeWrapper.getApi();
            providerName = api.getId().getProviderName();
            apiName = api.getId().getApiName();
            apiContext = api.getContext();
            apiType = api.getType();
            apiVersion = api.getId().getVersion();
            currentStatus = api.getStatus();
            uuid = api.getUuid();
            apiOrApiProductId = apiMgtDAO.getAPIID(uuid);
            workflowType = WorkflowConstants.WF_TYPE_AM_API_STATE;
        }
        String gatewayVendor = apiMgtDAO.getGatewayVendorByAPIUUID(uuid);
        WorkflowStatus apiWFState = null;
        WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(apiOrApiProductId), workflowType);
        if (wfDTO != null) {
            apiWFState = wfDTO.getStatus();
        }
        // if the workflow has started, then executor should not fire again
        if (!WorkflowStatus.CREATED.equals(apiWFState)) {
            response = executeStateChangeWorkflow(currentStatus, action, apiName, apiContext, apiType, apiVersion, providerName, apiOrApiProductId, uuid, gatewayVendor, workflowType);
            // get the workflow state once the executor is executed.
            wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(apiOrApiProductId), workflowType);
            if (wfDTO != null) {
                apiWFState = wfDTO.getStatus();
                response.setStateChangeStatus(apiWFState.toString());
            } else {
                response.setStateChangeStatus(WorkflowStatus.APPROVED.toString());
            }
        }
        // apiWFState is null when simple wf executor is used because wf state is not stored in the db.
        if (WorkflowStatus.APPROVED.equals(apiWFState) || apiWFState == null) {
            targetStatus = LCManagerFactory.getInstance().getLCManager().getStateForTransition(action);
            apiPersistenceInstance.changeAPILifeCycle(new Organization(orgId), uuid, targetStatus);
            sendLCStateChangeNotification(apiName, apiType, apiContext, apiVersion, targetStatus, providerName, apiOrApiProductId, uuid);
            if (!isApiProduct) {
                API api = apiTypeWrapper.getApi();
                api.setOrganization(orgId);
                changeLifeCycle(api, currentStatus, targetStatus, checklist);
                // Sending Notifications to existing subscribers
                if (APIConstants.PUBLISHED.equals(targetStatus)) {
                    sendEmailNotification(api);
                }
            } else {
                APIProduct apiProduct = apiTypeWrapper.getApiProduct();
                apiProduct.setOrganization(orgId);
                changeLifecycle(apiProduct, currentStatus, targetStatus);
            }
            addLCStateChangeInDatabase(currentStatus, targetStatus, uuid);
            if (log.isDebugEnabled()) {
                String logMessage = "LC Status changed successfully for artifact with name: " + apiName + ", version " + apiVersion + ", New Status : " + targetStatus;
                log.debug(logMessage);
            }
            extractRecommendationDetails(apiTypeWrapper);
            return response;
        }
    } catch (APIPersistenceException e) {
        handleException("Error while accessing persistence layer", e);
    } catch (PersistenceException e) {
        handleException("Error while accessing lifecycle information ", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
    return response;
}
Also used : PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) APIStateWorkflowDTO(org.wso2.carbon.apimgt.impl.workflow.APIStateWorkflowDTO) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus)

Aggregations

ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)41 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)38 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)25 API (org.wso2.carbon.apimgt.api.model.API)24 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)24 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)16 URI (java.net.URI)14 URISyntaxException (java.net.URISyntaxException)14 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)14 Application (org.wso2.carbon.apimgt.api.model.Application)14 ArrayList (java.util.ArrayList)13 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)13 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)11 Tier (org.wso2.carbon.apimgt.api.model.Tier)10 Comment (org.wso2.carbon.apimgt.api.model.Comment)9 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)9 Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 SubscriptionAlreadyExistingException (org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException)7 Identifier (org.wso2.carbon.apimgt.api.model.Identifier)7