Search in sources :

Example 81 with APIPersistenceException

use of org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException 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 82 with APIPersistenceException

use of org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException in project carbon-apimgt by wso2.

the class APIProviderImpl method restoreAPIProductRevision.

@Override
public void restoreAPIProductRevision(String apiProductId, String apiRevisionId, String organization) throws APIManagementException {
    APIProductIdentifier apiProductIdentifier = APIUtil.getAPIProductIdentifierFromUUID(apiProductId);
    if (apiProductIdentifier == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API Product with ID: " + apiProductId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiProductId));
    }
    APIRevision apiRevision = apiMgtDAO.getRevisionByRevisionUUID(apiRevisionId);
    if (apiRevision == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API Revision with Revision UUID: " + apiRevisionId, ExceptionCodes.from(ExceptionCodes.API_REVISION_NOT_FOUND, apiRevisionId));
    }
    apiProductIdentifier.setUUID(apiProductId);
    try {
        apiPersistenceInstance.restoreAPIRevision(new Organization(organization), apiProductIdentifier.getUUID(), apiRevision.getRevisionUUID(), apiRevision.getId());
    } catch (APIPersistenceException e) {
        String errorMessage = "Failed to restore registry artifacts";
        throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.ERROR_RESTORING_API_REVISION, apiRevision.getApiUUID()));
    }
    apiMgtDAO.restoreAPIProductRevision(apiRevision);
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) DeployedAPIRevision(org.wso2.carbon.apimgt.api.model.DeployedAPIRevision) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Example 83 with APIPersistenceException

use of org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException in project carbon-apimgt by wso2.

the class APIProviderImpl method searchPaginatedAPIProducts.

/**
 * Returns APIProduct Search result based on the provided query.
 *
 * @param registry
 * @param searchQuery Ex: provider=*admin*
 * @return APIProduct result
 * @throws APIManagementException
 */
public Map<String, Object> searchPaginatedAPIProducts(Registry registry, String searchQuery, int start, int end) throws APIManagementException {
    SortedSet<APIProduct> productSet = new TreeSet<APIProduct>(new APIProductNameComparator());
    List<APIProduct> productList = new ArrayList<APIProduct>();
    Map<String, Object> result = new HashMap<String, Object>();
    if (log.isDebugEnabled()) {
        log.debug("Original search query received : " + searchQuery);
    }
    Organization org = new Organization(tenantDomain);
    String[] roles = APIUtil.getFilteredUserRoles(userNameWithoutChange);
    Map<String, Object> properties = APIUtil.getUserProperties(userNameWithoutChange);
    UserContext userCtx = new UserContext(userNameWithoutChange, org, properties, roles);
    try {
        PublisherAPIProductSearchResult searchAPIs = apiPersistenceInstance.searchAPIProductsForPublisher(org, searchQuery, start, end, userCtx);
        if (log.isDebugEnabled()) {
            log.debug("searched API products for query : " + searchQuery + " :-->: " + searchAPIs.toString());
        }
        if (searchAPIs != null) {
            List<PublisherAPIProductInfo> list = searchAPIs.getPublisherAPIProductInfoList();
            List<Object> apiList = new ArrayList<>();
            for (PublisherAPIProductInfo publisherAPIInfo : list) {
                APIProduct mappedAPI = new APIProduct(new APIProductIdentifier(publisherAPIInfo.getProviderName(), publisherAPIInfo.getApiProductName(), publisherAPIInfo.getVersion()));
                mappedAPI.setUuid(publisherAPIInfo.getId());
                mappedAPI.setState(publisherAPIInfo.getState());
                mappedAPI.setContext(publisherAPIInfo.getContext());
                mappedAPI.setApiSecurity(publisherAPIInfo.getApiSecurity());
                populateAPIStatus(mappedAPI);
                productList.add(mappedAPI);
            }
            productSet.addAll(productList);
            result.put("products", productSet);
            result.put("length", searchAPIs.getTotalAPIsCount());
            result.put("isMore", true);
        } else {
            result.put("products", productSet);
            result.put("length", 0);
            result.put("isMore", false);
        }
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Error while searching the api ", e);
    }
    return result;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) ArrayList(java.util.ArrayList) PublisherAPIProductSearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProductSearchResult) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) PublisherAPIProductInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProductInfo) JSONObject(org.json.simple.JSONObject) APIProductNameComparator(org.wso2.carbon.apimgt.impl.utils.APIProductNameComparator)

