Search in sources :

Example 61 with LifeCycle

use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.

the class APIProviderImpl method checkAndChangeAPILCCheckListItem.

/**
 * This method is to set a lifecycle check list item given the APIIdentifier and the checklist item name.
 * If the given item not in the allowed lifecycle check items list or item is already checked, this will stay
 * silent and return false. Otherwise, the checklist item will be updated and returns true.
 *
 * @param apiIdentifier  APIIdentifier
 * @param checkItemName  Name of the checklist item
 * @param checkItemValue Value to be set to the checklist item
 * @return boolean value representing success not not
 * @throws APIManagementException
 */
@Override
public boolean checkAndChangeAPILCCheckListItem(APIIdentifier apiIdentifier, String checkItemName, boolean checkItemValue) throws APIManagementException {
    Map<String, Object> lifeCycleData = getAPILifeCycleData(apiIdentifier);
    if (lifeCycleData != null && lifeCycleData.get(APIConstants.LC_CHECK_ITEMS) != null && lifeCycleData.get(APIConstants.LC_CHECK_ITEMS) instanceof ArrayList) {
        List checkListItems = (List) lifeCycleData.get(APIConstants.LC_CHECK_ITEMS);
        for (Object item : checkListItems) {
            if (item instanceof CheckListItem) {
                CheckListItem checkListItem = (CheckListItem) item;
                int index = Integer.parseInt(checkListItem.getOrder());
                if (checkListItem.getName().equals(checkItemName)) {
                    changeAPILCCheckListItems(apiIdentifier, index, checkItemValue);
                    return true;
                }
            }
        }
    }
    return false;
}
Also used : CheckListItem(org.wso2.carbon.governance.custom.lifecycles.checklist.util.CheckListItem) ArrayList(java.util.ArrayList) JSONObject(org.json.simple.JSONObject) ArrayList(java.util.ArrayList) List(java.util.List)

Example 62 with LifeCycle

use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.

the class APIProviderImpl method changeLifeCycleStatusToPublish.

