use of org.wso2.balana.xacml3.Attributes in project carbon-apimgt by wso2.
the class AbstractAPIManager method populateDevPortalAPIInformation.
protected void populateDevPortalAPIInformation(String uuid, String organization, API api) throws APIManagementException, OASPersistenceException, ParseException {
Organization org = new Organization(organization);
// UUID
if (api.getUuid() == null) {
api.setUuid(uuid);
}
api.setOrganization(organization);
// environment
String environmentString = null;
if (api.getEnvironments() != null) {
environmentString = String.join(",", api.getEnvironments());
}
api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
// workflow status
APIIdentifier apiId = api.getId();
String currentApiUuid = uuid;
if (api.isRevision() && api.getRevisionedApiId() != null) {
currentApiUuid = api.getRevisionedApiId();
}
// TODO try to use a single query to get info from db
// Ratings
int internalId = apiMgtDAO.getAPIID(currentApiUuid);
api.setRating(APIUtil.getAverageRating(internalId));
apiId.setId(internalId);
// api level tier
String apiLevelTier = apiMgtDAO.getAPILevelTier(internalId);
api.setApiLevelPolicy(apiLevelTier);
// available tier
String tiers = null;
Set<Tier> tiersSet = api.getAvailableTiers();
Set<String> tierNameSet = new HashSet<String>();
for (Tier t : tiersSet) {
tierNameSet.add(t.getName());
}
if (api.getAvailableTiers() != null) {
tiers = String.join("||", tierNameSet);
}
Map<String, Tier> definedTiers = APIUtil.getTiers(APIUtil.getInternalOrganizationId(organization));
Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, api.getId().getApiName());
api.setAvailableTiers(availableTier);
// Scopes
Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(currentApiUuid, organization);
api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
// templates
String resourceConfigsString = null;
if (api.getSwaggerDefinition() != null) {
resourceConfigsString = api.getSwaggerDefinition();
} else {
resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
}
api.setSwaggerDefinition(resourceConfigsString);
if (api.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
api.setGraphQLSchema(getGraphqlSchemaDefinition(uuid, organization));
}
JSONParser jsonParser = new JSONParser();
JSONObject paths = null;
if (resourceConfigsString != null) {
JSONObject resourceConfigsJSON = (JSONObject) jsonParser.parse(resourceConfigsString);
paths = (JSONObject) resourceConfigsJSON.get(APIConstants.SWAGGER_PATHS);
}
Set<URITemplate> uriTemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
for (URITemplate uriTemplate : uriTemplates) {
String uTemplate = uriTemplate.getUriTemplate();
String method = uriTemplate.getHTTPVerb();
List<Scope> oldTemplateScopes = uriTemplate.retrieveAllScopes();
List<Scope> newTemplateScopes = new ArrayList<>();
if (!oldTemplateScopes.isEmpty()) {
for (Scope templateScope : oldTemplateScopes) {
Scope scope = scopeToKeyMapping.get(templateScope.getKey());
newTemplateScopes.add(scope);
}
}
uriTemplate.addAllScopes(newTemplateScopes);
uriTemplate.setResourceURI(api.getUrl());
uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
// AWS Lambda: set arn & timeout to URI template
if (paths != null) {
JSONObject path = (JSONObject) paths.get(uTemplate);
if (path != null) {
JSONObject operation = (JSONObject) path.get(method.toLowerCase());
if (operation != null) {
if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
uriTemplate.setAmznResourceName((String) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
}
if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
uriTemplate.setAmznResourceTimeout(((Long) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
}
}
}
}
}
if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
for (URITemplate template : uriTemplates) {
template.setMediationScript(template.getAggregatedMediationScript());
}
}
api.setUriTemplates(uriTemplates);
// CORS . if null is returned, set default config from the configuration
if (api.getCorsConfiguration() == null) {
api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
}
// set category
List<APICategory> categories = api.getApiCategories();
if (categories != null) {
List<String> categoriesOfAPI = new ArrayList<String>();
for (APICategory apiCategory : categories) {
categoriesOfAPI.add(apiCategory.getName());
}
List<APICategory> categoryList = new ArrayList<>();
if (!categoriesOfAPI.isEmpty()) {
// category array retrieved from artifact has only the category name, therefore we need to fetch
// categories
// and fill out missing attributes before attaching the list to the api
List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
for (String categoryName : categoriesOfAPI) {
for (APICategory category : allCategories) {
if (categoryName.equals(category.getName())) {
categoryList.add(category);
break;
}
}
}
}
api.setApiCategories(categoryList);
}
}
use of org.wso2.balana.xacml3.Attributes in project carbon-apimgt by wso2.
the class AbstractAPIManager method populateAPIProductInformation.
protected void populateAPIProductInformation(String uuid, String organization, APIProduct apiProduct) throws APIManagementException, OASPersistenceException, ParseException {
Organization org = new Organization(organization);
apiProduct.setOrganization(organization);
ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
apiProduct.setRating(Float.toString(APIUtil.getAverageRating(apiProduct.getProductId())));
List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProduct.getId());
Map<String, Scope> uniqueAPIProductScopeKeyMappings = new LinkedHashMap<>();
for (APIProductResource resource : resources) {
List<Scope> resourceScopes = resource.getUriTemplate().retrieveAllScopes();
ListIterator it = resourceScopes.listIterator();
while (it.hasNext()) {
Scope resourceScope = (Scope) it.next();
String scopeKey = resourceScope.getKey();
if (!uniqueAPIProductScopeKeyMappings.containsKey(scopeKey)) {
resourceScope = APIUtil.getScopeByName(scopeKey, organization);
uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
} else {
resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
}
it.set(resourceScope);
}
}
for (APIProductResource resource : resources) {
String resourceAPIUUID = resource.getApiIdentifier().getUUID();
resource.setApiId(resourceAPIUUID);
try {
PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, resourceAPIUUID);
API api = APIMapper.INSTANCE.toApi(publisherAPI);
if (api.isAdvertiseOnly()) {
resource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
} else {
resource.setEndpointConfig(api.getEndpointConfig());
}
resource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
} catch (APIPersistenceException e) {
throw new APIManagementException("Error while retrieving the api for api product " + e);
}
}
apiProduct.setProductResources(resources);
// UUID
if (apiProduct.getUuid() == null) {
apiProduct.setUuid(uuid);
}
// environment
String environmentString = null;
if (apiProduct.getEnvironments() != null) {
environmentString = String.join(",", apiProduct.getEnvironments());
}
apiProduct.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
// workflow status
APIProductIdentifier productIdentifier = apiProduct.getId();
WorkflowDTO workflow;
String currentApiProductUuid = uuid;
if (apiProduct.isRevision() && apiProduct.getRevisionedApiProductId() != null) {
currentApiProductUuid = apiProduct.getRevisionedApiProductId();
}
workflow = APIUtil.getAPIWorkflowStatus(currentApiProductUuid, WF_TYPE_AM_API_PRODUCT_STATE);
if (workflow != null) {
WorkflowStatus status = workflow.getStatus();
apiProduct.setWorkflowStatus(status.toString());
}
// available tier
String tiers = null;
Set<Tier> tiersSet = apiProduct.getAvailableTiers();
Set<String> tierNameSet = new HashSet<String>();
for (Tier t : tiersSet) {
tierNameSet.add(t.getName());
}
if (apiProduct.getAvailableTiers() != null) {
tiers = String.join("||", tierNameSet);
}
Map<String, Tier> definedTiers = APIUtil.getTiers(tenantId);
Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, apiProduct.getId().getName());
apiProduct.setAvailableTiers(availableTier);
// Scopes
/*
Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(api.getId(), requestedTenantDomain);
apiProduct.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
*/
// templates
String resourceConfigsString = null;
if (apiProduct.getDefinition() != null) {
resourceConfigsString = apiProduct.getDefinition();
} else {
resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
apiProduct.setDefinition(resourceConfigsString);
}
// CORS . if null is returned, set default config from the configuration
if (apiProduct.getCorsConfiguration() == null) {
apiProduct.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
}
// set category
List<APICategory> categories = apiProduct.getApiCategories();
if (categories != null) {
List<String> categoriesOfAPI = new ArrayList<String>();
for (APICategory apiCategory : categories) {
categoriesOfAPI.add(apiCategory.getName());
}
List<APICategory> categoryList = new ArrayList<>();
if (!categoriesOfAPI.isEmpty()) {
// category array retrieved from artifact has only the category name, therefore we need to fetch
// categories
// and fill out missing attributes before attaching the list to the api
List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
// todo-category: optimize this loop with breaks
for (String categoryName : categoriesOfAPI) {
for (APICategory category : allCategories) {
if (categoryName.equals(category.getName())) {
categoryList.add(category);
break;
}
}
}
}
apiProduct.setApiCategories(categoryList);
}
}
use of org.wso2.balana.xacml3.Attributes in project carbon-apimgt by wso2.
the class APIUtil method getMediationPolicyAttributes.
/**
* Returns attributes correspond to the given mediation policy name and direction
*
* @param policyName name of the sequence
* @param tenantId logged in user's tenantId
* @param direction in/out/fault
* @param identifier API identifier
* @return attributes(path, uuid) of the given mediation sequence or null
* @throws APIManagementException If failed to get the uuid of the mediation sequence
*/
public static Map<String, String> getMediationPolicyAttributes(String policyName, int tenantId, String direction, APIIdentifier identifier) throws APIManagementException {
org.wso2.carbon.registry.api.Collection seqCollection = null;
String seqCollectionPath = "";
Map<String, String> mediationPolicyAttributes = new HashMap<>(3);
try {
UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN.equals(direction)) {
seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
} else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT.equals(direction)) {
seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT);
} else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT.equals(direction)) {
seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT);
}
if (seqCollection == null) {
seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier, direction));
}
if (seqCollection != null) {
String[] childPaths = seqCollection.getChildren();
for (String childPath : childPaths) {
Resource mediationPolicy = registry.get(childPath);
OMElement seqElment = APIUtil.buildOMElement(mediationPolicy.getContentStream());
String seqElmentName = seqElment.getAttributeValue(new QName("name"));
if (policyName.equals(seqElmentName)) {
mediationPolicyAttributes.put("path", childPath);
mediationPolicyAttributes.put("uuid", mediationPolicy.getUUID());
mediationPolicyAttributes.put("name", policyName);
return mediationPolicyAttributes;
}
}
}
// If the sequence not found the default sequences, check in custom sequences
seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier, direction));
if (seqCollection != null) {
String[] childPaths = seqCollection.getChildren();
for (String childPath : childPaths) {
Resource mediationPolicy = registry.get(childPath);
OMElement seqElment = APIUtil.buildOMElement(mediationPolicy.getContentStream());
if (policyName.equals(seqElment.getAttributeValue(new QName("name")))) {
mediationPolicyAttributes.put("path", childPath);
mediationPolicyAttributes.put("uuid", mediationPolicy.getUUID());
mediationPolicyAttributes.put("name", policyName);
return mediationPolicyAttributes;
}
}
}
} catch (Exception e) {
String msg = "Issue is in accessing the Registry";
log.error(msg);
throw new APIManagementException(msg, e);
}
return mediationPolicyAttributes;
}
use of org.wso2.balana.xacml3.Attributes in project carbon-apimgt by wso2.
the class RegistryPersistenceImpl method searchContentForDevPortal.
@Override
public DevPortalContentSearchResult searchContentForDevPortal(Organization org, String searchQuery, int start, int offset, UserContext ctx) throws APIPersistenceException {
log.debug("Requested query for devportal content search: " + searchQuery);
Map<String, String> attributes = RegistrySearchUtil.getDevPortalSearchAttributes(searchQuery, ctx, isAllowDisplayAPIsWithMultipleStatus());
if (log.isDebugEnabled()) {
log.debug("Search attributes : " + attributes);
}
DevPortalContentSearchResult result = null;
boolean isTenantFlowStarted = false;
try {
RegistryHolder holder = getRegistry(ctx.getUserame(), org.getName());
Registry registry = holder.getRegistry();
isTenantFlowStarted = holder.isTenantFlowStarted();
String tenantAwareUsername = getTenantAwareUsername(ctx.getUserame());
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(tenantAwareUsername);
GenericArtifactManager apiArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifactManager docArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
int maxPaginationLimit = getMaxPaginationLimit();
PaginationContext.init(start, offset, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
int tenantId = holder.getTenantId();
if (tenantId == -1) {
tenantId = MultitenantConstants.SUPER_TENANT_ID;
}
UserRegistry systemUserRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getRegistry(CarbonConstants.REGISTRY_SYSTEM_USERNAME, tenantId);
ContentBasedSearchService contentBasedSearchService = new ContentBasedSearchService();
SearchResultsBean resultsBean = contentBasedSearchService.searchByAttribute(attributes, systemUserRegistry);
String errorMsg = resultsBean.getErrorMessage();
if (errorMsg != null) {
throw new APIPersistenceException("Error while searching " + errorMsg);
}
ResourceData[] resourceData = resultsBean.getResourceDataList();
int totalLength = PaginationContext.getInstance().getLength();
if (resourceData != null) {
result = new DevPortalContentSearchResult();
List<SearchContent> contentData = new ArrayList<SearchContent>();
if (log.isDebugEnabled()) {
log.debug("Number of records Found: " + resourceData.length);
}
for (ResourceData data : resourceData) {
String resourcePath = data.getResourcePath();
if (resourcePath.contains(APIConstants.APIMGT_REGISTRY_LOCATION)) {
int index = resourcePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
resourcePath = resourcePath.substring(index);
Resource resource = registry.get(resourcePath);
if (APIConstants.DOCUMENT_RXT_MEDIA_TYPE.equals(resource.getMediaType()) || APIConstants.DOCUMENTATION_INLINE_CONTENT_TYPE.equals(resource.getMediaType())) {
if (resourcePath.contains(APIConstants.INLINE_DOCUMENT_CONTENT_DIR)) {
int indexOfContents = resourcePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
resourcePath = resourcePath.substring(0, indexOfContents) + data.getName();
}
DocumentSearchContent docSearch = new DocumentSearchContent();
Resource docResource = registry.get(resourcePath);
String docArtifactId = docResource.getUUID();
GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docArtifactId);
Documentation doc = RegistryPersistenceDocUtil.getDocumentation(docArtifact);
int indexOfDocumentation = resourcePath.indexOf(APIConstants.DOCUMENTATION_KEY);
String apiPath = resourcePath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
Resource apiResource = registry.get(apiPath);
String apiArtifactId = apiResource.getUUID();
DevPortalAPI devAPI;
if (apiArtifactId != null) {
GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
devAPI = RegistryPersistenceUtil.getDevPortalAPIForSearch(apiArtifact);
docSearch.setApiName(devAPI.getApiName());
docSearch.setApiProvider(devAPI.getProviderName());
docSearch.setApiVersion(devAPI.getVersion());
docSearch.setApiUUID(devAPI.getId());
docSearch.setDocType(doc.getType());
docSearch.setId(doc.getId());
docSearch.setSourceType(doc.getSourceType());
docSearch.setVisibility(doc.getVisibility());
docSearch.setName(doc.getName());
contentData.add(docSearch);
} else {
throw new GovernanceException("artifact id is null of " + apiPath);
}
} else {
String apiArtifactId = resource.getUUID();
if (apiArtifactId != null) {
GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
DevPortalAPI devAPI = RegistryPersistenceUtil.getDevPortalAPIForSearch(apiArtifact);
DevPortalSearchContent content = new DevPortalSearchContent();
content.setContext(devAPI.getContext());
content.setDescription(devAPI.getDescription());
content.setId(devAPI.getId());
content.setName(devAPI.getApiName());
content.setProvider(RegistryPersistenceUtil.replaceEmailDomainBack(devAPI.getProviderName()));
content.setVersion(devAPI.getVersion());
content.setStatus(devAPI.getStatus());
content.setBusinessOwner(devAPI.getBusinessOwner());
content.setBusinessOwnerEmail(devAPI.getBusinessOwnerEmail());
contentData.add(content);
} else {
throw new GovernanceException("artifact id is null for " + resourcePath);
}
}
}
}
result.setTotalCount(totalLength);
result.setReturnedCount(contentData.size());
result.setResults(contentData);
}
} catch (RegistryException | IndexerException | DocumentationPersistenceException e) {
throw new APIPersistenceException("Error while searching for content ", e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return result;
}
use of org.wso2.balana.xacml3.Attributes in project carbon-apimgt by wso2.
the class RegistryPersistenceUtil method getAPIForSearch.
public static PublisherAPI getAPIForSearch(GenericArtifact apiArtifact) throws APIPersistenceException {
PublisherAPI api = new PublisherAPI();
try {
api.setContext(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
api.setDescription(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
api.setId(apiArtifact.getId());
api.setStatus(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS));
api.setApiName(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
api.setProviderName(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
;
api.setVersion(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
api.setAdvertiseOnly(Boolean.parseBoolean(apiArtifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
} catch (GovernanceException e) {
throw new APIPersistenceException("Error while extracting api attributes ", e);
}
return api;
}
Aggregations