Example 84 with APIPersistenceException

use of org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAllTags.

@Override
public Set<Tag> getAllTags(String organization) throws APIManagementException {
    /* We keep track of the lastUpdatedTime of the TagCache to determine its freshness.
         */
    long lastUpdatedTimeAtStart = lastUpdatedTime;
    long currentTimeAtStart = System.currentTimeMillis();
    if (isTagCacheEnabled && ((currentTimeAtStart - lastUpdatedTimeAtStart) < tagCacheValidityTime)) {
        if (tagSet != null) {
            return tagSet;
        }
    }
    Organization org = new Organization(organization);
    String userName = (userNameWithoutChange != null) ? userNameWithoutChange : username;
    String[] roles = APIUtil.getListOfRoles(userName);
    Map<String, Object> properties = APIUtil.getUserProperties(userName);
    UserContext userCtx = new UserContext(userNameWithoutChange, org, properties, roles);
    try {
        Set<Tag> tempTagSet = apiPersistenceInstance.getAllTags(org, userCtx);
        synchronized (tagCacheMutex) {
            lastUpdatedTime = System.currentTimeMillis();
            this.tagSet = tempTagSet;
        }
    } catch (APIPersistenceException e) {
        String msg = "Failed to get API tags";
        throw new APIManagementException(msg, e);
    }
    return tagSet;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) JSONObject(org.json.simple.JSONObject) Tag(org.wso2.carbon.apimgt.api.model.Tag)

Example 85 with APIPersistenceException

use of org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException in project carbon-apimgt by wso2.

the class APIConsumerImpl method getAPIorAPIProductByUUIDWithoutPermissionCheck.

/**
 * Used to retrieve API/API Products without performing the visibility permission checks
 * @param uuid
 * @param organization
 * @return
 * @throws APIManagementException
 */
private ApiTypeWrapper getAPIorAPIProductByUUIDWithoutPermissionCheck(String uuid, String organization) throws APIManagementException {
    try {
        Organization org = new Organization(organization);
        DevPortalAPI devPortalApi = apiPersistenceInstance.getDevPortalAPI(org, uuid);
        if (devPortalApi != null) {
            if (APIConstants.API_PRODUCT.equalsIgnoreCase(devPortalApi.getType())) {
                APIProduct apiProduct = APIMapper.INSTANCE.toApiProduct(devPortalApi);
                apiProduct.setID(new APIProductIdentifier(devPortalApi.getProviderName(), devPortalApi.getApiName(), devPortalApi.getVersion()));
                populateAPIProductInformation(uuid, organization, apiProduct);
                return new ApiTypeWrapper(apiProduct);
            } else {
                API api = APIMapper.INSTANCE.toApi(devPortalApi);
                populateDevPortalAPIInformation(uuid, organization, api);
                populateDefaultVersion(api);
                api = addTiersToAPI(api, organization);
                return new ApiTypeWrapper(api);
            }
        } else {
            String msg = "Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist";
            throw new APIMgtResourceNotFoundException(msg);
        }
    } catch (APIPersistenceException | OASPersistenceException | ParseException e) {
        String msg = "Failed to get API";
        throw new APIManagementException(msg, e);
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) ParseException(org.json.simple.parser.ParseException)

Aggregations

APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)83 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)55 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)53 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)49 Registry (org.wso2.carbon.registry.core.Registry)49 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)47 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)44 Resource (org.wso2.carbon.registry.core.Resource)40 API (org.wso2.carbon.apimgt.api.model.API)35 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)34 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)32 Test (org.junit.Test)29 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)27 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)24 ArrayList (java.util.ArrayList)21 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)19 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)18 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)18 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)16