private void changeLifeCycleStatusToPublish(APIProductIdentifier apiIdentifier) throws APIManagementException {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(this.tenantDomain, true);
        String productArtifactId = registry.get(APIUtil.getAPIProductPath(apiIdentifier)).getUUID();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(productArtifactId);
        if (apiArtifact != null) {
            apiArtifact.invokeAction("Publish", APIConstants.API_LIFE_CYCLE);
            if (log.isDebugEnabled()) {
                String logMessage = "API Product Status changed successfully. API Product Name: " + apiIdentifier.getName();
                log.debug(logMessage);
            }
        }
    } catch (RegistryException e) {
        throw new APIManagementException("Error while Changing Lifecycle status of API Product " + apiIdentifier.getName(), e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 63 with LifeCycle

use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.

the class APIProviderImpl method addAPI.

/**
 * Adds a new API to the Store
 *
 * @param api API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to add API
 */
public API addAPI(API api) throws APIManagementException {
    validateApiInfo(api);
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
    validateResourceThrottlingTiers(api, tenantDomain);
    validateKeyManagers(api);
    String apiName = api.getId().getApiName();
    String provider = APIUtil.replaceEmailDomain(api.getId().getProviderName());
    if (api.isEndpointSecured() && StringUtils.isEmpty(api.getEndpointUTPassword())) {
        String errorMessage = "Empty password is given for endpointSecurity when creating API " + apiName;
        throw new APIManagementException(errorMessage);
    }
    // Validate Transports
    validateAndSetTransports(api);
    validateAndSetAPISecurity(api);
    RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
    // Add default API LC if it is not there
    try {
        if (!CommonUtil.lifeCycleExists(APIConstants.API_LIFE_CYCLE, registryService.getConfigSystemRegistry(tenantId))) {
            String defaultLifecyclePath = CommonUtil.getDefaltLifecycleConfigLocation() + File.separator + APIConstants.API_LIFE_CYCLE + APIConstants.XML_EXTENSION;
            File file = new File(defaultLifecyclePath);
            String content = null;
            if (file != null && file.exists()) {
                content = FileUtils.readFileToString(file);
            }
            if (content != null) {
                CommonUtil.addLifecycle(content, registryService.getConfigSystemRegistry(tenantId), CommonUtil.getRootSystemRegistry(tenantId));
            }
        }
    } catch (RegistryException e) {
        handleException("Error occurred while adding default APILifeCycle.", e);
    } catch (IOException e) {
        handleException("Error occurred while loading APILifeCycle.xml.", e);
    } catch (XMLStreamException e) {
        handleException("Error occurred while adding default API LifeCycle.", e);
    }
    // Set version timestamp to the API
    String latestTimestamp = calculateVersionTimestamp(provider, apiName, api.getId().getVersion(), api.getOrganization());
    api.setVersionTimestamp(latestTimestamp);
    try {
        PublisherAPI addedAPI = apiPersistenceInstance.addAPI(new Organization(api.getOrganization()), APIMapper.INSTANCE.toPublisherApi(api));
        api.setUuid(addedAPI.getId());
        api.setCreatedTime(addedAPI.getCreatedTime());
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Error while persisting API ", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("API details successfully added to the registry. API Name: " + api.getId().getApiName() + ", API Version : " + api.getId().getVersion() + ", API context : " + api.getContext());
    }
    int tenantId = APIUtil.getInternalOrganizationId(api.getOrganization());
    addAPI(api, tenantId);
    JSONObject apiLogObject = new JSONObject();
    apiLogObject.put(APIConstants.AuditLogConstants.NAME, api.getId().getApiName());
    apiLogObject.put(APIConstants.AuditLogConstants.CONTEXT, api.getContext());
    apiLogObject.put(APIConstants.AuditLogConstants.VERSION, api.getId().getVersion());
    apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, api.getId().getProviderName());
    APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(), APIConstants.AuditLogConstants.CREATED, this.username);
    if (log.isDebugEnabled()) {
        log.debug("API details successfully added to the API Manager Database. API Name: " + api.getId().getApiName() + ", API Version : " + api.getId().getVersion() + ", API context : " + api.getContext());
    }
    if (APIUtil.isAPIManagementEnabled()) {
        Cache contextCache = APIUtil.getAPIContextCache();
        Boolean apiContext = null;
        Object cachedObject = contextCache.get(api.getContext());
        if (cachedObject != null) {
            apiContext = Boolean.valueOf(cachedObject.toString());
        }
        if (apiContext == null) {
            contextCache.put(api.getContext(), Boolean.TRUE);
        }
    }
    if ("null".equals(api.getAccessControlRoles())) {
        api.setAccessControlRoles(null);
    }
    // notify key manager with API addition
    registerOrUpdateResourceInKeyManager(api, tenantDomain);
    return api;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) XMLStreamException(javax.xml.stream.XMLStreamException) JSONObject(org.json.simple.JSONObject) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) JSONObject(org.json.simple.JSONObject) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File) Cache(javax.cache.Cache)

Example 64 with LifeCycle

use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.

the class APIProviderImpl method createAPI.

/**
 * Create an Api
 *
 * @param api API
 * @throws APIManagementException if failed to create API
 */
