use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.
the class ApiDAOImpl method getAPIsByStatus.
/**
* @see ApiDAO#getAPIsByStatus(Set, List, List)
*/
@Override
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
public List<API> getAPIsByStatus(Set<String> roles, List<String> statuses, List<String> labels) throws APIMgtDAOException {
// check for null at the beginning before constructing the query to retrieve APIs from database
if (roles == null || statuses == null) {
String errorMessage = "Role list or API status list should not be null to retrieve APIs.";
log.error(errorMessage);
throw new APIMgtDAOException(errorMessage);
}
// the below query will be used to retrieve the union of,
// published/prototyped APIs (statuses) with public visibility and
// published/prototyped APIs with restricted visibility where APIs are restricted based on roles of the user
String labelQuery = null;
if (labels.isEmpty()) {
labelQuery = "SELECT LABEL_ID FROM AM_LABELS WHERE TYPE_NAME='STORE'";
} else {
labelQuery = "SELECT LABEL_ID FROM AM_LABELS WHERE NAME IN ( " + DAOUtil.getParameterString(labels.size()) + ") AND TYPE_NAME='STORE'";
}
final String query = "Select UUID, PROVIDER, NAME, CONTEXT, VERSION, DESCRIPTION, CURRENT_LC_STATUS, " + "LIFECYCLE_INSTANCE_ID, LC_WORKFLOW_STATUS, SECURITY_SCHEME FROM (" + API_SUMMARY_SELECT + " WHERE " + "VISIBILITY = '" + API.Visibility.PUBLIC + "' " + "AND " + "CURRENT_LC_STATUS IN (" + DAOUtil.getParameterString(statuses.size()) + ") AND " + "API_TYPE_ID = (SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = ?)" + "UNION " + API_SUMMARY_SELECT + " WHERE " + "VISIBILITY = '" + API.Visibility.RESTRICTED + "' " + "AND " + "UUID IN (SELECT API_ID FROM AM_API_VISIBLE_ROLES WHERE ROLE IN " + "(" + DAOUtil.getParameterString(roles.size()) + ")) " + " AND CURRENT_LC_STATUS IN (" + DAOUtil.getParameterString(statuses.size()) + ") AND " + " API_TYPE_ID = (SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = ?)) A" + " JOIN AM_API_LABEL_MAPPING LM ON A.UUID=LM.API_ID WHERE LM.LABEL_ID IN (" + labelQuery + ")";
try (Connection connection = DAOUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
int i = 0;
// put desired API status into the query (to get APIs with public visibility)
for (String status : statuses) {
statement.setString(++i, status);
}
statement.setString(++i, ApiType.STANDARD.toString());
// put desired roles into the query
for (String role : roles) {
statement.setString(++i, role);
}
// put desired API status into the query (to get APIs with restricted visibility)
for (String status : statuses) {
statement.setString(++i, status);
}
statement.setString(++i, ApiType.STANDARD.toString());
// Set the label names in the query
for (String label : labels) {
statement.setString(++i, label);
}
return constructAPISummaryList(connection, statement);
} catch (SQLException e) {
String errorMessage = "Error while retrieving API list in store.";
throw new APIMgtDAOException(errorMessage, e);
}
}
use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.
the class APIPublisherImpl method addAPI.
/**
* Adds a new API to the system
*
* @param apiBuilder API model object
* @return UUID of the added API.
* @throws APIManagementException if failed to add API
*/
@Override
public String addAPI(API.APIBuilder apiBuilder) throws APIManagementException {
API createdAPI;
APIGateway gateway = getApiGateway();
apiBuilder.provider(getUsername());
if (StringUtils.isEmpty(apiBuilder.getId())) {
apiBuilder.id(UUID.randomUUID().toString());
}
LocalDateTime localDateTime = LocalDateTime.now();
apiBuilder.createdTime(localDateTime);
apiBuilder.lastUpdatedTime(localDateTime);
apiBuilder.createdBy(getUsername());
apiBuilder.updatedBy(getUsername());
if (apiBuilder.getLabels().isEmpty()) {
List<String> labelSet = new ArrayList<>();
labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_GATEWAY));
labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_STORE));
apiBuilder.labels(labelSet);
}
Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
validateEndpoints(apiEndpointMap, false);
try {
if (!isApiNameExist(apiBuilder.getName()) && !isContextExist(apiBuilder.getContext())) {
LifecycleState lifecycleState = getApiLifecycleManager().addLifecycle(APIMgtConstants.API_LIFECYCLE, getUsername());
apiBuilder.associateLifecycle(lifecycleState);
createUriTemplateList(apiBuilder, false);
List<UriTemplate> list = new ArrayList<>(apiBuilder.getUriTemplates().values());
List<TemplateBuilderDTO> resourceList = new ArrayList<>();
validateApiPolicy(apiBuilder.getApiPolicy());
validateSubscriptionPolicies(apiBuilder);
for (UriTemplate uriTemplate : list) {
TemplateBuilderDTO dto = new TemplateBuilderDTO();
dto.setTemplateId(uriTemplate.getTemplateId());
dto.setUriTemplate(uriTemplate.getUriTemplate());
dto.setHttpVerb(uriTemplate.getHttpVerb());
Map<String, Endpoint> map = uriTemplate.getEndpoint();
if (map.containsKey(APIMgtConstants.PRODUCTION_ENDPOINT)) {
Endpoint endpoint = map.get(APIMgtConstants.PRODUCTION_ENDPOINT);
dto.setProductionEndpoint(endpoint);
}
if (map.containsKey(APIMgtConstants.SANDBOX_ENDPOINT)) {
Endpoint endpoint = map.get(APIMgtConstants.SANDBOX_ENDPOINT);
dto.setSandboxEndpoint(endpoint);
}
resourceList.add(dto);
}
GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
String gatewayConfig = gatewaySourceGenerator.getConfigStringFromTemplate(resourceList);
if (log.isDebugEnabled()) {
log.debug("API " + apiBuilder.getName() + "gateway config: " + gatewayConfig);
}
apiBuilder.gatewayConfig(gatewayConfig);
if (StringUtils.isEmpty(apiBuilder.getApiDefinition())) {
apiBuilder.apiDefinition(apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder));
}
if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
Map<String, Integer> roleNamePermissionList;
roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
apiBuilder.permissionMap(roleNamePermissionList);
}
createdAPI = apiBuilder.build();
APIUtils.validate(createdAPI);
// Add API to gateway
gateway.addAPI(createdAPI);
if (log.isDebugEnabled()) {
log.debug("API : " + apiBuilder.getName() + " has been identifier published to gateway");
}
Set<String> apiRoleList;
// if the API has role based visibility, add the API with role checking
if (API.Visibility.PUBLIC == createdAPI.getVisibility()) {
getApiDAO().addAPI(createdAPI);
} else if (API.Visibility.RESTRICTED == createdAPI.getVisibility()) {
// get all the roles in the system
Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
// get the roles needed to be associated with the API
apiRoleList = createdAPI.getVisibleRoles();
if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
getApiDAO().addAPI(createdAPI);
}
}
APIUtils.logDebug("API " + createdAPI.getName() + "-" + createdAPI.getVersion() + " was created " + "successfully.", log);
// 'API_M Functions' related code
// Create a payload with event specific details
Map<String, String> eventPayload = new HashMap<>();
eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, createdAPI.getId());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, createdAPI.getName());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, createdAPI.getVersion());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, createdAPI.getDescription());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, createdAPI.getContext());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, createdAPI.getLifeCycleStatus());
eventPayload.put(APIMgtConstants.FunctionsConstants.API_PERMISSION, createdAPI.getApiPermission());
// This will notify all the EventObservers(Asynchronous)
ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_CREATION, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
} else {
String message = "Duplicate API already Exist with name/Context " + apiBuilder.getName();
log.error(message);
throw new APIManagementException(message, ExceptionCodes.API_ALREADY_EXISTS);
}
} catch (APIMgtDAOException e) {
String errorMsg = "Error occurred while creating the API - " + apiBuilder.getName();
log.error(errorMsg);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
} catch (LifecycleException | ParseException e) {
String errorMsg = "Error occurred while Associating the API - " + apiBuilder.getName();
log.error(errorMsg);
throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
} catch (APITemplateException e) {
String message = "Error generating API configuration for API " + apiBuilder.getName();
log.error(message, e);
throw new APIManagementException(message, ExceptionCodes.TEMPLATE_EXCEPTION);
} catch (GatewayException e) {
String message = "Error occurred while adding API - " + apiBuilder.getName() + " to gateway";
log.error(message, e);
throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
}
return apiBuilder.getId();
}
use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.
the class ApiDAOImplIT method testGetAPIsWhenUserRolesInAPIPermissionsWithoutREAD.
@Test(description = "Tests getting the APIs when the user roles are contained in the API permission list " + "but without READ permissions")
public void testGetAPIsWhenUserRolesInAPIPermissionsWithoutREAD() throws Exception {
ApiDAO apiDAO = DAOFactory.getApiDAO();
Set<String> rolesOfUser = new HashSet<>();
rolesOfUser.add(SampleTestObjectCreator.DEVELOPER_ROLE_ID);
// This user is not the provider of the API
List<API> apiList = apiDAO.getAPIs(rolesOfUser, ALTERNATIVE_USER);
Assert.assertTrue(apiList.isEmpty());
Map map = new HashMap();
map.put(SampleTestObjectCreator.DEVELOPER_ROLE_ID, 0);
API.APIBuilder builder = SampleTestObjectCreator.createDefaultAPI().permissionMap(map);
API api1 = builder.build();
testAddGetEndpoint();
apiDAO.addAPI(api1);
apiList = apiDAO.getAPIs(rolesOfUser, ALTERNATIVE_USER);
// Since the API has the role ID of the user but without READ permissions, it is not visible to this user
Assert.assertTrue(apiList.size() == 0);
}
use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.
the class ApiDAOImplIT method testAttributeSearchAPIsStore.
@Test
public void testAttributeSearchAPIsStore() throws Exception {
// Add few APIs with different attributes.
List<String> apiIDList = createAPIsAndGetIDsOfAddedAPIs();
List<String> userRoles = new ArrayList<>();
Map<String, String> attributeMap = new HashMap<>();
String[] expectedAPINames;
// Asserting results for different search queries
// Attribute search for "provider", for "admin" role
userRoles.add(ADMIN);
attributeMap.put("provider", "a");
expectedAPINames = new String[] { "PublicAPI", "AdminManagerAPI" };
Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
userRoles.clear();
attributeMap.clear();
// Attribute search for "version", for "manager" role
userRoles.add(MANAGER_ROLE);
attributeMap.put("version", "2.3");
expectedAPINames = new String[] { "PublicAPI", "ManagerOnlyAPI" };
Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
userRoles.clear();
attributeMap.clear();
// Attribute search for "context", for "manager", "employee" and "customer" roles
userRoles.add(MANAGER_ROLE);
userRoles.add(EMPLOYEE_ROLE);
userRoles.add(CUSTOMER_ROLE);
attributeMap.put("context", "Man");
expectedAPINames = new String[] { "ManagerOnlyAPI", "AdminManagerAPI" };
Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
userRoles.clear();
attributeMap.clear();
// Attribute search for "description", for "admin" role
userRoles.add(ADMIN);
attributeMap.put("description", "Admin and manager");
expectedAPINames = new String[] { "AdminManagerAPI" };
Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
userRoles.clear();
attributeMap.clear();
// Attribute search for "tags", for "manager", "employee" and "customer" roles
userRoles.add(MANAGER_ROLE);
userRoles.add(EMPLOYEE_ROLE);
userRoles.add(CUSTOMER_ROLE);
attributeMap.put("tags", "E");
expectedAPINames = new String[] { "ManagerOnlyAPI", "NonAdminAPI" };
Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
userRoles.clear();
attributeMap.clear();
// Attribute search for "subcontext", for "manager", "employee" and "customer" roles
userRoles.add(MANAGER_ROLE);
userRoles.add(EMPLOYEE_ROLE);
userRoles.add(CUSTOMER_ROLE);
attributeMap.put("subcontext", "C");
expectedAPINames = new String[] { "AdminManagerAPI", "EmployeeAPI", "NonAdminAPI" };
Assert.assertTrue(compareResults(userRoles, new ArrayList<>(), attributeMap, expectedAPINames));
userRoles.clear();
attributeMap.clear();
// cleanup added APIs
ApiDAO apiDAO = DAOFactory.getApiDAO();
for (String apiID : apiIDList) {
apiDAO.deleteAPI(apiID);
}
}
use of org.wso2.charon3.core.objects.Role in project carbon-apimgt by wso2.
the class ApiDAOImplIT method testGetAPIsByStatusStore.
@Test
public void testGetAPIsByStatusStore() throws Exception {
// Add few APIs with different attributes.
List<String> apiIDList = createAPIsAndGetIDsOfAddedAPIs();
Set<String> userRoles = new HashSet<>();
List<String> statuses = new ArrayList<>();
statuses.add(APIStatus.PUBLISHED.getStatus());
statuses.add(APIStatus.PROTOTYPED.getStatus());
ApiDAO apiDAO = DAOFactory.getApiDAO();
String[] expectedAPINames;
List<API> apiResults;
// Asserting results for different search queries
// Role based API retrieval for a user with "admin" role
userRoles.add(ADMIN);
apiResults = apiDAO.getAPIsByStatus(userRoles, statuses, new ArrayList<>());
List<String> resultAPINameList = new ArrayList<>();
for (API api : apiResults) {
resultAPINameList.add(api.getName());
}
expectedAPINames = new String[] { "PublicAPI", "AdminManagerAPI" };
Assert.assertTrue(resultAPINameList.containsAll(Arrays.asList(expectedAPINames)) && Arrays.asList(expectedAPINames).containsAll(resultAPINameList));
userRoles.clear();
apiResults.clear();
resultAPINameList.clear();
// Role based API retrieval for a user with "manager" role
userRoles.add(MANAGER_ROLE);
apiResults = apiDAO.getAPIsByStatus(userRoles, statuses, new ArrayList<>());
for (API api : apiResults) {
resultAPINameList.add(api.getName());
}
expectedAPINames = new String[] { "PublicAPI", "ManagerOnlyAPI", "AdminManagerAPI", "NonAdminAPI" };
Assert.assertTrue(resultAPINameList.containsAll(Arrays.asList(expectedAPINames)) && Arrays.asList(expectedAPINames).containsAll(resultAPINameList));
userRoles.clear();
apiResults.clear();
resultAPINameList.clear();
// Role based API retrieval for a user with "manager", "employee" and "customer" roles
userRoles.add(MANAGER_ROLE);
userRoles.add(EMPLOYEE_ROLE);
userRoles.add(CUSTOMER_ROLE);
apiResults = apiDAO.getAPIsByStatus(userRoles, statuses, new ArrayList<>());
for (API api : apiResults) {
resultAPINameList.add(api.getName());
}
expectedAPINames = new String[] { "PublicAPI", "ManagerOnlyAPI", "AdminManagerAPI", "EmployeeAPI", "NonAdminAPI" };
Assert.assertTrue(resultAPINameList.containsAll(Arrays.asList(expectedAPINames)) && Arrays.asList(expectedAPINames).containsAll(resultAPINameList));
userRoles.clear();
apiResults.clear();
resultAPINameList.clear();
}
Aggregations