use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.
the class AbstractAPIManager method registerCustomQueries.
/**
* method to register custom registry queries
*
* @param registry Registry instance to use
* @throws RegistryException n error
*/
protected void registerCustomQueries(UserRegistry registry, String username) throws RegistryException, APIManagementException {
String tagsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/tag-summary";
String latestAPIsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/latest-apis";
String resourcesByTag = RegistryConstants.QUERIES_COLLECTION_PATH + "/resource-by-tag";
String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION);
if (username == null) {
try {
UserRealm realm = ServiceReferenceHolder.getUserRealm();
RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(realm);
authorizationManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} catch (UserStoreException e) {
String msg = "Error while setting the permissions";
throw new APIManagementException(msg, e);
}
} else if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
int tenantId;
try {
tenantId = getTenantManager().getTenantId(tenantDomain);
AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
} catch (org.wso2.carbon.user.api.UserStoreException e) {
String msg = "Error while setting the permissions";
throw new APIManagementException(msg, e);
}
}
if (!registry.resourceExists(tagsQueryPath)) {
Resource resource = registry.newResource();
// Tag Search Query
// 'MOCK_PATH' used to bypass ChrootWrapper -> filterSearchResult. A valid registry path is
// a must for executeQuery results to be passed to client side
String sql1 = "SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " + " RT.REG_TAG_NAME AS TAG_NAME, " + " COUNT(RT.REG_TAG_NAME) AS USED_COUNT " + "FROM " + " REG_RESOURCE_TAG RRT, " + " REG_TAG RT, " + " REG_RESOURCE R, " + " REG_RESOURCE_PROPERTY RRP, " + " REG_PROPERTY RP " + "WHERE " + " RT.REG_ID = RRT.REG_TAG_ID " + " AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + " AND RRT.REG_VERSION = R.REG_VERSION " + " AND RRP.REG_VERSION = R.REG_VERSION " + " AND RP.REG_NAME = 'STATUS' " + " AND RRP.REG_PROPERTY_ID = RP.REG_ID " + " AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED' AND RP.REG_VALUE !='BLOCKED' AND RP.REG_VALUE !='RETIRED') " + "GROUP BY " + " RT.REG_TAG_NAME";
resource.setContent(sql1);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.TAG_SUMMARY_RESULT_TYPE);
registry.put(tagsQueryPath, resource);
}
if (!registry.resourceExists(latestAPIsQueryPath)) {
// Recently added APIs
Resource resource = registry.newResource();
String sql = "SELECT " + " RR.REG_PATH_ID AS REG_PATH_ID, " + " RR.REG_NAME AS REG_NAME " + "FROM " + " REG_RESOURCE RR, " + " REG_RESOURCE_PROPERTY RRP, " + " REG_PROPERTY RP " + "WHERE " + " RR.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + " AND RRP.REG_VERSION = RR.REG_VERSION " + " AND RP.REG_NAME = 'STATUS' " + " AND RRP.REG_PROPERTY_ID = RP.REG_ID " + " AND (RP.REG_VALUE !='DEPRECATED' AND RP.REG_VALUE !='CREATED') " + "ORDER BY " + " RR.REG_LAST_UPDATED_TIME " + "DESC ";
resource.setContent(sql);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCES_RESULT_TYPE);
registry.put(latestAPIsQueryPath, resource);
}
if (!registry.resourceExists(resourcesByTag)) {
Resource resource = registry.newResource();
String sql = "SELECT '" + APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + APIConstants.GOVERNANCE_COMPONENT_REGISTRY_LOCATION + "' AS MOCK_PATH, " + " R.REG_UUID AS REG_UUID " + "FROM " + " REG_RESOURCE_TAG RRT, " + " REG_TAG RT, " + " REG_RESOURCE R, " + " REG_PATH RP " + "WHERE " + " RT.REG_TAG_NAME = ? " + " AND R.REG_MEDIA_TYPE = 'application/vnd.wso2-api+xml' " + " AND RP.REG_PATH_ID = R.REG_PATH_ID " + " AND RT.REG_ID = RRT.REG_TAG_ID " + " AND RRT.REG_VERSION = R.REG_VERSION ";
resource.setContent(sql);
resource.setMediaType(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
resource.addProperty(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.RESOURCE_UUID_RESULT_TYPE);
registry.put(resourcesByTag, resource);
}
}
use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.
the class AbstractAPIManager method searchPaginatedAPIs.
@Override
public Map<String, Object> searchPaginatedAPIs(String searchQuery, String requestedTenantDomain, int start, int end, boolean isLazyLoad, boolean isPublisherListing) throws APIManagementException {
Map<String, Object> result = new HashMap<String, Object>();
boolean isTenantFlowStarted = false;
String[] searchQueries = searchQuery.split("&");
StringBuilder filteredQuery = new StringBuilder();
String subQuery = null;
if (log.isDebugEnabled()) {
log.debug("Original search query received : " + searchQuery);
}
// Filtering the queries related with custom properties
for (String query : searchQueries) {
if (searchQuery.startsWith(APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX)) {
subQuery = query;
break;
}
// If the query does not contains "=" then it is an errornous scenario.
if (query.contains("=")) {
String[] searchKeys = query.split("=");
if (searchKeys.length >= 2) {
if (!Arrays.asList(APIConstants.API_SEARCH_PREFIXES).contains(searchKeys[0].toLowerCase())) {
if (log.isDebugEnabled()) {
log.debug(searchKeys[0] + " does not match with any of the reserved key words. Hence" + " appending " + APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX + " as prefix");
}
searchKeys[0] = (APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX + searchKeys[0]);
}
// category search should only return results that exactly match.
if (searchKeys[0].equals(APIConstants.LABEL_SEARCH_TYPE_PREFIX)) {
searchKeys[0] = APIConstants.API_LABELS_GATEWAY_LABELS;
searchKeys[1] = searchKeys[1].replace("*", "");
} else if (searchKeys[0].equals(APIConstants.CATEGORY_SEARCH_TYPE_PREFIX)) {
searchKeys[0] = APIConstants.API_CATEGORIES_CATEGORY_NAME;
searchKeys[1] = searchKeys[1].replace("*", "");
}
if (filteredQuery.length() == 0) {
filteredQuery.append(searchKeys[0]).append("=").append(searchKeys[1]);
} else {
filteredQuery.append("&").append(searchKeys[0]).append("=").append(searchKeys[1]);
}
}
} else {
filteredQuery.append(query);
}
}
searchQuery = filteredQuery.toString();
if (log.isDebugEnabled()) {
log.debug("Final search query after the post processing for the custom properties : " + searchQuery);
}
try {
boolean isTenantMode = (requestedTenantDomain != null);
if (isTenantMode && !org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(requestedTenantDomain)) {
isTenantFlowStarted = true;
startTenantFlow(requestedTenantDomain);
} else {
requestedTenantDomain = org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
isTenantFlowStarted = true;
startTenantFlow(requestedTenantDomain);
}
Registry userRegistry;
int tenantIDLocal = 0;
String userNameLocal = this.username;
if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(requestedTenantDomain))) {
// Tenant store anonymous mode
tenantIDLocal = getTenantManager().getTenantId(requestedTenantDomain);
APIUtil.loadTenantRegistry(tenantIDLocal);
userRegistry = getRegistryService().getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantIDLocal);
userNameLocal = CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME;
if (!requestedTenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
APIUtil.loadTenantConfigBlockingMode(requestedTenantDomain);
}
} else {
userRegistry = this.registry;
tenantIDLocal = tenantId;
}
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userNameLocal);
if (subQuery != null && subQuery.startsWith(APIConstants.DOCUMENTATION_SEARCH_TYPE_PREFIX)) {
Map<Documentation, API> apiDocMap = searchAPIDoc(userRegistry, tenantIDLocal, userNameLocal, subQuery.split("=")[1]);
result.put("apis", apiDocMap);
/*Pagination for Document search results is not supported yet, hence length is sent as end-start*/
if (apiDocMap.isEmpty()) {
result.put("length", 0);
} else {
result.put("length", end - start);
}
} else if (searchQuery != null && searchQuery.startsWith(APIConstants.CONTENT_SEARCH_TYPE_PREFIX)) {
result = searchPaginatedAPIsByContent(userRegistry, tenantIDLocal, searchQuery, start, end, isLazyLoad);
} else {
result = searchPaginatedAPIs(userRegistry, tenantIDLocal, searchQuery, start, end, isLazyLoad, isPublisherListing);
}
} catch (Exception e) {
String msg = "Failed to Search APIs";
throw new APIManagementException(msg, e);
} finally {
if (isTenantFlowStarted) {
endTenantFlow();
}
}
return result;
}
use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.
the class APIProviderImpl method getCustomSequence.
/**
* Get the resource which matches the user selected resource type and the name from the custom uploaded sequences.
*
* @param identifier : The API Identifier.
* @param type : The sequence type.
* @return : Resource object which matches the parameters. If no resource found, return null.
*/
private Resource getCustomSequence(APIIdentifier identifier, String type, String name) throws APIManagementException {
Resource customSequence = null;
boolean isTenantFlowStarted = false;
try {
String tenantDomain = null;
if (identifier.getProviderName().contains("-AT-")) {
String provider = identifier.getProviderName().replace("-AT-", "@");
tenantDomain = MultitenantUtils.getTenantDomain(provider);
}
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
PrivilegedCarbonContext.startTenantFlow();
isTenantFlowStarted = true;
}
if (!StringUtils.isEmpty(tenantDomain)) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
} else {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
}
UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
String customSeqFileLocation = "";
if (APIConstants.FAULT_SEQUENCE.equals(type)) {
customSeqFileLocation = APIUtil.getSequencePath(identifier, APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT);
} else if (APIConstants.OUT_SEQUENCE.equals(type)) {
customSeqFileLocation = APIUtil.getSequencePath(identifier, APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT);
} else {
customSeqFileLocation = APIUtil.getSequencePath(identifier, APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
}
if (registry.resourceExists(customSeqFileLocation)) {
org.wso2.carbon.registry.api.Collection customSeqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(customSeqFileLocation);
if (customSeqCollection != null) {
String[] faultSeqChildPaths = customSeqCollection.getChildren();
for (String customSeqChildPath : faultSeqChildPaths) {
customSequence = registry.get(customSeqChildPath);
OMElement seqElement = APIUtil.buildOMElement(customSequence.getContentStream());
if (name.equals(seqElement.getAttributeValue(new QName("name")))) {
return customSequence;
}
}
}
}
} catch (RegistryException e) {
throw new APIManagementException("Error while retrieving registry for tenant " + tenantId, e);
} catch (org.wso2.carbon.registry.api.RegistryException e) {
throw new APIManagementException("Error while processing the " + type + " sequences of " + identifier + " in the registry", e);
} catch (Exception e) {
throw new APIManagementException("Error while building the OMElement from the sequence " + name, e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return null;
}
use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.
the class APIProviderImpl method getAPILifeCycleData.
@Override
public /*
* This method returns the lifecycle data for an API including current state,next states.
*
* @param apiId APIIdentifier
* @return Map<String,Object> a map with lifecycle data
*/
Map<String, Object> getAPILifeCycleData(APIIdentifier apiId) throws APIManagementException {
String path = APIUtil.getAPIPath(apiId);
Map<String, Object> lcData = new HashMap<String, Object>();
String providerTenantMode = apiId.getProviderName();
boolean isTenantFlowStarted = false;
try {
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerTenantMode));
if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
isTenantFlowStarted = true;
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
}
Resource apiSourceArtifact = registry.get(path);
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Failed to retrieve artifact manager when getting lifecycle data for API " + apiId;
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
GenericArtifact artifact = artifactManager.getGenericArtifact(apiSourceArtifact.getUUID());
// Get all the actions corresponding to current state of the api artifact
String[] actions = artifact.getAllLifecycleActions(APIConstants.API_LIFE_CYCLE);
// Put next states into map
lcData.put(APIConstants.LC_NEXT_STATES, actions);
String lifeCycleState = artifact.getLifecycleState();
lcData.put(APIConstants.LC_STATUS, lifeCycleState);
LifecycleBean bean;
bean = LifecycleBeanPopulator.getLifecycleBean(path, (UserRegistry) registry, configRegistry);
if (bean != null) {
ArrayList<CheckListItem> checkListItems = new ArrayList<CheckListItem>();
ArrayList<String> permissionList = new ArrayList<String>();
// Get lc properties
Property[] lifecycleProps = bean.getLifecycleProperties();
// Get roles of the current session holder
String[] roleNames = bean.getRolesOfUser();
for (Property property : lifecycleProps) {
String propName = property.getKey();
String[] propValues = property.getValues();
// Check for permission properties if any exists
if (propValues != null && propValues.length != 0) {
if (propName.startsWith(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX) && propName.endsWith(APIConstants.LC_PROPERTY_PERMISSION_SUFFIX) && propName.contains(APIConstants.API_LIFE_CYCLE)) {
for (String role : roleNames) {
for (String propValue : propValues) {
String key = propName.replace(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX, "").replace(APIConstants.LC_PROPERTY_PERMISSION_SUFFIX, "");
if (propValue.equals(role)) {
permissionList.add(key);
} else if (propValue.startsWith(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX) && propValue.endsWith(APIConstants.LC_PROPERTY_PERMISSION_SUFFIX)) {
permissionList.add(key);
}
}
}
}
}
}
// Check for lifecycle checklist item properties defined
for (Property property : lifecycleProps) {
String propName = property.getKey();
String[] propValues = property.getValues();
if (propValues != null && propValues.length != 0) {
CheckListItem checkListItem = new CheckListItem();
checkListItem.setVisible("false");
if (propName.startsWith(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX) && propName.endsWith(APIConstants.LC_PROPERTY_ITEM_SUFFIX) && propName.contains(APIConstants.API_LIFE_CYCLE)) {
if (propValues.length > 2) {
for (String param : propValues) {
if (param.startsWith(APIConstants.LC_STATUS)) {
checkListItem.setLifeCycleStatus(param.substring(7));
} else if (param.startsWith(APIConstants.LC_CHECK_ITEM_NAME)) {
checkListItem.setName(param.substring(5));
} else if (param.startsWith(APIConstants.LC_CHECK_ITEM_VALUE)) {
checkListItem.setValue(param.substring(6));
} else if (param.startsWith(APIConstants.LC_CHECK_ITEM_ORDER)) {
checkListItem.setOrder(param.substring(6));
}
}
}
String key = propName.replace(APIConstants.LC_PROPERTY_CHECKLIST_PREFIX, "").replace(APIConstants.LC_PROPERTY_ITEM_SUFFIX, "");
if (permissionList.contains(key)) {
// Set visible to true if the checklist item permits
checkListItem.setVisible("true");
}
}
if (checkListItem.matchLifeCycleStatus(lifeCycleState)) {
checkListItems.add(checkListItem);
}
}
}
lcData.put("items", checkListItems);
}
} catch (Exception e) {
handleException(e.getMessage(), e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return lcData;
}
use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.
the class APIProviderImpl method getCustomApiInSequences.
/**
* Get the list of Custom in sequences of API.
*
* @return List of in sequences
* @throws APIManagementException
*/
public List<String> getCustomApiInSequences(APIIdentifier apiIdentifier) throws APIManagementException {
Set<String> sequenceList = new TreeSet<>();
boolean isTenantFlowStarted = false;
try {
String tenantDomain = null;
if (apiIdentifier.getProviderName().contains("-AT-")) {
String provider = apiIdentifier.getProviderName().replace("-AT-", "@");
tenantDomain = MultitenantUtils.getTenantDomain(provider);
}
PrivilegedCarbonContext.startTenantFlow();
isTenantFlowStarted = true;
if (!StringUtils.isEmpty(tenantDomain)) {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
} else {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
}
UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
String customInSeqFileLocation = APIUtil.getSequencePath(apiIdentifier, APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
if (registry.resourceExists(customInSeqFileLocation)) {
org.wso2.carbon.registry.api.Collection inSeqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(customInSeqFileLocation);
if (inSeqCollection != null) {
String[] inSeqChildPaths = inSeqCollection.getChildren();
Arrays.sort(inSeqChildPaths);
for (String inSeqChildPath : inSeqChildPaths) {
Resource outSequence = registry.get(inSeqChildPath);
try {
OMElement seqElment = APIUtil.buildOMElement(outSequence.getContentStream());
sequenceList.add(seqElment.getAttributeValue(new QName("name")));
} catch (OMException e) {
log.info("Error occurred when reading the sequence '" + inSeqChildPath + "' from the registry.", e);
}
}
}
}
} catch (RegistryException e) {
String msg = "Error while retrieving registry for tenant " + tenantId;
log.error(msg);
throw new APIManagementException(msg, e);
} catch (org.wso2.carbon.registry.api.RegistryException e) {
String msg = "Error while processing the " + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN + " sequences of " + apiIdentifier + " in the registry";
log.error(msg);
throw new APIManagementException(msg, e);
} catch (Exception e) {
log.error(e.getMessage());
throw new APIManagementException(e.getMessage(), e);
} finally {
if (isTenantFlowStarted) {
PrivilegedCarbonContext.endTenantFlow();
}
}
return new ArrayList<>(sequenceList);
}
Aggregations