protected String createAPI(API api) throws APIManagementException {
    GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
    if (artifactManager == null) {
        String errorMessage = "Failed to retrieve artifact manager when creating API " + api.getId().getApiName();
        log.error(errorMessage);
        throw new APIManagementException(errorMessage);
    }
    if (api.isEndpointSecured() && StringUtils.isEmpty(api.getEndpointUTPassword())) {
        String errorMessage = "Empty password is given for endpointSecurity when creating API " + api.getId().getApiName();
        throw new APIManagementException(errorMessage);
    }
    // Validate Transports
    validateAndSetTransports(api);
    validateAndSetAPISecurity(api);
    boolean transactionCommitted = false;
    String apiUUID = null;
    try {
        registry.beginTransaction();
        GenericArtifact genericArtifact = artifactManager.newGovernanceArtifact(new QName(api.getId().getApiName()));
        if (genericArtifact == null) {
            String errorMessage = "Generic artifact is null when creating API " + api.getId().getApiName();
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        GenericArtifact artifact = APIUtil.createAPIArtifactContent(genericArtifact, api);
        artifactManager.addGenericArtifact(artifact);
        // Attach the API lifecycle
        artifact.attachLifecycle(APIConstants.API_LIFE_CYCLE);
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        String providerPath = APIUtil.getAPIProviderPath(api.getId());
        // provider ------provides----> API
        registry.addAssociation(providerPath, artifactPath, APIConstants.PROVIDER_ASSOCIATION);
        Set<String> tagSet = api.getTags();
        if (tagSet != null) {
            for (String tag : tagSet) {
                registry.applyTag(artifactPath, tag);
            }
        }
        if (APIUtil.isValidWSDLURL(api.getWsdlUrl(), false)) {
            String path = APIUtil.createWSDL(registry, api);
            updateWSDLUriInAPIArtifact(path, artifactManager, artifact, artifactPath);
        }
        if (api.getWsdlResource() != null) {
            String path = APIUtil.saveWSDLResource(registry, api);
            updateWSDLUriInAPIArtifact(path, artifactManager, artifact, artifactPath);
        }
        // write API Status to a separate property. This is done to support querying APIs using custom query (SQL)
        // to gain performance
        String apiStatus = api.getStatus();
        saveAPIStatus(artifactPath, apiStatus);
        String visibleRolesList = api.getVisibleRoles();
        String[] visibleRoles = new String[0];
        if (visibleRolesList != null) {
            visibleRoles = visibleRolesList.split(",");
        }
        String publisherAccessControlRoles = api.getAccessControlRoles();
        updateRegistryResources(artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
        registry.commitTransaction();
        transactionCommitted = true;
        if (log.isDebugEnabled()) {
            String logMessage = "API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + " created";
            log.debug(logMessage);
        }
        apiUUID = artifact.getId();
    } catch (RegistryException e) {
        try {
            registry.rollbackTransaction();
        } catch (RegistryException re) {
            // Throwing an error here would mask the original exception
            log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
        }
        handleException("Error while performing registry transaction operation", e);
    } catch (APIManagementException e) {
        handleException("Error while creating API", e);
    } finally {
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            handleException("Error while rolling back the transaction for API: " + api.getId().getApiName(), ex);
        }
    }
    return apiUUID;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) QName(javax.xml.namespace.QName) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 65 with LifeCycle

use of org.wso2.carbon.apimgt.impl.importexport.lifecycle.LifeCycle in project carbon-apimgt by wso2.

the class APIProviderImpl method sendLCStateChangeNotification.

/**
 * @param apiName           Name of the API
 * @param apiType           API Type
 * @param apiContext        API or Product context
 * @param apiVersion        API or Product version
 * @param targetStatus      Target Lifecycle status
 * @param provider          Provider of the API or Product
 * @param apiOrApiProductId unique ID of API or API product
 * @param uuid              unique UUID of API or API Product
 */
private void sendLCStateChangeNotification(String apiName, String apiType, String apiContext, String apiVersion, String targetStatus, String provider, int apiOrApiProductId, String uuid) {
    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_LIFECYCLE_CHANGE.name(), tenantId, tenantDomain, apiName, apiOrApiProductId, uuid, apiVersion, apiType, apiContext, APIUtil.replaceEmailDomainBack(provider), targetStatus);
    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
}
Also used : APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent)

Aggregations

Test (org.testng.annotations.Test)20 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)20 API (org.wso2.carbon.apimgt.core.models.API)20 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)19 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)13 ArrayList (java.util.ArrayList)12 HashMap (java.util.HashMap)11 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)10 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)10 LifecycleException (org.wso2.carbon.lcm.core.exception.LifecycleException)10 JSONObject (org.json.simple.JSONObject)8 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)8 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)7 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)7 List (java.util.List)6 IOException (java.io.IOException)5 Map (java.util.Map)5 FaultGatewaysException (org.wso2.carbon.apimgt.api.FaultGatewaysException)4