use of org.wso2.carbon.apimgt.api.model.APICategory in project carbon-apimgt by wso2.
the class ApiMgtDAO method getAPICategoryByID.
public APICategory getAPICategoryByID(String apiCategoryID) throws APIManagementException {
APICategory apiCategory = null;
try (Connection connection = APIMgtDBUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(SQLConstants.GET_API_CATEGORY_BY_ID)) {
statement.setString(1, apiCategoryID);
ResultSet rs = statement.executeQuery();
if (rs.next()) {
apiCategory = new APICategory();
apiCategory.setName(rs.getString("NAME"));
apiCategory.setDescription(rs.getString("DESCRIPTION"));
apiCategory.setId(apiCategoryID);
}
} catch (SQLException e) {
handleException("Failed to fetch API category : " + apiCategoryID, e);
}
return apiCategory;
}
use of org.wso2.carbon.apimgt.api.model.APICategory in project carbon-apimgt by wso2.
the class APIProviderImpl method updateApiArtifact.
private String updateApiArtifact(API api, boolean updateMetadata, boolean updatePermissions) throws APIManagementException {
// Validate Transports
validateAndSetTransports(api);
validateAndSetAPISecurity(api);
boolean transactionCommitted = false;
String apiUUID = null;
try {
registry.beginTransaction();
String apiArtifactId = registry.get(APIUtil.getAPIPath(api.getId())).getUUID();
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
if (artifactManager == null) {
String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
String oldStatus = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
Resource apiResource = registry.get(artifact.getPath());
String oldAccessControlRoles = api.getAccessControlRoles();
if (apiResource != null) {
oldAccessControlRoles = registry.get(artifact.getPath()).getProperty(APIConstants.PUBLISHER_ROLES);
}
GenericArtifact updateApiArtifact = APIUtil.createAPIArtifactContent(artifact, api);
String artifactPath = GovernanceUtils.getArtifactPath(registry, updateApiArtifact.getId());
org.wso2.carbon.registry.core.Tag[] oldTags = registry.getTags(artifactPath);
if (oldTags != null) {
for (org.wso2.carbon.registry.core.Tag tag : oldTags) {
registry.removeTag(artifactPath, tag.getTagName());
}
}
Set<String> tagSet = api.getTags();
if (tagSet != null) {
for (String tag : tagSet) {
registry.applyTag(artifactPath, tag);
}
}
if (updateMetadata && api.getEndpointConfig() != null && !api.getEndpointConfig().isEmpty()) {
// If WSDL URL get change only we update registry WSDL resource. If its registry resource patch we
// will skip registry update. Only if this API created with WSDL end point type we need to update
// wsdls for each update.
// check for wsdl endpoint
org.json.JSONObject response1 = new org.json.JSONObject(api.getEndpointConfig());
boolean isWSAPI = APIConstants.APITransportType.WS.toString().equals(api.getType());
String wsdlURL;
if (!APIUtil.isStreamingApi(api) && "wsdl".equalsIgnoreCase(response1.get("endpoint_type").toString()) && response1.has("production_endpoints")) {
wsdlURL = response1.getJSONObject("production_endpoints").get("url").toString();
if (APIUtil.isValidWSDLURL(wsdlURL, true)) {
String path = APIUtil.createWSDL(registry, api);
if (path != null) {
// reset the wsdl path to permlink
updateApiArtifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
}
}
}
}
artifactManager.updateGenericArtifact(updateApiArtifact);
// write API Status to a separate property. This is done to support querying APIs using custom query (SQL)
// to gain performance
String apiStatus = api.getStatus().toUpperCase();
saveAPIStatus(artifactPath, apiStatus);
String[] visibleRoles = new String[0];
String publisherAccessControlRoles = api.getAccessControlRoles();
updateRegistryResources(artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
// propagate api status change and access control roles change to document artifact
String newStatus = updateApiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
if (!StringUtils.equals(oldStatus, newStatus) || !StringUtils.equals(oldAccessControlRoles, publisherAccessControlRoles)) {
APIUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
}
if (updatePermissions) {
APIUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
String visibleRolesList = api.getVisibleRoles();
if (visibleRolesList != null) {
visibleRoles = visibleRolesList.split(",");
}
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
}
// attaching api categories to the API
List<APICategory> attachedApiCategories = api.getApiCategories();
artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
if (attachedApiCategories != null) {
for (APICategory category : attachedApiCategories) {
artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
}
}
registry.commitTransaction();
transactionCommitted = true;
apiUUID = updateApiArtifact.getId();
if (updatePermissions) {
APIManagerConfiguration config = getAPIManagerConfiguration();
boolean isSetDocLevelPermissions = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_API_DOC_VISIBILITY_LEVELS));
String docRootPath = APIUtil.getAPIDocPath(api.getId());
if (isSetDocLevelPermissions) {
// Retain the docs
List<Documentation> docs = getAllDocumentation(api.getId());
for (Documentation doc : docs) {
if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
String contentPath = APIUtil.getAPIDocContentPath(api.getId(), doc.getName());
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
} else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
String filePath = APIUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
}
}
}
} else {
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docRootPath, registry);
}
} else {
// In order to support content search feature - we need to update resource permissions of document resources
// if their visibility is set to API level.
List<Documentation> docs = getAllDocumentation(api.getId());
if (docs != null) {
for (Documentation doc : docs) {
if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
}
}
}
}
} catch (Exception e) {
try {
registry.rollbackTransaction();
} catch (RegistryException re) {
// Throwing an error from this level will mask the original exception
log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
}
handleException("Error while performing registry transaction operation", e);
} finally {
try {
if (!transactionCommitted) {
registry.rollbackTransaction();
}
} catch (RegistryException ex) {
handleException("Error occurred while rolling back the transaction.", ex);
}
}
return apiUUID;
}
use of org.wso2.carbon.apimgt.api.model.APICategory in project carbon-apimgt by wso2.
the class APIUtil method getAPICategoriesFromAPIGovernanceArtifact.
/**
* This method returns the categories attached to the API
*
* @param artifact API artifact
* @param tenantID tenant ID of API Provider
* @return List<APICategory> list of categories
*/
private static List<APICategory> getAPICategoriesFromAPIGovernanceArtifact(GovernanceArtifact artifact, int tenantID) throws GovernanceException, APIManagementException {
String[] categoriesOfAPI = artifact.getAttributes(APIConstants.API_CATEGORIES_CATEGORY_NAME);
List<APICategory> categoryList = new ArrayList<>();
if (ArrayUtils.isNotEmpty(categoriesOfAPI)) {
// 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
String tenantDomain = getTenantDomainFromTenantId(tenantID);
List<APICategory> allCategories = getAllAPICategoriesOfOrganization(tenantDomain);
// todo-category: optimize this loop with breaks
for (String categoryName : categoriesOfAPI) {
for (APICategory category : allCategories) {
if (categoryName.equals(category.getName())) {
categoryList.add(category);
break;
}
}
}
}
return categoryList;
}
use of org.wso2.carbon.apimgt.api.model.APICategory in project carbon-apimgt by wso2.
the class APIUtil method createAPIArtifactContent.
/**
* Create Governance artifact from given attributes
*
* @param artifact initial governance artifact
* @param api API object with the attributes value
* @return GenericArtifact
* @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to create API
*/
public static GenericArtifact createAPIArtifactContent(GenericArtifact artifact, API api) throws APIManagementException {
try {
String apiStatus = api.getStatus();
artifact.setAttribute(APIConstants.API_OVERVIEW_NAME, api.getId().getApiName());
artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION, api.getId().getVersion());
artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP, api.getVersionTimestamp());
artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT, api.getContext());
artifact.setAttribute(APIConstants.API_OVERVIEW_PROVIDER, api.getId().getProviderName());
artifact.setAttribute(APIConstants.API_OVERVIEW_DESCRIPTION, api.getDescription());
artifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
artifact.setAttribute(APIConstants.API_OVERVIEW_WADL, api.getWadlUrl());
artifact.setAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL, api.getThumbnailUrl());
artifact.setAttribute(APIConstants.API_OVERVIEW_STATUS, apiStatus);
artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER, api.getTechnicalOwner());
artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL, api.getTechnicalOwnerEmail());
artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER, api.getBusinessOwner());
artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL, api.getBusinessOwnerEmail());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBILITY, api.getVisibility());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES, api.getVisibleRoles());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS, api.getVisibleTenants());
artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED, Boolean.toString(api.isEndpointSecured()));
artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST, Boolean.toString(api.isEndpointAuthDigest()));
artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME, api.getEndpointUTUsername());
artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD, api.getEndpointUTPassword());
artifact.setAttribute(APIConstants.API_OVERVIEW_TRANSPORTS, api.getTransports());
artifact.setAttribute(APIConstants.API_OVERVIEW_INSEQUENCE, api.getInSequence());
artifact.setAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE, api.getOutSequence());
artifact.setAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE, api.getFaultSequence());
artifact.setAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING, api.getResponseCache());
artifact.setAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT, Integer.toString(api.getCacheTimeout()));
artifact.setAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL, api.getRedirectURL());
artifact.setAttribute(APIConstants.API_OVERVIEW_EXTERNAL_PRODUCTION_ENDPOINT, api.getApiExternalProductionEndpoint());
artifact.setAttribute(APIConstants.API_OVERVIEW_EXTERNAL_SANDBOX_ENDPOINT, api.getApiExternalSandboxEndpoint());
artifact.setAttribute(APIConstants.API_OVERVIEW_OWNER, api.getApiOwner());
artifact.setAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY, Boolean.toString(api.isAdvertiseOnly()));
artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG, api.getEndpointConfig());
artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY, api.getSubscriptionAvailability());
artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS, api.getSubscriptionAvailableTenants());
artifact.setAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION, api.getImplementation());
artifact.setAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS, api.getProductionMaxTps());
artifact.setAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS, api.getSandboxMaxTps());
artifact.setAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER, api.getAuthorizationHeader());
artifact.setAttribute(APIConstants.API_OVERVIEW_API_SECURITY, api.getApiSecurity());
artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA, Boolean.toString(api.isEnabledSchemaValidation()));
artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE, Boolean.toString(api.isEnableStore()));
artifact.setAttribute(APIConstants.API_OVERVIEW_TESTKEY, api.getTestKey());
// Validate if the API has an unsupported context before setting it in the artifact
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) {
String invalidContext = File.separator + APIConstants.VERSION_PLACEHOLDER;
if (invalidContext.equals(api.getContextTemplate())) {
throw new APIManagementException("API : " + api.getId() + " has an unsupported context : " + api.getContextTemplate());
}
} else {
String invalidContext = APIConstants.TENANT_PREFIX + tenantDomain + File.separator + APIConstants.VERSION_PLACEHOLDER;
if (invalidContext.equals(api.getContextTemplate())) {
throw new APIManagementException("API : " + api.getId() + " has an unsupported context : " + api.getContextTemplate());
}
}
// This is to support the pluggable version strategy.
artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE, api.getContextTemplate());
artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TYPE, "context");
artifact.setAttribute(APIConstants.API_OVERVIEW_TYPE, api.getType());
StringBuilder policyBuilder = new StringBuilder();
for (Tier tier : api.getAvailableTiers()) {
policyBuilder.append(tier.getName());
policyBuilder.append("||");
}
String policies = policyBuilder.toString();
if (!"".equals(policies)) {
policies = policies.substring(0, policies.length() - 2);
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, policies);
}
StringBuilder tiersBuilder = new StringBuilder();
for (Tier tier : api.getAvailableTiers()) {
tiersBuilder.append(tier.getName());
tiersBuilder.append("||");
}
String tiers = tiersBuilder.toString();
if (!"".equals(tiers)) {
tiers = tiers.substring(0, tiers.length() - 2);
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, tiers);
} else {
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, tiers);
}
if (APIConstants.PUBLISHED.equals(apiStatus)) {
artifact.setAttribute(APIConstants.API_OVERVIEW_IS_LATEST, "true");
}
String[] keys = artifact.getAttributeKeys();
for (String key : keys) {
if (key.contains("URITemplate")) {
artifact.removeAttribute(key);
}
}
Set<URITemplate> uriTemplateSet = api.getUriTemplates();
int i = 0;
for (URITemplate uriTemplate : uriTemplateSet) {
artifact.addAttribute(APIConstants.API_URI_PATTERN + i, uriTemplate.getUriTemplate());
artifact.addAttribute(APIConstants.API_URI_HTTP_METHOD + i, uriTemplate.getHTTPVerb());
artifact.addAttribute(APIConstants.API_URI_AUTH_TYPE + i, uriTemplate.getAuthType());
i++;
}
artifact.setAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS, writeEnvironmentsToArtifact(api));
artifact.setAttribute(APIConstants.API_OVERVIEW_CORS_CONFIGURATION, APIUtil.getCorsConfigurationJsonFromDto(api.getCorsConfiguration()));
artifact.setAttribute(APIConstants.API_OVERVIEW_WEBSUB_SUBSCRIPTION_CONFIGURATION, APIUtil.getWebsubSubscriptionConfigurationJsonFromDto(api.getWebsubSubscriptionConfiguration()));
artifact.setAttribute(APIConstants.API_OVERVIEW_WS_URI_MAPPING, APIUtil.getWsUriMappingJsonFromDto(api.getWsUriMapping()));
// attaching api categories to the API
List<APICategory> attachedApiCategories = api.getApiCategories();
artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
if (attachedApiCategories != null) {
for (APICategory category : attachedApiCategories) {
artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
}
}
// set monetization status (i.e - enabled or disabled)
artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS, Boolean.toString(api.getMonetizationStatus()));
// set additional monetization data
if (api.getMonetizationProperties() != null) {
artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES, api.getMonetizationProperties().toJSONString());
}
if (api.getKeyManagers() != null) {
artifact.setAttribute(APIConstants.API_OVERVIEW_KEY_MANAGERS, new Gson().toJson(api.getKeyManagers()));
}
// check in github code to see this method was removed
String apiSecurity = artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY);
if (apiSecurity != null && !apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) && !apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, "");
}
} catch (GovernanceException e) {
String msg = "Failed to create API for : " + api.getId().getApiName();
log.error(msg, e);
throw new APIManagementException(msg, e);
}
return artifact;
}
use of org.wso2.carbon.apimgt.api.model.APICategory in project carbon-apimgt by wso2.
the class APIUtilTest method testValidateAPICategoriesWithValidCategories.
@Test
public void testValidateAPICategoriesWithValidCategories() throws Exception {
List<APICategory> inputApiCategories = new ArrayList<>();
List<APICategory> availableApiCategories = new ArrayList<>();
APICategory apiCategory1 = Mockito.mock(APICategory.class);
APICategory apiCategory2 = Mockito.mock(APICategory.class);
;
APICategory apiCategory3 = Mockito.mock(APICategory.class);
inputApiCategories.add(apiCategory1);
inputApiCategories.add(apiCategory2);
availableApiCategories.add(apiCategory1);
availableApiCategories.add(apiCategory2);
availableApiCategories.add(apiCategory3);
PowerMockito.spy(APIUtil.class);
PowerMockito.doReturn(availableApiCategories).when(APIUtil.class, "getAllAPICategoriesOfOrganization", tenantDomain);
Assert.assertTrue("Failed to Validate API categories", APIUtil.validateAPICategories(inputApiCategories, tenantDomain));
}
Aggregations