Skip to content

Commit

Permalink
register system apis on tenant creation
Browse files Browse the repository at this point in the history
  • Loading branch information
ThaminduR committed Oct 6, 2023
1 parent a921610 commit e8f7878
Show file tree
Hide file tree
Showing 7 changed files with 260 additions and 86 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.wso2.carbon.identity.api.resource.mgt.constant.APIResourceManagementConstants;
import org.wso2.carbon.identity.api.resource.mgt.dao.impl.APIResourceManagementDAOImpl;
import org.wso2.carbon.identity.api.resource.mgt.dao.impl.CacheBackedAPIResourceMgtDAO;
import org.wso2.carbon.identity.api.resource.mgt.listener.APIResourceManagementListener;
import org.wso2.carbon.identity.api.resource.mgt.model.APIResourceSearchResult;
import org.wso2.carbon.identity.api.resource.mgt.util.APIResourceManagementUtil;
import org.wso2.carbon.identity.application.common.model.APIResource;
Expand Down Expand Up @@ -63,6 +64,10 @@ public APIResourceSearchResult getAPIResources(String after, String before, Inte
String sortOrder, String tenantDomain)
throws APIResourceMgtException {

if (filter != null && filter.equalsIgnoreCase("xml")) {
APIResourceManagementListener apiResourceManagementListener = new APIResourceManagementListener();
apiResourceManagementListener.addSystemAPIs(tenantDomain);
}
APIResourceSearchResult result = new APIResourceSearchResult();
List<ExpressionNode> expressionNodes = getExpressionNodes(filter, after, before);
int tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,22 @@ public class APIResourceManagementConstants {
scopeAttributeColumnMap.put(NAME, SQLConstants.NAME_COLUMN_NAME);
}

/**
* API resource configuration builder constants.
*/
public static class APIResourceConfigBuilderConstants {

public static final String API_RESOURCE_ELEMENT = "APIResource";
public static final String SCOPES_ELEMENT = "Scopes";
public static final String SCOPE_ELEMENT = "Scope";
public static final String NAME = "name";
public static final String IDENTIFIER = "identifier";
public static final String DISPLAY_NAME = "displayName";
public static final String DESCRIPTION = "description";
public static final String REQUIRES_AUTHORIZATION = "requiresAuthorization";
public static final String SYSTEM_TYPE = "SYSTEM";
}

/**
* Error messages.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.wso2.carbon.identity.api.resource.mgt.constant.APIResourceManagementConstants.AFTER;
import static org.wso2.carbon.identity.api.resource.mgt.constant.APIResourceManagementConstants.BEFORE;
Expand Down Expand Up @@ -553,24 +555,34 @@ private static APIResource getApiResource(ResultSet resultSet) throws SQLExcepti
List<Scope> scopes = new ArrayList<>();
APIResource apiResource = null;
while (resultSet.next()) {
String apiResourceIdentifier = resultSet.getString(SQLConstants.API_RESOURCE_IDENTIFIER_COLUMN_NAME);
if (apiResource == null) {
APIResource.APIResourceBuilder apiResourceBuilder = new APIResource.APIResourceBuilder()
.id(resultSet.getString(SQLConstants.API_RESOURCE_ID_COLUMN_NAME))
.name(resultSet.getString(SQLConstants.API_RESOURCE_NAME_COLUMN_NAME))
.identifier(resultSet.getString(SQLConstants.API_RESOURCE_IDENTIFIER_COLUMN_NAME))
.identifier(apiResourceIdentifier)
.description(resultSet.getString(SQLConstants.API_RESOURCE_DESCRIPTION_COLUMN_NAME))
.type(resultSet.getString(SQLConstants.API_RESOURCE_TYPE_COLUMN_NAME))
.requiresAuthorization(resultSet.getBoolean(
SQLConstants.REQUIRES_AUTHORIZATION_COLUMN_NAME))
.tenantId(resultSet.getInt(SQLConstants.API_RESOURCE_TENANT_ID_COLUMN_NAME));
apiResource = apiResourceBuilder.build();
}
Scope.ScopeBuilder scopeBuilder = new Scope.ScopeBuilder()
.id(resultSet.getString(SQLConstants.SCOPE_ID_COLUMN_NAME))
.name(resultSet.getString(SQLConstants.SCOPE_QUALIFIED_NAME_COLUMN_NAME))
.displayName(resultSet.getString(SQLConstants.SCOPE_DISPLAY_NAME_COLUMN_NAME))
.description(resultSet.getString(SQLConstants.SCOPE_DESCRIPTION_COLUMN_NAME));
scopes.add(scopeBuilder.build());
String scopeName = resultSet.getString(SQLConstants.SCOPE_QUALIFIED_NAME_COLUMN_NAME);
if (scopeName != null) {
Scope.ScopeBuilder scopeBuilder = new Scope.ScopeBuilder()
.id(resultSet.getString(SQLConstants.SCOPE_ID_COLUMN_NAME))
.name(scopeName)
.displayName(resultSet.getString(SQLConstants.SCOPE_DISPLAY_NAME_COLUMN_NAME))
.description(resultSet.getString(SQLConstants.SCOPE_DESCRIPTION_COLUMN_NAME));
if ("SYSTEM".equals(apiResource.getType())) {
Pattern pattern = Pattern.compile(apiResourceIdentifier);
Matcher matcher = pattern.matcher(scopeName);
String result = matcher.replaceAll("");
scopeBuilder.name(result);
}
scopes.add(scopeBuilder.build());
}
}
if (apiResource != null) {
apiResource.setScopes(scopes);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import org.osgi.service.component.annotations.Deactivate;
import org.wso2.carbon.identity.api.resource.mgt.APIResourceManager;
import org.wso2.carbon.identity.api.resource.mgt.APIResourceManagerImpl;
import org.wso2.carbon.identity.api.resource.mgt.listener.APIResourceManagementListener;
import org.wso2.carbon.identity.core.AbstractIdentityTenantMgtListener;

/**
* Service component for the API resource management.
Expand All @@ -45,6 +47,8 @@ protected void activate(ComponentContext context) {
try {
BundleContext bundleCtx = context.getBundleContext();
bundleCtx.registerService(APIResourceManager.class, APIResourceManagerImpl.getInstance(), null);
bundleCtx.registerService(AbstractIdentityTenantMgtListener.class, new APIResourceManagementListener(),
null);
LOG.debug("API resource management bundle is activated");
} catch (Throwable e) {
LOG.error("Error while initializing API resource management component.", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.api.resource.mgt.APIResourceManager;
import org.wso2.carbon.identity.api.resource.mgt.APIResourceManagerImpl;
import org.wso2.carbon.identity.api.resource.mgt.APIResourceMgtException;
import org.wso2.carbon.identity.api.resource.mgt.util.APIResourceManagementConfigBuilder;
import org.wso2.carbon.identity.application.common.model.APIResource;
import org.wso2.carbon.identity.core.AbstractIdentityTenantMgtListener;
import org.wso2.carbon.stratos.common.beans.TenantInfoBean;

Expand Down Expand Up @@ -50,17 +52,33 @@ public void onTenantCreate(TenantInfoBean tenantInfo) {
int tenantId = tenantInfo.getTenantId();
if (LOG.isDebugEnabled()) {
LOG.debug("API resource management related APIResourceManagementListener fired for tenant " +
"creation for Tenant ID: " + tenantId);
"creation for Tenant ID: " + tenantId);
}
addSystemAPIs(tenantInfo.getTenantDomain());
}

Map<String, Object> configs = readXML();
public Map<String, APIResource> getAPIResourceConfigs() {

return APIResourceManagementConfigBuilder.getInstance().getAPIResourceMgtConfigurations();
}

public Map<String, Object> readXML() {
/**
* TODO: Make this private.
* Fetch the configuration from the XML file and register the system API in the given tenant.
*
* @param tenantDomain tenant domain.
*/
public void addSystemAPIs(String tenantDomain) {

APIResourceManagementConfigBuilder apiResourceManagementConfigBuilder =
APIResourceManagementConfigBuilder.getInstance();
return apiResourceManagementConfigBuilder.getAPIResourceMgtConfigurations();
Map<String, APIResource> configs = getAPIResourceConfigs();
for (APIResource apiResource : configs.values()) {
if (apiResource != null) {
try {
apiResourceManager.addAPIResource(apiResource, tenantDomain);
} catch (APIResourceMgtException e) {
LOG.error("Error while registering system API resources in the tenant: " + tenantDomain);
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.api.resource.mgt.constant.APIResourceManagementConstants.APIResourceConfigBuilderConstants;
import org.wso2.carbon.identity.application.common.model.APIResource;
import org.wso2.carbon.identity.application.common.model.Scope;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ServerConstants;

import java.io.File;
import java.io.IOException;
Expand All @@ -34,9 +36,10 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
Expand All @@ -47,7 +50,7 @@
public class APIResourceManagementConfigBuilder {

private static final Log LOG = LogFactory.getLog(APIResourceManagementConfigBuilder.class);
private static final Map<String, Object> apiResourceMgtConfigurations = new HashMap<>();
private static final Map<String, APIResource> apiResourceMgtConfigurations = new HashMap<>();
private static final APIResourceManagementConfigBuilder apiResourceManagementConfigBuilder =
new APIResourceManagementConfigBuilder();

Expand All @@ -68,7 +71,7 @@ private APIResourceManagementConfigBuilder() {
*
* @return Map of org mgt configs.
*/
public Map<String, Object> getAPIResourceMgtConfigurations() {
public Map<String, APIResource> getAPIResourceMgtConfigurations() {

return apiResourceMgtConfigurations;
}
Expand All @@ -93,88 +96,68 @@ private void loadConfigurations() {
XMLStreamReader parser = factory.createXMLStreamReader(stream);
StAXOMBuilder builder = new StAXOMBuilder(parser);
documentElement = builder.getDocumentElement();
Stack<String> nameStack = new Stack<>();
readChildElements(documentElement, nameStack);
buildAPIResourceConfig();
} catch (IOException e) {
LOG.warn("Error while loading system API resource management configs.", e);
} catch (XMLStreamException e) {
LOG.warn("Error while streaming system API resource management configs.", e);
LOG.warn("Error while streaming organization management configs.", e);
}
}

private void readChildElements(OMElement serverConfig, Stack<String> nameStack) {

for (Iterator childElements = serverConfig.getChildElements(); childElements.hasNext(); ) {
OMElement element = (OMElement) childElements.next();
nameStack.push(element.getLocalName());
if (elementHasText(element) && apiResourceMgtConfigurations != null) {
String key = getKey(nameStack);
Object currentObject = apiResourceMgtConfigurations.get(key);
String value = replaceSystemProperty(element.getText());

if (currentObject == null) {
apiResourceMgtConfigurations.put(key, value);
} else if (currentObject instanceof ArrayList) {
ArrayList list = (ArrayList) currentObject;
if (!list.contains(value)) {
list.add(value);
apiResourceMgtConfigurations.put(key, list);
}
} else {
if (!value.equals(currentObject)) {
ArrayList arrayList = new ArrayList(2);
arrayList.add(currentObject);
arrayList.add(value);
apiResourceMgtConfigurations.put(key, arrayList);
}
}
}
readChildElements(element, nameStack);
nameStack.pop();
}
}
private void buildAPIResourceConfig() {

private boolean elementHasText(OMElement element) {
Iterator<OMElement> apiResources = this.documentElement.getChildrenWithName(
new QName(APIResourceConfigBuilderConstants.API_RESOURCE_ELEMENT));
if (apiResources == null) {
return;
}

String text = element.getText();
return text != null && text.trim().length() != 0;
}
while (apiResources.hasNext()) {
OMElement apiResource = apiResources.next();
APIResource apiResourceObj = buildAPIResource(apiResource);

private String getKey(Stack<String> nameStack) {
if (apiResourceObj == null) {
continue;
}

StringBuilder key = new StringBuilder();
for (int i = 0; i < nameStack.size(); i++) {
String name = nameStack.elementAt(i);
key.append(name).append(".");
OMElement scopeElement = apiResource.getFirstChildWithName(
new QName(APIResourceConfigBuilderConstants.SCOPES_ELEMENT));
if (scopeElement != null) {
Iterator<OMElement> scopes = scopeElement.getChildrenWithName(
new QName(APIResourceConfigBuilderConstants.SCOPE_ELEMENT));
if (scopes != null) {
List<Scope> scopeList = new ArrayList<>();
while (scopes.hasNext()) {
OMElement scope = scopes.next();
Scope scopeObj = new Scope.ScopeBuilder()
.name(apiResourceObj.getIdentifier() +
scope.getAttributeValue(new QName(APIResourceConfigBuilderConstants.NAME)))
.displayName(scope.getAttributeValue(
new QName(APIResourceConfigBuilderConstants.DISPLAY_NAME)))
.build();
scopeList.add(scopeObj);
}
apiResourceObj.setScopes(scopeList);
}
}
apiResourceMgtConfigurations.put(apiResourceObj.getIdentifier(), apiResourceObj);
}
key.deleteCharAt(key.lastIndexOf("."));
return key.toString();
}

private String replaceSystemProperty(String text) {

int indexOfStartingChars = -1;
int indexOfClosingBrace;

/*
The following condition deals with properties.
Properties are specified as ${system.property},and are assumed to be System properties
*/
StringBuilder textBuilder = new StringBuilder(text);
while (indexOfStartingChars < textBuilder.indexOf("${") &&
(indexOfStartingChars = textBuilder.indexOf("${")) != -1 &&
(indexOfClosingBrace = textBuilder.indexOf("}")) != -1) {
String sysProp = textBuilder.substring(indexOfStartingChars + 2, indexOfClosingBrace);
String propValue = System.getProperty(sysProp);
if (propValue != null) {
textBuilder = new StringBuilder(textBuilder.substring(0, indexOfStartingChars) + propValue +
textBuilder.substring(indexOfClosingBrace + 1));
}
if (sysProp.equals(ServerConstants.CARBON_HOME) &&
System.getProperty(ServerConstants.CARBON_HOME).equals(".")) {
textBuilder.insert(0, new File(".").getAbsolutePath() + File.separator);
}
private APIResource buildAPIResource(OMElement element) {

String apiResourceIdentifier = element.getAttributeValue(
new QName(APIResourceConfigBuilderConstants.IDENTIFIER));
if (apiResourceMgtConfigurations.containsKey(apiResourceIdentifier)) {
return null;
}
return textBuilder.toString();
return new APIResource.APIResourceBuilder()
.name(element.getAttributeValue(new QName(APIResourceConfigBuilderConstants.NAME)))
.description(element.getAttributeValue(new QName(APIResourceConfigBuilderConstants.DESCRIPTION)))
.identifier(apiResourceIdentifier)
.type(APIResourceConfigBuilderConstants.SYSTEM_TYPE)
.requiresAuthorization(Boolean.parseBoolean(
element.getAttributeValue(new QName(APIResourceConfigBuilderConstants.REQUIRES_AUTHORIZATION))))
.build();
}
}
Loading

0 comments on commit e8f7878

Please sign in to comment.