Search in sources :

Example 31 with PublisherAPI

use of org.wso2.carbon.apimgt.persistence.dto.PublisherAPI 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 32 with PublisherAPI

use of org.wso2.carbon.apimgt.persistence.dto.PublisherAPI in project carbon-apimgt by wso2.

the class APIProviderImpl method updateAPIforStateChange.

public boolean updateAPIforStateChange(API api, String currentStatus, String newStatus) throws APIManagementException, FaultGatewaysException {
    boolean isSuccess = false;
    String provider = api.getId().getProviderName();
    String providerTenantMode = api.getId().getProviderName();
    provider = APIUtil.replaceEmailDomain(provider);
    String name = api.getId().getApiName();
    String version = api.getId().getVersion();
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerTenantMode));
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        // API api = getAPI(apiId);
        if (api != null) {
            if (!currentStatus.equals(newStatus)) {
                api.setStatus(newStatus);
                // If API status changed to publish we should add it to recently added APIs list
                // this should happen in store-publisher cluster domain if deployment is distributed
                // IF new API published we will add it to recently added APIs
                Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME).removeAll();
                api.setAsPublishedDefaultVersion(api.getId().getVersion().equals(apiMgtDAO.getPublishedDefaultVersion(api.getId())));
                if (APIConstants.RETIRED.equals(newStatus)) {
                    cleanUpPendingSubscriptionCreationProcessesByAPI(api.getUuid());
                    apiMgtDAO.removeAllSubscriptions(api.getUuid());
                    deleteAPIRevisions(api.getUuid(), tenantDomain);
                }
                // updateApiArtifactNew(api, false, false);
                PublisherAPI publisherAPI = APIMapper.INSTANCE.toPublisherApi(api);
                try {
                    apiPersistenceInstance.updateAPI(new Organization(api.getOrganization()), publisherAPI);
                } catch (APIPersistenceException e) {
                    handleException("Error while persisting the updated API ", e);
                }
            }
            isSuccess = true;
        } else {
            handleException("Couldn't find an API with the name-" + name + "version-" + version);
        }
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return isSuccess;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)

Aggregations

PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)29 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)24 API (org.wso2.carbon.apimgt.api.model.API)23 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)22 Test (org.junit.Test)21 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)21 Resource (org.wso2.carbon.registry.core.Resource)20 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)17 QName (javax.xml.namespace.QName)16 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)15 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)15 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)14 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)14 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)13 RealmService (org.wso2.carbon.user.core.service.RealmService)13 TenantManager (org.wso2.carbon.user.core.tenant.TenantManager)13 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)11 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)10 Registry (org.wso2.carbon.registry.core.Registry)9 HashSet (java.util.HashSet)8