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;
}
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);
}
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;
}
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;
}
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);
}
}
Aggregations