use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class APIMappingUtil method fromDTOtoAPIProduct.
public static APIProduct fromDTOtoAPIProduct(APIProductDTO dto, String provider) throws APIManagementException {
APIProduct product = new APIProduct();
APIProductIdentifier id = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), dto.getName(), // todo: replace this with dto.getVersion
APIConstants.API_PRODUCT_VERSION);
product.setID(id);
product.setUuid(dto.getId());
product.setDescription(dto.getDescription());
String context = dto.getContext();
if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
}
context = context.startsWith("/") ? context : ("/" + context);
String providerDomain = MultitenantUtils.getTenantDomain(provider);
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain) && dto.getId() == null) {
// Create tenant aware context for API
context = "/t/" + providerDomain + context;
}
product.setType(APIConstants.API_PRODUCT_IDENTIFIER_TYPE.replaceAll("\\s", ""));
product.setContext(context);
context = checkAndSetVersionParam(context);
product.setContextTemplate(context);
List<String> apiProductTags = dto.getTags();
Set<String> tagsToReturn = new HashSet<>(apiProductTags);
product.addTags(tagsToReturn);
if (dto.isEnableSchemaValidation() != null) {
product.setEnableSchemaValidation(dto.isEnableSchemaValidation());
}
product.setEnableStore(true);
if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
product.setResponseCache(APIConstants.ENABLED);
} else {
product.setResponseCache(APIConstants.DISABLED);
}
if (dto.getCacheTimeout() != null) {
product.setCacheTimeout(dto.getCacheTimeout());
} else {
product.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
}
if (dto.getBusinessInformation() != null) {
product.setBusinessOwner(dto.getBusinessInformation().getBusinessOwner());
product.setBusinessOwnerEmail(dto.getBusinessInformation().getBusinessOwnerEmail());
product.setTechnicalOwner(dto.getBusinessInformation().getTechnicalOwner());
product.setTechnicalOwnerEmail(dto.getBusinessInformation().getTechnicalOwnerEmail());
}
Set<Tier> apiTiers = new HashSet<>();
List<String> tiersFromDTO = dto.getPolicies();
if (dto.getVisibility() != null) {
product.setVisibility(mapVisibilityFromDTOtoAPIProduct(dto.getVisibility()));
}
if (dto.getVisibleRoles() != null) {
String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
product.setVisibleRoles(visibleRoles);
}
if (dto.getVisibleTenants() != null) {
String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
product.setVisibleTenants(visibleTenants);
}
List<String> accessControlRoles = dto.getAccessControlRoles();
if (accessControlRoles == null || accessControlRoles.isEmpty()) {
product.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
product.setAccessControlRoles("null");
} else {
product.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
product.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
}
for (String tier : tiersFromDTO) {
apiTiers.add(new Tier(tier));
}
product.setAvailableTiers(apiTiers);
product.setProductLevelPolicy(dto.getApiThrottlingPolicy());
product.setGatewayVendor(dto.getGatewayVendor());
if (dto.getSubscriptionAvailability() != null) {
product.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPIProduct(dto.getSubscriptionAvailability()));
}
List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
if (additionalProperties != null) {
for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
if (property.isDisplay()) {
product.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
} else {
product.addProperty(property.getName(), property.getValue());
}
}
}
if (dto.getSubscriptionAvailableTenants() != null) {
product.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
}
String transports = StringUtils.join(dto.getTransport(), ',');
product.setTransports(transports);
List<APIProductResource> productResources = new ArrayList<APIProductResource>();
Set<String> verbResourceCombo = new HashSet<>();
for (ProductAPIDTO res : dto.getApis()) {
List<APIOperationsDTO> productAPIOperationsDTO = res.getOperations();
for (APIOperationsDTO resourceItem : productAPIOperationsDTO) {
if (!verbResourceCombo.add(resourceItem.getVerb() + resourceItem.getTarget())) {
throw new APIManagementException("API Product resource: " + resourceItem.getTarget() + ", with verb: " + resourceItem.getVerb() + " , is duplicated for id " + id, ExceptionCodes.from(ExceptionCodes.API_PRODUCT_DUPLICATE_RESOURCE, resourceItem.getTarget(), resourceItem.getVerb()));
}
URITemplate template = new URITemplate();
template.setHTTPVerb(resourceItem.getVerb());
template.setHttpVerbs(resourceItem.getVerb());
template.setResourceURI(resourceItem.getTarget());
template.setUriTemplate(resourceItem.getTarget());
template.setOperationPolicies(OperationPolicyMappingUtil.fromDTOToAPIOperationPoliciesList(resourceItem.getOperationPolicies()));
APIProductResource resource = new APIProductResource();
resource.setApiId(res.getApiId());
resource.setUriTemplate(template);
productResources.add(resource);
}
}
Set<Scope> scopes = getScopes(dto);
product.setScopes(scopes);
APICorsConfigurationDTO apiCorsConfigurationDTO = dto.getCorsConfiguration();
CORSConfiguration corsConfiguration;
if (apiCorsConfigurationDTO != null) {
corsConfiguration = new CORSConfiguration(apiCorsConfigurationDTO.isCorsConfigurationEnabled(), apiCorsConfigurationDTO.getAccessControlAllowOrigins(), apiCorsConfigurationDTO.isAccessControlAllowCredentials(), apiCorsConfigurationDTO.getAccessControlAllowHeaders(), apiCorsConfigurationDTO.getAccessControlAllowMethods());
} else {
corsConfiguration = APIUtil.getDefaultCorsConfiguration();
}
product.setCorsConfiguration(corsConfiguration);
product.setProductResources(productResources);
product.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
product.setAuthorizationHeader(dto.getAuthorizationHeader());
// attach api categories to API model
setAPICategoriesToModel(dto, product, provider);
return product;
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class APIMappingUtil method getAPIProductIdentifierFromUUID.
/**
* Returns the APIProductIdentifier given the uuid.
*
* @param productId API Product uuid
* @param requestedTenantDomain tenant domain of the API
* @return APIProductIdentifier which represents the given id
* @throws APIManagementException
*/
public static APIProductIdentifier getAPIProductIdentifierFromUUID(String productId, String requestedTenantDomain) throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
APIProduct product = apiProvider.getAPIProductbyUUID(productId, requestedTenantDomain);
return product.getId();
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method deleteAPIClientCertificateByAlias.
@Override
public Response deleteAPIClientCertificateByAlias(String alias, String apiId, MessageContext messageContext) {
String organization = null;
try {
organization = RestApiUtil.getValidatedOrganization(messageContext);
// validate if api exists
validateAPIExistence(apiId);
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
API api = apiProvider.getAPIbyUUID(apiId, organization);
api.setOrganization(organization);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(api.getStatus());
ClientCertificateDTO clientCertificateDTO = CertificateRestApiUtils.preValidateClientCertificate(alias, api.getId(), organization);
int responseCode = apiProvider.deleteClientCertificate(RestApiCommonUtil.getLoggedInUsername(), clientCertificateDTO.getApiIdentifier(), alias);
if (responseCode == ResponseCode.SUCCESS.getResponseCode()) {
// Handle api product case.
if (API_PRODUCT_TYPE.equals(api.getType())) {
APIIdentifier apiIdentifier = api.getId();
APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
apiProduct.setOrganization(organization);
apiProvider.updateAPIProduct(apiProduct);
} else {
apiProvider.updateAPI(api);
}
if (log.isDebugEnabled()) {
log.debug(String.format("The client certificate which belongs to tenant : %s represented by the " + "alias : %s is deleted successfully", organization, alias));
}
return Response.ok().entity("The certificate for alias '" + alias + "' deleted successfully.").build();
} else {
if (log.isDebugEnabled()) {
log.debug(String.format("Failed to delete the client certificate which belongs to tenant : %s " + "represented by the alias : %s.", organization, alias));
}
RestApiUtil.handleInternalServerError("Error while deleting the client certificate for alias '" + alias + "'.", log);
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error while deleting the client certificate with alias " + alias + " for the tenant " + organization, e, log);
} catch (FaultGatewaysException e) {
RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method addAPIClientCertificate.
@Override
public Response addAPIClientCertificate(String apiId, InputStream certificateInputStream, Attachment certificateDetail, String alias, String tier, MessageContext messageContext) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
ContentDisposition contentDisposition = certificateDetail.getContentDisposition();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
String fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
if (StringUtils.isEmpty(alias) || StringUtils.isEmpty(apiId)) {
RestApiUtil.handleBadRequest("The alias and/ or apiId should not be empty", log);
}
if (StringUtils.isBlank(fileName)) {
RestApiUtil.handleBadRequest("Certificate addition failed. Proper Certificate file should be provided", log);
}
// validate if api exists
validateAPIExistence(apiId);
API api = apiProvider.getAPIbyUUID(apiId, organization);
api.setOrganization(organization);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(api.getStatus());
String userName = RestApiCommonUtil.getLoggedInUsername();
String base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
int responseCode = apiProvider.addClientCertificate(userName, api.getId(), base64EncodedCert, alias, tier, organization);
if (log.isDebugEnabled()) {
log.debug(String.format("Add certificate operation response code : %d", responseCode));
}
if (ResponseCode.SUCCESS.getResponseCode() == responseCode) {
// Handle api product case.
if (API_PRODUCT_TYPE.equals(api.getType())) {
APIIdentifier apiIdentifier = api.getId();
APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
apiProduct.setOrganization(organization);
apiProvider.updateAPIProduct(apiProduct);
} else {
apiProvider.updateAPI(api);
}
ClientCertMetadataDTO certificateDTO = new ClientCertMetadataDTO();
certificateDTO.setAlias(alias);
certificateDTO.setApiId(apiId);
certificateDTO.setTier(tier);
URI createdCertUri = new URI(RestApiConstants.CLIENT_CERTS_BASE_PATH + "?alias=" + alias);
return Response.created(createdCertUri).entity(certificateDTO).build();
} else if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
RestApiUtil.handleInternalServerError("Internal server error while adding the client certificate to " + "API " + apiId, log);
} else if (ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE.getResponseCode() == responseCode) {
RestApiUtil.handleResourceAlreadyExistsError("The alias '" + alias + "' already exists in the trust store.", log);
} else if (ResponseCode.CERTIFICATE_EXPIRED.getResponseCode() == responseCode) {
RestApiUtil.handleBadRequest("Error while adding the certificate to the API " + apiId + ". " + "Certificate Expired.", log);
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("APIManagement exception while adding the certificate to the API " + apiId + " due to an internal " + "server error", e, log);
} catch (IOException e) {
RestApiUtil.handleInternalServerError("IOException while generating the encoded certificate for the API " + apiId, e, log);
} catch (URISyntaxException e) {
RestApiUtil.handleInternalServerError("Error while generating the resource location URI for alias '" + alias + "'", e, log);
} catch (FaultGatewaysException e) {
RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class ImportUtils method importApiProduct.
/**
* This method imports an API Product.
*
* @param extractedFolderPath Location of the extracted folder of the API Product
* @param preserveProvider Decision to keep or replace the provider
* @param overwriteAPIProduct Whether to update the API Product or not
* @param overwriteAPIs Whether to update the dependent APIs or not
* @param organization Organization Identifier
* @param importAPIs Whether to import the dependent APIs or not
* @throws APIImportExportException If there is an error in importing an API
*/
public static APIProduct importApiProduct(String extractedFolderPath, Boolean preserveProvider, Boolean rotateRevision, Boolean overwriteAPIProduct, Boolean overwriteAPIs, Boolean importAPIs, String[] tokenScopes, String organization) throws APIManagementException {
String userName = RestApiCommonUtil.getLoggedInUsername();
String currentTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(userName));
APIProduct importedApiProduct = null;
JsonArray deploymentInfoArray = null;
String currentStatus;
String targetStatus;
String lifecycleAction;
try {
JsonElement jsonObject = retrieveValidatedDTOObject(extractedFolderPath, preserveProvider, userName, ImportExportConstants.TYPE_API_PRODUCT);
APIProductDTO importedApiProductDTO = new Gson().fromJson(jsonObject, APIProductDTO.class);
// If the provided dependent APIs params config is null, it means this happening when importing an API (not
// because when importing a dependent API of an API Product). Hence, try to retrieve the definition from
// the API folder path
JsonObject paramsConfigObject = APIControllerUtil.resolveAPIControllerEnvParams(extractedFolderPath);
// If above the params configurations are not null, then resolve those
if (paramsConfigObject != null) {
importedApiProductDTO = APIControllerUtil.injectEnvParamsToAPIProduct(importedApiProductDTO, paramsConfigObject, extractedFolderPath);
JsonElement deploymentsParam = paramsConfigObject.get(ImportExportConstants.DEPLOYMENT_ENVIRONMENTS);
if (deploymentsParam != null && !deploymentsParam.isJsonNull()) {
deploymentInfoArray = deploymentsParam.getAsJsonArray();
}
}
APIProvider apiProvider = RestApiCommonUtil.getProvider(importedApiProductDTO.getProvider());
// Check whether the API resources are valid
checkAPIProductResourcesValid(extractedFolderPath, userName, apiProvider, importedApiProductDTO, preserveProvider, organization);
targetStatus = importedApiProductDTO.getState().toString();
if (importAPIs) {
// Import dependent APIs only if it is asked (the UUIDs of the dependent APIs will be updated here if a
// fresh import happens)
importedApiProductDTO = importDependentAPIs(extractedFolderPath, userName, preserveProvider, apiProvider, overwriteAPIs, rotateRevision, importedApiProductDTO, tokenScopes, organization);
} else {
// Even we do not import APIs, the UUIDs of the dependent APIs should be updated if the APIs are
// already in the APIM
importedApiProductDTO = updateDependentApiUuids(importedApiProductDTO, apiProvider, currentTenantDomain, organization);
}
APIProduct targetApiProduct = retrieveApiProductToOverwrite(importedApiProductDTO.getName(), currentTenantDomain, apiProvider, Boolean.TRUE, organization);
// If the overwrite is set to true (which means an update), retrieve the existing API
if (Boolean.TRUE.equals(overwriteAPIProduct) && targetApiProduct != null) {
log.info("Existing API Product found, attempting to update it...");
currentStatus = targetApiProduct.getState();
importedApiProduct = PublisherCommonUtils.updateApiProduct(targetApiProduct, importedApiProductDTO, RestApiCommonUtil.getLoggedInUserProvider(), userName, currentTenantDomain);
} else {
if (targetApiProduct == null && Boolean.TRUE.equals(overwriteAPIProduct)) {
log.info("Cannot find : " + importedApiProductDTO.getName() + ". Creating it.");
}
currentStatus = APIStatus.CREATED.toString();
importedApiProduct = PublisherCommonUtils.addAPIProductWithGeneratedSwaggerDefinition(importedApiProductDTO, importedApiProductDTO.getProvider(), organization);
}
// Retrieving the life cycle action to do the lifecycle state change explicitly later
lifecycleAction = getLifeCycleAction(currentTenantDomain, currentStatus, targetStatus, apiProvider);
// Add/update swagger of API Product
importedApiProduct = updateApiProductSwagger(extractedFolderPath, importedApiProduct.getUuid(), importedApiProduct, apiProvider, currentTenantDomain);
// Since Image, documents and client certificates are optional, exceptions are logged and ignored in
// implementation
ApiTypeWrapper apiTypeWrapperWithUpdatedApiProduct = new ApiTypeWrapper(importedApiProduct);
addThumbnailImage(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider);
addDocumentation(extractedFolderPath, apiTypeWrapperWithUpdatedApiProduct, apiProvider, organization);
if (log.isDebugEnabled()) {
log.debug("Mutual SSL enabled. Importing client certificates.");
}
addClientCertificates(extractedFolderPath, apiProvider, preserveProvider, importedApiProduct.getId().getProviderName(), organization);
// Change API Product lifecycle if state transition is required
if (StringUtils.isNotEmpty(lifecycleAction)) {
apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
log.info("Changing lifecycle from " + currentStatus + " to " + targetStatus);
apiProvider.changeLifeCycleStatus(currentTenantDomain, new ApiTypeWrapper(importedApiProduct), lifecycleAction, new HashMap<>());
}
importedApiProduct.setState(targetStatus);
if (deploymentInfoArray == null) {
// If the params have not overwritten the deployment environments, yaml file will be read
deploymentInfoArray = retrieveDeploymentLabelsFromArchive(extractedFolderPath, false);
}
List<APIRevisionDeployment> apiProductRevisionDeployments = getValidatedDeploymentsList(deploymentInfoArray, currentTenantDomain, apiProvider, organization);
if (apiProductRevisionDeployments.size() > 0) {
String importedAPIUuid = importedApiProduct.getUuid();
String revisionId;
APIRevision apiProductRevision = new APIRevision();
apiProductRevision.setApiUUID(importedAPIUuid);
apiProductRevision.setDescription("Revision created after importing the API Product");
try {
revisionId = apiProvider.addAPIProductRevision(apiProductRevision, organization);
if (log.isDebugEnabled()) {
log.debug("A new revision has been created for API Product " + importedApiProduct.getId().getName() + "_" + importedApiProduct.getId().getVersion() + " with ID: " + revisionId);
}
} catch (APIManagementException e) {
// rotateRevision enabled, earliest revision will be deleted before creating a revision again
if (e.getErrorHandler().getErrorCode() == ExceptionCodes.from(ExceptionCodes.MAXIMUM_REVISIONS_REACHED).getErrorCode() && rotateRevision) {
String earliestRevisionUuid = apiProvider.getEarliestRevisionUUID(importedAPIUuid);
List<APIRevisionDeployment> deploymentsList = apiProvider.getAPIRevisionDeploymentList(earliestRevisionUuid);
// if the earliest revision is already deployed in gateway environments, it will be undeployed
// before deleting
apiProvider.undeployAPIProductRevisionDeployment(importedAPIUuid, earliestRevisionUuid, deploymentsList);
apiProvider.deleteAPIProductRevision(importedAPIUuid, earliestRevisionUuid, organization);
revisionId = apiProvider.addAPIProductRevision(apiProductRevision, organization);
if (log.isDebugEnabled()) {
log.debug("Revision ID: " + earliestRevisionUuid + " has been undeployed from " + deploymentsList.size() + " gateway environments and created a new revision ID: " + revisionId + " for API Product " + importedApiProduct.getId().getName() + "_" + importedApiProduct.getId().getVersion());
}
} else {
throw new APIManagementException(e);
}
}
// Once the new revision successfully created, artifacts will be deployed in mentioned gateway
// environments
apiProvider.deployAPIProductRevision(importedAPIUuid, revisionId, apiProductRevisionDeployments);
} else {
log.info("Valid deployment environments were not found for the imported artifact. Hence not deployed" + " in any of the gateway environments.");
}
return importedApiProduct;
} catch (IOException e) {
// mandatory steps
throw new APIManagementException("Error while reading API Product meta information from path: " + extractedFolderPath, e);
} catch (FaultGatewaysException e) {
throw new APIManagementException("Error while updating API Product: " + importedApiProduct.getId().getName(), e);
} catch (APIManagementException e) {
String errorMessage = "Error while importing API Product: ";
if (importedApiProduct != null) {
errorMessage += importedApiProduct.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + importedApiProduct.getId().getVersion();
}
throw new APIManagementException(errorMessage + " " + e.getMessage(), e);
}
}
Aggregations