use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.
the class APIMappingUtil method fromAPItoDTO.
public static APIDTO fromAPItoDTO(APIProduct model, String organization) throws APIManagementException {
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
APIDTO dto = new APIDTO();
dto.setName(model.getId().getName());
dto.setVersion(model.getId().getVersion());
String providerName = model.getId().getProviderName();
dto.setProvider(APIUtil.replaceEmailDomainBack(providerName));
dto.setId(model.getUuid());
dto.setContext(model.getContext());
dto.setDescription(model.getDescription());
dto.setLifeCycleStatus(model.getState());
dto.setType(model.getType());
dto.setAvgRating(String.valueOf(model.getRating()));
/* todo: created and last updated times
if (null != model.getLastUpdated()) {
Date lastUpdateDate = model.getLastUpdated();
Timestamp timeStamp = new Timestamp(lastUpdateDate.getTime());
dto.setLastUpdatedTime(String.valueOf(timeStamp));
}
String createdTimeStamp = model.getCreatedTime();
if (null != createdTimeStamp) {
Date date = new Date(Long.valueOf(createdTimeStamp));
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String dateFormatted = formatter.format(date);
dto.setCreatedTime(dateFormatted);
} */
String apiDefinition = null;
if (model.isAsync()) {
// for asyncAPI retrieve asyncapi.yml specification
apiDefinition = apiConsumer.getAsyncAPIDefinition(model.getUuid(), organization);
} else {
// retrieve open API definition
if (model.getDefinition() != null) {
apiDefinition = model.getDefinition();
} else {
apiDefinition = apiConsumer.getOpenAPIDefinition(model.getUuid(), organization);
}
}
dto.setApiDefinition(apiDefinition);
Set<String> apiTags = model.getTags();
List<String> tagsToReturn = new ArrayList<>();
tagsToReturn.addAll(apiTags);
dto.setTags(tagsToReturn);
Set<org.wso2.carbon.apimgt.api.model.Tier> apiTiers = model.getAvailableTiers();
List<APITiersDTO> tiersToReturn = new ArrayList<>();
// set the monetization status of this API (enabled or disabled)
APIMonetizationInfoDTO monetizationInfoDTO = new APIMonetizationInfoDTO();
monetizationInfoDTO.enabled(model.getMonetizationStatus());
dto.setMonetization(monetizationInfoDTO);
for (org.wso2.carbon.apimgt.api.model.Tier currentTier : apiTiers) {
APITiersDTO apiTiersDTO = new APITiersDTO();
apiTiersDTO.setTierName(currentTier.getName());
apiTiersDTO.setTierPlan(currentTier.getTierPlan());
// monetization attributes are applicable only for commercial tiers
if (APIConstants.COMMERCIAL_TIER_PLAN.equalsIgnoreCase(currentTier.getTierPlan())) {
APIMonetizationAttributesDTO monetizationAttributesDTO = new APIMonetizationAttributesDTO();
if (MapUtils.isNotEmpty(currentTier.getMonetizationAttributes())) {
Map<String, String> monetizationAttributes = currentTier.getMonetizationAttributes();
// check the billing plan (fixed or price per request)
if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE))) {
monetizationAttributesDTO.setFixedPrice(monetizationAttributes.get(APIConstants.Monetization.FIXED_PRICE));
} else if (!StringUtils.isBlank(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST))) {
monetizationAttributesDTO.setPricePerRequest(monetizationAttributes.get(APIConstants.Monetization.PRICE_PER_REQUEST));
}
monetizationAttributesDTO.setCurrencyType(monetizationAttributes.get(APIConstants.Monetization.CURRENCY) != null ? monetizationAttributes.get(APIConstants.Monetization.CURRENCY) : StringUtils.EMPTY);
monetizationAttributesDTO.setBillingCycle(monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) != null ? monetizationAttributes.get(APIConstants.Monetization.BILLING_CYCLE) : StringUtils.EMPTY);
}
apiTiersDTO.setMonetizationAttributes(monetizationAttributesDTO);
}
tiersToReturn.add(apiTiersDTO);
}
dto.setTiers(tiersToReturn);
List<APIOperationsDTO> operationList = new ArrayList<>();
Map<String, ScopeInfoDTO> uniqueScopes = new HashMap<>();
for (APIProductResource productResource : model.getProductResources()) {
URITemplate uriTemplate = productResource.getUriTemplate();
APIOperationsDTO operation = new APIOperationsDTO();
operation.setTarget(uriTemplate.getUriTemplate());
operation.setVerb(uriTemplate.getHTTPVerb());
operationList.add(operation);
List<Scope> scopes = uriTemplate.retrieveAllScopes();
for (Scope scope : scopes) {
if (!uniqueScopes.containsKey(scope.getKey())) {
ScopeInfoDTO scopeInfoDTO = new ScopeInfoDTO().key(scope.getKey()).name(scope.getName()).description(scope.getDescription());
if (StringUtils.isNotBlank(scope.getRoles())) {
scopeInfoDTO.roles(Arrays.asList(scope.getRoles().trim().split(",")));
}
uniqueScopes.put(scope.getKey(), scopeInfoDTO);
}
}
}
dto.setOperations(operationList);
dto.setScopes(new ArrayList<>(uniqueScopes.values()));
dto.setTransport(Arrays.asList(model.getTransports().split(",")));
APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
apiBusinessInformationDTO.setBusinessOwner(model.getBusinessOwner());
apiBusinessInformationDTO.setBusinessOwnerEmail(model.getBusinessOwnerEmail());
apiBusinessInformationDTO.setTechnicalOwner(model.getTechnicalOwner());
apiBusinessInformationDTO.setTechnicalOwnerEmail(model.getTechnicalOwnerEmail());
dto.setBusinessInformation(apiBusinessInformationDTO);
if (!StringUtils.isBlank(model.getThumbnailUrl())) {
dto.setHasThumbnail(true);
}
if (model.getAdditionalProperties() != null) {
JSONObject additionalProperties = model.getAdditionalProperties();
List<APIAdditionalPropertiesDTO> additionalPropertiesList = new ArrayList<>();
for (Object propertyKey : additionalProperties.keySet()) {
APIAdditionalPropertiesDTO additionalPropertiesDTO = new APIAdditionalPropertiesDTO();
String key = (String) propertyKey;
int index = key.lastIndexOf(APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX);
additionalPropertiesDTO.setValue((String) additionalProperties.get(key));
if (index > 0) {
additionalPropertiesDTO.setName(key.substring(0, index));
additionalPropertiesDTO.setDisplay(true);
additionalPropertiesList.add(additionalPropertiesDTO);
}
}
dto.setAdditionalProperties(additionalPropertiesList);
}
if (model.getEnvironments() != null) {
List<String> environmentListToReturn = new ArrayList<>(model.getEnvironments());
dto.setEnvironmentList(environmentListToReturn);
}
dto.setAuthorizationHeader(model.getAuthorizationHeader());
if (model.getApiSecurity() != null) {
dto.setSecurityScheme(Arrays.asList(model.getApiSecurity().split(",")));
}
// Since same APIInfoDTO is used for APIProduct in StoreUI set default AdvertisedInfo to the DTO
AdvertiseInfoDTO advertiseInfoDTO = new AdvertiseInfoDTO();
advertiseInfoDTO.setAdvertised(false);
dto.setAdvertiseInfo(advertiseInfoDTO);
String apiTenant = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(model.getId().getProviderName()));
String subscriptionAvailability = model.getSubscriptionAvailability();
String subscriptionAllowedTenants = model.getSubscriptionAvailableTenants();
dto.setIsSubscriptionAvailable(isSubscriptionAvailable(apiTenant, subscriptionAvailability, subscriptionAllowedTenants));
return dto;
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getAPIByAPIId.
private APIDTO getAPIByAPIId(String apiId, String organization) {
try {
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
ApiTypeWrapper api = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
String status = api.getStatus();
// Extracting clicked API name by the user, for the recommendation system
String userName = RestApiCommonUtil.getLoggedInUsername();
apiConsumer.publishClickedAPI(api, userName);
if (APIConstants.PUBLISHED.equals(status) || APIConstants.PROTOTYPED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
return APIMappingUtil.fromAPItoDTO(api, organization);
} else {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, log);
}
} catch (APIManagementException e) {
if (RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, e, log);
} else if (RestApiUtil.isDueToResourceNotFound(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else {
String errorMessage = "Error while retrieving API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO 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.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.
the class SecurityConfigContext method getContext.
public VelocityContext getContext() {
VelocityContext context = super.getContext();
boolean isSecureVaultEnabled = Boolean.parseBoolean(getApiManagerConfiguration().getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE));
if (api != null) {
Map<String, EndpointSecurityModel> endpointSecurityModelMap = new HashMap<>();
endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_PRODUCTION, new EndpointSecurityModel());
endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_SANDBOX, new EndpointSecurityModel());
if (StringUtils.isNotEmpty(api.getEndpointConfig())) {
if (productionEndpointSecurity != null) {
EndpointSecurityModel endpointSecurityModel = new ObjectMapper().convertValue(productionEndpointSecurity, EndpointSecurityModel.class);
endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, api.getId().getApiName(), api.getId().getVersion(), api.getUuid(), APIConstants.ENDPOINT_SECURITY_PRODUCTION, null);
if (endpointSecurityModel != null) {
endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_PRODUCTION, endpointSecurityModel);
}
}
if (sandboxEndpointSecurity != null) {
EndpointSecurityModel endpointSecurityModel = new ObjectMapper().convertValue(sandboxEndpointSecurity, EndpointSecurityModel.class);
endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, api.getId().getApiName(), api.getId().getVersion(), api.getUuid(), APIConstants.ENDPOINT_SECURITY_SANDBOX, null);
if (endpointSecurityModel != null) {
endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_SANDBOX, endpointSecurityModel);
}
}
}
context.put("endpoint_security", endpointSecurityModelMap);
} else if (apiProduct != null) {
Map<String, Map<String, EndpointSecurityModel>> endpointSecurityModelMap = new HashMap<>();
for (APIProductResource apiProductResource : apiProduct.getProductResources()) {
APIDTO apidto = associatedAPIMap.get(apiProductResource.getApiId());
String alias = apiProduct.getId().getName() + "--v" + apiProduct.getId().getVersion();
Map<String, EndpointSecurityModel> stringEndpointSecurityModelMap = new HashMap<>();
Map<String, EndpointSecurity> endpointSecurityMap = apiProductResource.getEndpointSecurityMap();
for (Map.Entry<String, EndpointSecurity> endpointSecurityEntry : endpointSecurityMap.entrySet()) {
EndpointSecurityModel endpointSecurityModel = new EndpointSecurityModel(endpointSecurityEntry.getValue());
endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, apidto.getName(), apidto.getVersion(), apidto.getId(), endpointSecurityEntry.getKey(), alias);
stringEndpointSecurityModelMap.put(endpointSecurityEntry.getKey(), endpointSecurityModel);
}
endpointSecurityModelMap.put(apiProductResource.getApiId(), stringEndpointSecurityModelMap);
}
context.put("endpoint_security", endpointSecurityModelMap);
}
context.put("isSecureVaultEnabled", isSecureVaultEnabled);
return context;
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.
the class AdditionalSubscriptionInfoMappingUtil method setEndpointURLsForApiDto.
/**
* Sets the Endpoint URLs for the APIDTO object using solace protocols
*
* @param api API object
* @param tenantDomain Tenant Domain
* @return List containing AdditionalSubscriptionInfoSolaceEndpointURLsDTOs
* @throws APIManagementException if error occurred when retrieving protocols URLs
*/
public static List<String> setEndpointURLsForApiDto(API api, String tenantDomain) throws APIManagementException {
List<AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO> urlsList = setSolaceEnvironmentDetailsForSubscription(api, tenantDomain);
List<String> urlsStringList = new ArrayList<>();
if (!urlsList.isEmpty()) {
for (AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO item : urlsList) {
List<AdditionalSubscriptionInfoSolaceURLsDTO> protocols = item.getSolaceURLs();
for (AdditionalSubscriptionInfoSolaceURLsDTO protocol : protocols) {
// Create Json string to return
JSONObject asyncProtocolsObj = new JSONObject();
asyncProtocolsObj.put("protocol", protocol.getProtocol());
asyncProtocolsObj.put("endPointUrl", protocol.getEndpointURL());
urlsStringList.add(asyncProtocolsObj.toString());
}
}
}
return urlsStringList;
}
Aggregations