use of org.wso2.carbon.apimgt.api.model.APICategory in project carbon-apimgt by wso2.
the class APICategoryMappingUtil method fromCategoryListToCategoryListDTO.
/**
* Convert list of API Categories to CategoryListDTO
*
* @param categories List of api categories
* @return CategoryListDTO list containing api category data
*/
public static APICategoryListDTO fromCategoryListToCategoryListDTO(List<APICategory> categories) {
APICategoryListDTO categoryListDTO = new APICategoryListDTO();
categoryListDTO.setCount(categories.size());
categoryListDTO.setList(fromCategoryListToCategoryDTOList(categories));
return categoryListDTO;
}
use of org.wso2.carbon.apimgt.api.model.APICategory in project carbon-apimgt by wso2.
the class ApiCategoriesApiServiceImpl method apiCategoriesGet.
public Response apiCategoriesGet(String xWSO2Tenant, MessageContext messageContext) {
try {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
List<APICategory> categoryList = APIUtil.getAllAPICategoriesOfOrganization(organization);
APICategoryListDTO categoryListDTO = APICategoryMappingUtil.fromCategoryListToCategoryListDTO(categoryList);
return Response.ok().entity(categoryListDTO).build();
} catch (APIManagementException e) {
String errorMessage = "Error while retrieving API categories";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.APICategory in project carbon-apimgt by wso2.
the class AbstractAPIManager method populateAPIInformation.
protected void populateAPIInformation(String uuid, String organization, API api) throws APIManagementException, OASPersistenceException, ParseException, AsyncSpecPersistenceException {
Organization org = new Organization(organization);
// UUID
if (api.getUuid() == null) {
api.setUuid(uuid);
}
api.setOrganization(organization);
// environment
String environmentString = null;
if (api.getEnvironments() != null) {
environmentString = String.join(",", api.getEnvironments());
}
api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
// workflow status
APIIdentifier apiId = api.getId();
WorkflowDTO workflow;
String currentApiUuid = uuid;
if (api.isRevision() && api.getRevisionedApiId() != null) {
currentApiUuid = api.getRevisionedApiId();
}
workflow = APIUtil.getAPIWorkflowStatus(currentApiUuid, WF_TYPE_AM_API_STATE);
if (workflow != null) {
WorkflowStatus status = workflow.getStatus();
api.setWorkflowStatus(status.toString());
}
// TODO try to use a single query to get info from db
int internalId = apiMgtDAO.getAPIID(currentApiUuid);
apiId.setId(internalId);
apiMgtDAO.setServiceStatusInfoToAPI(api, internalId);
// api level tier
String apiLevelTier;
if (api.isRevision()) {
apiLevelTier = apiMgtDAO.getAPILevelTier(api.getRevisionedApiId(), api.getUuid());
} else {
apiLevelTier = apiMgtDAO.getAPILevelTier(internalId);
}
api.setApiLevelPolicy(apiLevelTier);
// available tier
String tiers = null;
Set<Tier> tiersSet = api.getAvailableTiers();
Set<String> tierNameSet = new HashSet<String>();
for (Tier t : tiersSet) {
tierNameSet.add(t.getName());
}
if (api.getAvailableTiers() != null) {
tiers = String.join("||", tierNameSet);
}
Map<String, Tier> definedTiers = APIUtil.getTiers(APIUtil.getInternalOrganizationId(organization));
Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, api.getId().getApiName());
api.setAvailableTiers(availableTier);
// Scopes
Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(currentApiUuid, organization);
api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
// templates
String resourceConfigsString;
if (api.getSwaggerDefinition() != null) {
resourceConfigsString = api.getSwaggerDefinition();
} else {
resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
}
api.setSwaggerDefinition(resourceConfigsString);
if (resourceConfigsString == null) {
if (api.getAsyncApiDefinition() != null) {
resourceConfigsString = api.getAsyncApiDefinition();
} else {
resourceConfigsString = apiPersistenceInstance.getAsyncDefinition(org, uuid);
}
api.setAsyncApiDefinition(resourceConfigsString);
}
if (api.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
api.setGraphQLSchema(getGraphqlSchemaDefinition(uuid, organization));
}
JSONParser jsonParser = new JSONParser();
JSONObject paths = null;
if (resourceConfigsString != null) {
JSONObject resourceConfigsJSON = (JSONObject) jsonParser.parse(resourceConfigsString);
paths = (JSONObject) resourceConfigsJSON.get(APIConstants.SWAGGER_PATHS);
}
Set<URITemplate> uriTemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
for (URITemplate uriTemplate : uriTemplates) {
String uTemplate = uriTemplate.getUriTemplate();
String method = uriTemplate.getHTTPVerb();
List<Scope> oldTemplateScopes = uriTemplate.retrieveAllScopes();
List<Scope> newTemplateScopes = new ArrayList<>();
if (!oldTemplateScopes.isEmpty()) {
for (Scope templateScope : oldTemplateScopes) {
Scope scope = scopeToKeyMapping.get(templateScope.getKey());
newTemplateScopes.add(scope);
}
}
uriTemplate.addAllScopes(newTemplateScopes);
uriTemplate.setResourceURI(api.getUrl());
uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
// AWS Lambda: set arn & timeout to URI template
if (paths != null) {
JSONObject path = (JSONObject) paths.get(uTemplate);
if (path != null) {
JSONObject operation = (JSONObject) path.get(method.toLowerCase());
if (operation != null) {
if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
uriTemplate.setAmznResourceName((String) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
}
if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
uriTemplate.setAmznResourceTimeout(((Long) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
}
}
}
}
}
if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
for (URITemplate template : uriTemplates) {
template.setMediationScript(template.getAggregatedMediationScript());
}
}
api.setUriTemplates(uriTemplates);
// CORS . if null is returned, set default config from the configuration
if (api.getCorsConfiguration() == null) {
api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
}
// set category
List<APICategory> categories = api.getApiCategories();
if (categories != null) {
List<String> categoriesOfAPI = new ArrayList<String>();
for (APICategory apiCategory : categories) {
categoriesOfAPI.add(apiCategory.getName());
}
List<APICategory> categoryList = new ArrayList<>();
if (!categoriesOfAPI.isEmpty()) {
// 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
List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
// todo-category: optimize this loop with breaks
for (String categoryName : categoriesOfAPI) {
for (APICategory category : allCategories) {
if (categoryName.equals(category.getName())) {
categoryList.add(category);
break;
}
}
}
}
api.setApiCategories(categoryList);
}
}
use of org.wso2.carbon.apimgt.api.model.APICategory in project carbon-apimgt by wso2.
the class PublisherCommonUtils method addAPIWithGeneratedSwaggerDefinition.
/**
* Add API with the generated swagger from the DTO.
*
* @param apiDto API DTO of the API
* @param oasVersion Open API Definition version
* @param username Username
* @param organization Organization Identifier
* @return Created API object
* @throws APIManagementException Error while creating the API
* @throws CryptoException Error while encrypting
*/
public static API addAPIWithGeneratedSwaggerDefinition(APIDTO apiDto, String oasVersion, String username, String organization) throws APIManagementException, CryptoException {
if (APIUtil.isOnPremResolver()) {
String name = apiDto.getName();
// replace all white spaces in the API Name
apiDto.setName(name.replaceAll("\\s+", ""));
}
if (APIDTO.TypeEnum.ASYNC.equals(apiDto.getType())) {
throw new APIManagementException("ASYNC API type does not support API creation from scratch", ExceptionCodes.API_CREATION_NOT_SUPPORTED_FOR_ASYNC_TYPE_APIS);
}
boolean isWSAPI = APIDTO.TypeEnum.WS.equals(apiDto.getType());
boolean isAsyncAPI = isWSAPI || APIDTO.TypeEnum.WEBSUB.equals(apiDto.getType()) || APIDTO.TypeEnum.SSE.equals(apiDto.getType()) || APIDTO.TypeEnum.ASYNC.equals(apiDto.getType());
username = StringUtils.isEmpty(username) ? RestApiCommonUtil.getLoggedInUsername() : username;
APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
// validate web socket api endpoint configurations
if (isWSAPI && !PublisherCommonUtils.isValidWSAPI(apiDto)) {
throw new APIManagementException("Endpoint URLs should be valid web socket URLs", ExceptionCodes.INVALID_ENDPOINT_URL);
}
// validate sandbox and production endpoints
if (!PublisherCommonUtils.validateEndpoints(apiDto)) {
throw new APIManagementException("Invalid/Malformed endpoint URL(s) detected", ExceptionCodes.INVALID_ENDPOINT_URL);
}
Map endpointConfig = (Map) apiDto.getEndpointConfig();
CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
// OAuth 2.0 backend protection: API Key and API Secret encryption
encryptEndpointSecurityOAuthCredentials(endpointConfig, cryptoUtil, StringUtils.EMPTY, StringUtils.EMPTY, apiDto);
// AWS Lambda: secret key encryption while creating the API
if (apiDto.getEndpointConfig() != null) {
if (endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY)) {
String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
if (!StringUtils.isEmpty(secretKey)) {
String encryptedSecretKey = cryptoUtil.encryptAndBase64Encode(secretKey.getBytes());
endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
apiDto.setEndpointConfig(endpointConfig);
}
}
}
/* if (isWSAPI) {
ArrayList<String> websocketTransports = new ArrayList<>();
websocketTransports.add(APIConstants.WS_PROTOCOL);
websocketTransports.add(APIConstants.WSS_PROTOCOL);
apiDto.setTransport(websocketTransports);
}*/
API apiToAdd = prepareToCreateAPIByDTO(apiDto, apiProvider, username, organization);
validateScopes(apiToAdd);
// validate API categories
List<APICategory> apiCategories = apiToAdd.getApiCategories();
List<APICategory> apiCategoriesList = new ArrayList<>();
for (APICategory category : apiCategories) {
category.setOrganization(organization);
apiCategoriesList.add(category);
}
apiToAdd.setApiCategories(apiCategoriesList);
if (apiCategoriesList.size() > 0) {
if (!APIUtil.validateAPICategories(apiCategoriesList, organization)) {
throw new APIManagementException("Invalid API Category name(s) defined", ExceptionCodes.from(ExceptionCodes.API_CATEGORY_INVALID));
}
}
if (!isAsyncAPI) {
APIDefinition oasParser;
if (RestApiConstants.OAS_VERSION_2.equalsIgnoreCase(oasVersion)) {
oasParser = new OAS2Parser();
} else {
oasParser = new OAS3Parser();
}
SwaggerData swaggerData = new SwaggerData(apiToAdd);
String apiDefinition = oasParser.generateAPIDefinition(swaggerData);
apiToAdd.setSwaggerDefinition(apiDefinition);
} else {
AsyncApiParser asyncApiParser = new AsyncApiParser();
String asyncApiDefinition = asyncApiParser.generateAsyncAPIDefinition(apiToAdd);
apiToAdd.setAsyncApiDefinition(asyncApiDefinition);
}
apiToAdd.setOrganization(organization);
if (isAsyncAPI) {
AsyncApiParser asyncApiParser = new AsyncApiParser();
String apiDefinition = asyncApiParser.generateAsyncAPIDefinition(apiToAdd);
apiToAdd.setAsyncApiDefinition(apiDefinition);
}
// adding the api
apiProvider.addAPI(apiToAdd);
return apiToAdd;
}
use of org.wso2.carbon.apimgt.api.model.APICategory in project carbon-apimgt by wso2.
the class RegistryPersistenceUtil method createAPIArtifactContent.
/**
* Create Governance artifact from given attributes
*
* @param artifact initial governance artifact
* @param api API object with the attributes value
* @return GenericArtifact
* @throws 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_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_ADVERTISE_ONLY_API_VENDOR, api.getAdvertiseOnlyAPIVendor());
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.isEnableSchemaValidation()));
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.getEnvironments()));
artifact.setAttribute(APIConstants.API_OVERVIEW_CORS_CONFIGURATION, RegistryPersistenceUtil.getCorsConfigurationJsonFromDto(api.getCorsConfiguration()));
artifact.setAttribute(APIConstants.API_OVERVIEW_WEBSUB_SUBSCRIPTION_CONFIGURATION, RegistryPersistenceUtil.getWebsubSubscriptionJsonFromDto(api.getWebsubSubscriptionConfiguration()));
artifact.setAttribute(APIConstants.API_OVERVIEW_WS_URI_MAPPING, RegistryPersistenceUtil.getWsUriMappingJsonFromDto(api.getWsUriMapping()));
// attaching micro-gateway labels to the API
// 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.isMonetizationEnabled()));
// 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, "");
}
// set gateway vendor for the API
artifact.setAttribute(APIConstants.API_GATEWAY_VENDOR, api.getGatewayVendor());
// set async transport protocols for the API
artifact.setAttribute(APIConstants.ASYNC_API_TRANSPORT_PROTOCOLS, api.getAsyncTransportProtocols());
artifact.setAttribute(APIConstants.API_OVERVIEW_AUDIENCE, api.getAudience());
} catch (GovernanceException e) {
String msg = "Failed to create API for : " + api.getId().getApiName();
log.error(msg, e);
throw new APIManagementException(msg, e);
}
return artifact;
}
Aggregations