use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.
the class APIUtil method getAPIProduct.
/**
* Retrieves api product artifact from registry
*
* @param artifact
* @param registry
* @return APIProduct
* @throws org.wso2.carbon.apimgt.api.APIManagementException
*/
public static APIProduct getAPIProduct(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
APIProduct apiProduct;
try {
String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
String productName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
String productVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(providerName, productName, productVersion);
apiProductIdentifier.setUUID(artifact.getId());
apiProduct = new APIProduct(apiProductIdentifier);
apiProduct.setUuid(artifact.getId());
apiProduct.setRating(Float.toString(getAverageRating(artifact.getId())));
ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
setResourceProperties(apiProduct, registry, artifactPath);
// set uuid
apiProduct.setUuid(artifact.getId());
apiProduct.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
apiProduct.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
apiProduct.setState(getLcStateFromArtifact(artifact));
apiProduct.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
apiProduct.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
apiProduct.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
apiProduct.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
apiProduct.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
apiProduct.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
apiProduct.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
apiProduct.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
apiProduct.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
apiProduct.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
apiProduct.setEnvironments(extractEnvironmentsForAPI(environments));
apiProduct.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
apiProduct.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
apiProduct.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
apiProduct.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
apiProduct.setCreatedTime(registry.get(artifactPath).getCreatedTime());
apiProduct.setLastUpdated(registry.get(artifactPath).getLastModified());
apiProduct.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
apiProduct.setGatewayVendor(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR));
String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
apiProduct.setTenantDomain(tenantDomainName);
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
Map<String, Tier> definedTiers = getTiers(tenantId);
Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, productName);
apiProduct.setAvailableTiers(availableTier);
// We set the context template here
apiProduct.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
apiProduct.setEnableSchemaValidation(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA)));
apiProduct.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
apiProduct.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
apiProduct.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
try {
cacheTimeout = Integer.parseInt(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT));
} catch (NumberFormatException e) {
if (log.isDebugEnabled()) {
log.debug("Error in converting cache time out due to " + e.getMessage());
}
}
apiProduct.setCacheTimeout(cacheTimeout);
List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProductIdentifier);
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 = getScopeByName(scopeKey, tenantDomainName);
uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
} else {
resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
}
it.set(resourceScope);
}
}
Set<String> tags = new HashSet<String>();
Tag[] tag = registry.getTags(artifactPath);
for (Tag tag1 : tag) {
tags.add(tag1.getTagName());
}
apiProduct.addTags(tags);
for (APIProductResource resource : resources) {
String apiPath = APIUtil.getAPIPath(resource.getApiIdentifier());
Resource productResource = null;
try {
// Handles store and publisher visibility issue when associated apis have different visibility
// restrictions.
productResource = registry.get(apiPath);
} catch (RegistryException e) {
if (e.getClass().equals(AuthorizationFailedException.class)) {
if (log.isDebugEnabled()) {
log.debug("User is not authorized to access the resource " + apiPath);
}
continue;
} else {
String msg = "Failed to get product resource";
throw new APIManagementException(msg, e);
}
}
String artifactId = productResource.getUUID();
resource.setApiId(artifactId);
GenericArtifactManager artifactManager = getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(resource.getApiId());
API api = getAPI(apiArtifact, registry);
resource.setEndpointConfig(api.getEndpointConfig());
resource.setEndpointSecurityMap(setEndpointSecurityForAPIProduct(api));
}
apiProduct.setProductResources(resources);
// set data and status related to monetization
apiProduct.setMonetizationStatus(Boolean.parseBoolean(artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS)));
String monetizationInfo = artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
if (StringUtils.isNotBlank(monetizationInfo)) {
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(monetizationInfo);
apiProduct.setMonetizationProperties(jsonObj);
}
apiProduct.setApiCategories(getAPICategoriesFromAPIGovernanceArtifact(artifact, tenantId));
} catch (GovernanceException e) {
String msg = "Failed to get API Product for artifact ";
throw new APIManagementException(msg, e);
} catch (RegistryException e) {
String msg = "Failed to get LastAccess time or Rating";
throw new APIManagementException(msg, e);
} catch (UserStoreException e) {
String msg = "Failed to get User Realm of API Product Provider";
throw new APIManagementException(msg, e);
} catch (ParseException e) {
String msg = "Failed to get parse monetization information.";
throw new APIManagementException(msg, e);
}
return apiProduct;
}
use of org.wso2.carbon.registry.core.Tag in project carbon-apimgt by wso2.
the class APIUtil method getAPI.
/**
* This method used to get API from governance artifact specific to copyAPI
*
* @param artifact API artifact
* @param registry Registry
* @return API
* @throws APIManagementException if failed to get API from artifact
*/
public static API getAPI(GovernanceArtifact artifact, Registry registry, APIIdentifier oldId, String oldContext) throws APIManagementException {
API api;
try {
String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
api = new API(new APIIdentifier(providerName, apiName, apiVersion));
int apiId = ApiMgtDAO.getInstance().getAPIID(artifact.getId());
if (apiId == -1) {
return null;
}
// set rating
String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
BigDecimal bigDecimal = BigDecimal.valueOf(registry.getAverageRating(artifactPath));
BigDecimal res = bigDecimal.setScale(1, RoundingMode.HALF_UP);
api.setRating(res.floatValue());
// set description
api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
// set last access time
api.setLastUpdated(registry.get(artifactPath).getLastModified());
// set uuid
api.setUUID(artifact.getId());
// set url
api.setStatus(getLcStateFromArtifact(artifact));
api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
api.setEndpointAuthDigest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
if (!((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD).equals(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)))) {
api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
} else {
// If APIEndpointPasswordRegistryHandler is enabled take password from the registry hidden property
api.setEndpointUTPassword(getActualEpPswdFromHiddenProperty(api, registry));
}
api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
api.setApiLevelPolicy(apiLevelTier);
String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
Map<String, Tier> definedTiers = getTiers(tenantId);
Set<Tier> availableTier = getAvailableTiers(definedTiers, tiers, apiName);
api.addAvailableTiers(availableTier);
api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
ArrayList<URITemplate> urlPatternsList;
Map<String, Scope> scopeToKeyMapping = getAPIScopes(artifact.getId(), tenantDomainName);
api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
HashMap<Integer, Set<String>> resourceScopes;
resourceScopes = ApiMgtDAO.getInstance().getResourceToScopeMapping(artifact.getId());
urlPatternsList = ApiMgtDAO.getInstance().getAllURITemplates(oldContext, oldId.getVersion());
Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList);
for (URITemplate uriTemplate : uriTemplates) {
uriTemplate.setResourceURI(api.getUrl());
uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
List<String> templateScopeKeys = new ArrayList<>(resourceScopes.get(uriTemplate.getId()));
List<Scope> newTemplateScopes = new ArrayList<>();
if (!templateScopeKeys.isEmpty()) {
for (String templateScope : templateScopeKeys) {
Scope scope = scopeToKeyMapping.get(templateScope);
newTemplateScopes.add(scope);
}
}
uriTemplate.addAllScopes(newTemplateScopes);
}
api.setUriTemplates(uriTemplates);
Set<String> tags = new HashSet<String>();
Tag[] tag = registry.getTags(artifactPath);
for (Tag tag1 : tag) {
tags.add(tag1.getTagName());
}
api.addTags(tags);
api.setLastUpdated(registry.get(artifactPath).getLastModified());
api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
api.setEnvironments(extractEnvironmentsForAPI(environments));
api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
} catch (GovernanceException e) {
String msg = "Failed to get API fro artifact ";
throw new APIManagementException(msg, e);
} catch (RegistryException e) {
String msg = "Failed to get LastAccess time or Rating";
throw new APIManagementException(msg, e);
} catch (UserStoreException e) {
String msg = "Failed to get User Realm of API Provider";
throw new APIManagementException(msg, e);
}
return api;
}
use of org.wso2.carbon.registry.core.Tag in project jaggery by wso2.
the class RegistryHostObject method jsFunction_search.
public static Scriptable jsFunction_search(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException {
String functionName = "search";
int argsCount = args.length;
if (argsCount != 1) {
HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
}
if (!(args[0] instanceof NativeObject)) {
HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "json", args[0], false);
}
NativeObject options = (NativeObject) args[0];
CustomSearchParameterBean parameters = new CustomSearchParameterBean();
String path = null;
List<String[]> values = new ArrayList<String[]>();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String val;
for (Object idObj : options.getIds()) {
String id = (String) idObj;
Object value = options.get(id, options);
if (value == null || value instanceof Undefined) {
continue;
}
if ("path".equals(id)) {
path = (String) value;
continue;
}
if ("createdBefore".equals(id) || "createdAfter".equals(id) || "updatedBefore".equals(id) || "updatedAfter".equals(id)) {
long t;
if (value instanceof Number) {
t = ((Number) value).longValue();
} else {
t = Long.parseLong(HostObjectUtil.serializeObject(value));
}
val = new String(dateFormat.format(new Date(t)).getBytes());
} else {
val = HostObjectUtil.serializeObject(value);
}
values.add(new String[] { id, val });
}
parameters.setParameterValues(values.toArray(new String[0][0]));
RegistryHostObject registryHostObject = (RegistryHostObject) thisObj;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
UserRegistry userRegistry = RegistryHostObjectContext.getRegistryService().getRegistry(registryHostObject.registry.getUserName(), tenantId);
Registry configRegistry = RegistryHostObjectContext.getRegistryService().getConfigSystemRegistry(tenantId);
AdvancedSearchResultsBean resultsBean = registryHostObject.search(configRegistry, userRegistry, parameters);
if (resultsBean.getResourceDataList() == null) {
ScriptableObject error = (ScriptableObject) cx.newObject(thisObj);
error.put("error", error, true);
error.put("description", error, resultsBean.getErrorMessage());
return error;
}
List<ScriptableObject> results = new ArrayList<ScriptableObject>();
for (ResourceData resourceData : resultsBean.getResourceDataList()) {
String resourcePath = resourceData.getResourcePath();
if (path != null && !resourcePath.startsWith(path)) {
continue;
}
ScriptableObject result = (ScriptableObject) cx.newObject(thisObj);
result.put("author", result, resourceData.getAuthorUserName());
result.put("rating", result, resourceData.getAverageRating());
result.put("created", result, resourceData.getCreatedOn().getTime().getTime());
result.put("description", result, resourceData.getDescription());
result.put("name", result, resourceData.getName());
result.put("path", result, resourceData.getResourcePath());
List<ScriptableObject> tags = new ArrayList<ScriptableObject>();
if (resourceData.getTagCounts() != null) {
for (TagCount tagCount : resourceData.getTagCounts()) {
ScriptableObject tag = (ScriptableObject) cx.newObject(thisObj);
tag.put("name", tag, tagCount.getKey());
tag.put("count", tag, tagCount.getValue());
tags.add(tag);
}
}
result.put("tags", result, cx.newArray(thisObj, tags.toArray()));
results.add(result);
}
return cx.newArray(thisObj, results.toArray());
} catch (RegistryException e) {
throw new ScriptException(e);
} catch (CarbonException e) {
throw new ScriptException(e);
}
}
use of org.wso2.carbon.registry.core.Tag in project ballerina by ballerina-lang.
the class TypeChecker method visit.
public void visit(BLangRecordLiteral recordLiteral) {
BType actualType = symTable.errType;
int expTypeTag = expTypes.get(0).tag;
if (expTypeTag == TypeTags.NONE || expTypeTag == TypeTags.ANY) {
// var a = {}
// Change the expected type to map
expTypes = Lists.of(symTable.mapType);
}
List<BType> matchedTypeList = getRecordCompatibleType(expTypes.get(0));
if (matchedTypeList.isEmpty()) {
dlog.error(recordLiteral.pos, DiagnosticCode.INVALID_LITERAL_FOR_TYPE, expTypes.get(0));
} else if (matchedTypeList.size() > 1) {
dlog.error(recordLiteral.pos, DiagnosticCode.AMBIGUOUS_TYPES, expTypes.get(0));
} else {
recordLiteral.keyValuePairs.forEach(keyValuePair -> checkRecLiteralKeyValue(keyValuePair, matchedTypeList.get(0)));
actualType = matchedTypeList.get(0);
// TODO Following check can be moved the code analyzer.
if (expTypeTag == TypeTags.STRUCT) {
validateStructInitalizer(recordLiteral.pos);
}
}
resultTypes = types.checkTypes(recordLiteral, Lists.of(actualType), expTypes);
}
use of org.wso2.carbon.registry.core.Tag in project ballerina by ballerina-lang.
the class TypeChecker method visit.
@Override
public void visit(BLangTableQueryExpression tableQueryExpression) {
BType actualType = symTable.errType;
int expTypeTag = expTypes.get(0).tag;
if (expTypeTag == TypeTags.TABLE) {
actualType = expTypes.get(0);
} else if (expTypeTag != TypeTags.ERROR) {
dlog.error(tableQueryExpression.pos, DiagnosticCode.INCOMPATIBLE_TYPES_CONVERSION, expTypes.get(0));
}
BLangTableQuery tableQuery = (BLangTableQuery) tableQueryExpression.getTableQuery();
tableQuery.accept(this);
resultTypes = types.checkTypes(tableQueryExpression, Lists.of(actualType), expTypes);
}
Aggregations