use of org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method getThumbnail.
@Override
public ResourceFile getThumbnail(Organization org, String apiId) throws ThumbnailPersistenceException {
Registry registry;
boolean isTenantFlowStarted = false;
try {
String tenantDomain = org.getName();
RegistryHolder holder = getRegistry(tenantDomain);
registry = holder.getRegistry();
isTenantFlowStarted = holder.isTenantFlowStarted();
GenericArtifact apiArtifact = getAPIArtifact(apiId, registry);
if (apiArtifact == null) {
return null;
}
String apiProviderName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
apiProviderName = RegistryPersistenceUtil.replaceEmailDomain(apiProviderName);
String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
String artifactOldPath = APIConstants.API_IMAGE_LOCATION + RegistryConstants.PATH_SEPARATOR + apiProviderName + RegistryConstants.PATH_SEPARATOR + apiName + RegistryConstants.PATH_SEPARATOR + apiVersion;
String apiPath = GovernanceUtils.getArtifactPath(registry, apiId);
int prependIndex = apiPath.lastIndexOf("/api");
String artifactPath = apiPath.substring(0, prependIndex);
String oldThumbPath = artifactOldPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
String thumbPath = artifactPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ICON_IMAGE;
if (registry.resourceExists(thumbPath)) {
Resource res = registry.get(thumbPath);
return new ResourceFile(res.getContentStream(), res.getMediaType());
} else if (registry.resourceExists(oldThumbPath)) {
Resource res = registry.get(oldThumbPath);
return new ResourceFile(res.getContentStream(), res.getMediaType());
}
} catch (RegistryException | APIPersistenceException e) {
String msg = "Error while loading API icon of API " + apiId + " from the registry";
throw new ThumbnailPersistenceException(msg, e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return null;
}
use of org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method getPublisherAPI.
@Override
public PublisherAPI getPublisherAPI(Organization org, String apiId) throws APIPersistenceException {
boolean tenantFlowStarted = false;
try {
RegistryHolder holder = getRegistry(org.getName());
tenantFlowStarted = holder.isTenantFlowStarted();
Registry registry = holder.getRegistry();
GenericArtifact apiArtifact = getAPIArtifact(apiId, registry);
if (apiArtifact != null) {
API api = RegistryPersistenceUtil.getApiForPublishing(registry, apiArtifact);
String apiPath = GovernanceUtils.getArtifactPath(registry, apiId);
int prependIndex = apiPath.lastIndexOf("/api");
String apiSourcePath = apiPath.substring(0, prependIndex);
String definitionPath = apiSourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
String asyncApiDefinitionPath = apiSourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ASYNC_API_DEFINITION_RESOURCE_NAME;
if (registry.resourceExists(definitionPath)) {
Resource apiDocResource = registry.get(definitionPath);
String apiDocContent = new String((byte[]) apiDocResource.getContent(), Charset.defaultCharset());
api.setSwaggerDefinition(apiDocContent);
}
if (APIConstants.API_TYPE_SOAPTOREST.equals(api.getType())) {
List<SOAPToRestSequence> list = getSoapToRestSequences(registry, api, Direction.IN);
list.addAll(getSoapToRestSequences(registry, api, Direction.OUT));
api.setSoapToRestSequences(list);
} else if (APIConstants.API_TYPE_WEBSUB.equals(api.getType()) || APIConstants.API_TYPE_WS.equals(api.getType()) || APIConstants.API_TYPE_SSE.equals(api.getType()) || APIConstants.API_TYPE_WEBHOOK.equals(api.getType())) {
if (asyncApiDefinitionPath != null) {
if (registry.resourceExists(asyncApiDefinitionPath)) {
Resource apiDocResource = registry.get(asyncApiDefinitionPath);
String apiDocContent = new String((byte[]) apiDocResource.getContent(), Charset.defaultCharset());
api.setAsyncApiDefinition(apiDocContent);
}
}
}
PublisherAPI pubApi = APIMapper.INSTANCE.toPublisherApi(api);
if (log.isDebugEnabled()) {
log.debug("API for id " + apiId + " : " + pubApi.toString());
}
return pubApi;
} else {
String msg = "Failed to get API. API artifact corresponding to artifactId " + apiId + " does not exist";
throw new APIMgtResourceNotFoundException(msg);
}
} catch (RegistryException e) {
String msg = "Failed to get API";
throw new APIPersistenceException(msg, e);
} catch (APIManagementException e) {
String msg = "Failed to get API";
throw new APIPersistenceException(msg, e);
} finally {
if (tenantFlowStarted) {
RegistryPersistenceUtil.endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method saveOASDefinition.
@Override
public void saveOASDefinition(Organization org, String apiId, String apiDefinition) throws OASPersistenceException {
boolean isTenantFlowStarted = false;
try {
RegistryHolder holder = getRegistry(org.getName());
Registry registry = holder.getRegistry();
isTenantFlowStarted = holder.isTenantFlowStarted();
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Failed to retrieve artifact manager when deleting API " + apiId;
log.error(errorMessage);
throw new OASPersistenceException(errorMessage);
}
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
String apiProviderName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
String visibleRoles = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES);
String visibility = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY);
String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(apiName, apiVersion, apiProviderName);
resourcePath = resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
Resource resource;
if (!registry.resourceExists(resourcePath)) {
resource = registry.newResource();
} else {
resource = registry.get(resourcePath);
}
resource.setContent(apiDefinition);
resource.setMediaType("application/json");
registry.put(resourcePath, resource);
String[] visibleRolesArr = null;
if (visibleRoles != null) {
visibleRolesArr = visibleRoles.split(",");
}
// Need to set anonymous if the visibility is public
RegistryPersistenceUtil.clearResourcePermissions(resourcePath, new APIIdentifier(apiProviderName, apiName, apiVersion), ((UserRegistry) registry).getTenantId());
RegistryPersistenceUtil.setResourcePermissions(apiProviderName, visibility, visibleRolesArr, resourcePath);
} catch (RegistryException | APIPersistenceException | APIManagementException e) {
throw new OASPersistenceException("Error while adding OSA Definition for " + apiId, e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method getAllTags.
@Override
public Set<Tag> getAllTags(Organization org, UserContext ctx) throws APIPersistenceException {
TreeSet<Tag> tempTagSet = new TreeSet<Tag>(new Comparator<Tag>() {
@Override
public int compare(Tag o1, Tag o2) {
return o1.getName().compareTo(o2.getName());
}
});
Registry userRegistry = null;
boolean tenantFlowStarted = false;
String tagsQueryPath = null;
try {
RegistryHolder holder = getRegistry(org.getName());
tenantFlowStarted = holder.isTenantFlowStarted();
userRegistry = holder.getRegistry();
tagsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/tag-summary";
Map<String, String> params = new HashMap<String, String>();
params.put(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.TAG_SUMMARY_RESULT_TYPE);
String userNameLocal;
if (holder.isAnonymousMode()) {
userNameLocal = APIConstants.WSO2_ANONYMOUS_USER;
} else {
userNameLocal = getTenantAwareUsername(ctx.getUserame());
}
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userNameLocal);
Map<String, Tag> tagsData = new HashMap<String, Tag>();
Map<String, List<String>> criteriaPublished = new HashMap<String, List<String>>();
criteriaPublished.put(APIConstants.LCSTATE_SEARCH_KEY, new ArrayList<String>() {
{
add(APIConstants.PUBLISHED);
}
});
// rxt api media type
List<TermData> termsPublished = GovernanceUtils.getTermDataList(criteriaPublished, APIConstants.API_OVERVIEW_TAG, APIConstants.API_RXT_MEDIA_TYPE, true);
if (termsPublished != null) {
for (TermData data : termsPublished) {
tempTagSet.add(new Tag(data.getTerm(), (int) data.getFrequency()));
}
}
Map<String, List<String>> criteriaPrototyped = new HashMap<String, List<String>>();
criteriaPrototyped.put(APIConstants.LCSTATE_SEARCH_KEY, new ArrayList<String>() {
{
add(APIConstants.PROTOTYPED);
}
});
// rxt api media type
List<TermData> termsPrototyped = GovernanceUtils.getTermDataList(criteriaPrototyped, APIConstants.API_OVERVIEW_TAG, APIConstants.API_RXT_MEDIA_TYPE, true);
if (termsPrototyped != null) {
for (TermData data : termsPrototyped) {
tempTagSet.add(new Tag(data.getTerm(), (int) data.getFrequency()));
}
}
return tempTagSet;
} catch (RegistryException e) {
try {
// give a warn.
if (userRegistry != null && !userRegistry.resourceExists(tagsQueryPath)) {
log.warn("Failed to retrieve tags query resource at " + tagsQueryPath);
return Collections.EMPTY_SET;
}
} catch (RegistryException e1) {
// Even if we should ignore this exception, we are logging this as a warn log.
// The reason is that, this error happens when we try to add some additional logs in an error
// scenario and it does not affect the execution path.
log.warn("Unable to execute the resource exist method for tags query resource path : " + tagsQueryPath, e1);
}
throw new APIPersistenceException("Failed to get all the tags", e);
} finally {
if (tenantFlowStarted) {
RegistryPersistenceUtil.endTenantFlow();
}
}
}
use of org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method searchPaginatedPublisherAPIsByDoc.
private PublisherAPISearchResult searchPaginatedPublisherAPIsByDoc(Registry registry, int tenantID, String searchQuery, String username, int start, int offset) throws APIPersistenceException {
PublisherAPISearchResult searchResults = new PublisherAPISearchResult();
try {
GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Artifact manager is null when searching APIs by docs in tenant ID " + tenantID;
log.error(errorMessage);
throw new APIPersistenceException(errorMessage);
}
GenericArtifactManager docArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
if (docArtifactManager == null) {
String errorMessage = "Doc artifact manager is null when searching APIs by docs in tenant ID " + tenantID;
log.error(errorMessage);
throw new APIPersistenceException(errorMessage);
}
SolrClient client = SolrClient.getInstance();
Map<String, String> fields = new HashMap<String, String>();
fields.put(APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, "*" + APIConstants.API_ROOT_LOCATION + "*");
fields.put(APIConstants.DOCUMENTATION_SEARCH_MEDIA_TYPE_FIELD, "*");
if (tenantID == -1) {
tenantID = MultitenantConstants.SUPER_TENANT_ID;
}
// PaginationContext.init(0, 10000, "ASC", APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, Integer.MAX_VALUE);
SolrDocumentList documentList = client.query(searchQuery, tenantID, fields);
org.wso2.carbon.user.api.AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantID).getAuthorizationManager();
username = MultitenantUtils.getTenantAwareUsername(username);
List<PublisherAPIInfo> publisherAPIInfoList = new ArrayList<PublisherAPIInfo>();
for (SolrDocument document : documentList) {
PublisherAPIInfo apiInfo = new PublisherAPIInfo();
String filePath = (String) document.getFieldValue("path_s");
String fileName = (String) document.getFieldValue("resourceName_s");
int index = filePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
filePath = filePath.substring(index);
boolean isAuthorized;
int indexOfContents = filePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
String documentationPath = filePath.substring(0, indexOfContents) + fileName;
String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + documentationPath);
if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} else {
isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
}
if (isAuthorized) {
int indexOfDocumentation = filePath.indexOf(APIConstants.DOCUMENTATION_KEY);
String apiPath = documentationPath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + apiPath);
if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} else {
isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
}
if (isAuthorized) {
Resource resource = registry.get(apiPath);
String apiArtifactId = resource.getUUID();
if (apiArtifactId != null) {
GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
if (APIConstants.PUBLISHED.equals(status) || APIConstants.PROTOTYPED.equals(status)) {
apiInfo.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
apiInfo.setId(artifact.getId());
apiInfo.setApiName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
apiInfo.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
apiInfo.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
apiInfo.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
apiInfo.setStatus(status);
apiInfo.setThumbnail(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
apiInfo.setCreatedTime(String.valueOf(resource.getCreatedTime().getTime()));
apiInfo.setUpdatedTime(resource.getLastModified());
apiInfo.setGatewayVendor(String.valueOf(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR)));
// apiInfo.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
apiInfo.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
apiInfo.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
publisherAPIInfoList.add(apiInfo);
}
} else {
throw new GovernanceException("artifact id is null of " + apiPath);
}
}
}
}
// Sort the publisherAPIInfoList according to the API name.
Collections.sort(publisherAPIInfoList, new PublisherAPISearchResultComparator());
searchResults.setPublisherAPIInfoList(publisherAPIInfoList);
searchResults.setTotalAPIsCount(publisherAPIInfoList.size());
searchResults.setReturnedAPIsCount(publisherAPIInfoList.size());
} catch (RegistryException | UserStoreException | APIPersistenceException | IndexerException e) {
String msg = "Failed to search APIs with type";
throw new APIPersistenceException(msg, e);
} finally {
PaginationContext.destroy();
}
return searchResults;
}
Aggregations