use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class APIMappingUtil method fromDTOtoAPI.
public static API fromDTOtoAPI(APIDTO dto, String provider) throws APIManagementException {
String providerEmailDomainReplaced = APIUtil.replaceEmailDomain(provider);
// The provider name that is coming from the body is not honored for now.
// Later we can use it by checking admin privileges of the user.
APIIdentifier apiId = new APIIdentifier(providerEmailDomainReplaced, dto.getName(), dto.getVersion());
API model = new API(apiId);
String context = dto.getContext();
final String originalContext = context;
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 && !context.contains("/t/" + providerDomain)) {
// Create tenant aware context for API
context = "/t/" + providerDomain + context;
}
// This is to support the pluggable version strategy
// if the context does not contain any {version} segment, we use the default version strategy.
context = checkAndSetVersionParam(context);
model.setContextTemplate(context);
context = updateContextWithVersion(dto.getVersion(), originalContext, context);
model.setContext(context);
model.setDescription(dto.getDescription());
if (dto.getEndpointConfig() != null) {
ObjectMapper mapper = new ObjectMapper();
try {
model.setEndpointConfig(mapper.writeValueAsString(dto.getEndpointConfig()));
} catch (IOException e) {
handleException("Error while converting endpointConfig to json", e);
}
}
model.setImplementation(dto.getEndpointImplementationType().toString());
model.setType(dto.getType().toString());
if (dto.getLifeCycleStatus() != null) {
model.setStatus((dto.getLifeCycleStatus() != null) ? dto.getLifeCycleStatus().toUpperCase() : null);
}
if (dto.isIsDefaultVersion() != null) {
model.setAsDefaultVersion(dto.isIsDefaultVersion());
}
if (dto.isEnableSchemaValidation() != null) {
model.setEnableSchemaValidation(dto.isEnableSchemaValidation());
}
model.setEnableStore(true);
if (dto.getAdvertiseInfo() != null) {
AdvertiseInfoDTO advertiseInfoDTO = dto.getAdvertiseInfo();
model.setAdvertiseOnly(advertiseInfoDTO.isAdvertised());
model.setApiExternalProductionEndpoint(advertiseInfoDTO.getApiExternalProductionEndpoint());
model.setApiExternalSandboxEndpoint(advertiseInfoDTO.getApiExternalSandboxEndpoint());
model.setRedirectURL(advertiseInfoDTO.getOriginalDevPortalUrl());
model.setApiOwner(advertiseInfoDTO.getApiOwner());
model.setAdvertiseOnlyAPIVendor(dto.getAdvertiseInfo().getVendor().value());
}
if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
model.setResponseCache(APIConstants.ENABLED);
} else {
model.setResponseCache(APIConstants.DISABLED);
}
if (dto.getCacheTimeout() != null) {
model.setCacheTimeout(dto.getCacheTimeout());
} else {
model.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
}
if (dto.getMediationPolicies() != null) {
List<MediationPolicyDTO> policies = dto.getMediationPolicies();
// validate whether provided sequences are available
for (MediationPolicyDTO policy : policies) {
if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN.equalsIgnoreCase(policy.getType())) {
model.setInSequence(policy.getName());
} else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT.equalsIgnoreCase(policy.getType())) {
model.setOutSequence(policy.getName());
} else {
model.setFaultSequence(policy.getName());
}
}
}
if (dto.getSubscriptionAvailability() != null) {
model.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPI(dto.getSubscriptionAvailability()));
}
if (dto.getSubscriptionAvailableTenants() != null) {
model.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
}
Set<Scope> scopes = getScopes(dto);
model.setScopes(scopes);
// URI Templates
// No default topics for AsyncAPIs. Therefore set URITemplates only for non-AsyncAPIs.
Set<URITemplate> uriTemplates = getURITemplates(model, dto.getOperations());
model.setUriTemplates(uriTemplates);
// wsUriMapping
if (dto.getType().toString().equals(APIConstants.API_TYPE_WS)) {
Map<String, String> wsUriMapping = new HashMap<>();
for (APIOperationsDTO operationsDTO : dto.getOperations()) {
wsUriMapping.put(operationsDTO.getVerb() + "_" + operationsDTO.getTarget(), operationsDTO.getUriMapping());
}
model.setWsUriMapping(wsUriMapping);
}
if (dto.getTags() != null) {
Set<String> apiTags = new HashSet<>(dto.getTags());
model.addTags(apiTags);
}
Set<Tier> apiTiers = new HashSet<>();
List<String> tiersFromDTO = dto.getPolicies();
for (String tier : tiersFromDTO) {
apiTiers.add(new Tier(tier));
}
model.addAvailableTiers(apiTiers);
model.setApiLevelPolicy(dto.getApiThrottlingPolicy());
String transports = StringUtils.join(dto.getTransport(), ',');
model.setTransports(transports);
if (dto.getVisibility() != null) {
model.setVisibility(mapVisibilityFromDTOtoAPI(dto.getVisibility()));
}
if (dto.getVisibleRoles() != null) {
String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
model.setVisibleRoles(visibleRoles);
}
if (dto.getVisibleTenants() != null) {
if (APIUtil.isCrossTenantSubscriptionsEnabled()) {
String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
model.setVisibleTenants(visibleTenants);
}
}
List<String> accessControlRoles = dto.getAccessControlRoles();
if (accessControlRoles == null || accessControlRoles.isEmpty()) {
model.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
model.setAccessControlRoles("null");
} else {
model.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
model.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
}
List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
if (additionalProperties != null) {
for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
if (property.isDisplay()) {
model.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
} else {
model.addProperty(property.getName(), property.getValue());
}
}
}
Map<String, APIInfoAdditionalPropertiesMapDTO> additionalPropertiesMap = dto.getAdditionalPropertiesMap();
if (additionalPropertiesMap != null && !additionalPropertiesMap.isEmpty()) {
for (Map.Entry<String, APIInfoAdditionalPropertiesMapDTO> entry : additionalPropertiesMap.entrySet()) {
if (entry.getValue().isDisplay()) {
model.addProperty(entry.getKey() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, entry.getValue().getValue());
} else {
model.addProperty(entry.getKey(), entry.getValue().getValue());
}
}
}
ObjectMapper objectMapper = new ObjectMapper();
APIBusinessInformationDTO apiBusinessInformationDTO = objectMapper.convertValue(dto.getBusinessInformation(), APIBusinessInformationDTO.class);
if (apiBusinessInformationDTO != null) {
model.setBusinessOwner(apiBusinessInformationDTO.getBusinessOwner());
model.setBusinessOwnerEmail(apiBusinessInformationDTO.getBusinessOwnerEmail());
model.setTechnicalOwner(apiBusinessInformationDTO.getTechnicalOwner());
model.setTechnicalOwnerEmail(apiBusinessInformationDTO.getTechnicalOwnerEmail());
}
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();
}
model.setCorsConfiguration(corsConfiguration);
setMaxTpsFromApiDTOToModel(dto, model);
model.setAuthorizationHeader(dto.getAuthorizationHeader());
model.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
if (dto.getType().toString().equals(APIConstants.API_TYPE_WEBSUB)) {
WebsubSubscriptionConfigurationDTO websubSubscriptionConfigurationDTO = dto.getWebsubSubscriptionConfiguration();
WebsubSubscriptionConfiguration websubSubscriptionConfiguration;
if (websubSubscriptionConfigurationDTO != null) {
websubSubscriptionConfiguration = new WebsubSubscriptionConfiguration(websubSubscriptionConfigurationDTO.isEnable(), websubSubscriptionConfigurationDTO.getSecret(), websubSubscriptionConfigurationDTO.getSigningAlgorithm(), websubSubscriptionConfigurationDTO.getSignatureHeader());
} else {
websubSubscriptionConfiguration = getDefaultWebsubSubscriptionConfiguration();
}
model.setWebsubSubscriptionConfiguration(websubSubscriptionConfiguration);
}
// attach api categories to API model
setAPICategoriesToModel(dto, model, provider);
if (dto.getKeyManagers() instanceof List) {
model.setKeyManagers((List<String>) dto.getKeyManagers());
} else if (dto.getKeyManagers() == null) {
model.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
} else {
throw new APIManagementException("KeyManagers value need to be an array");
}
APIServiceInfoDTO serviceInfoDTO = dto.getServiceInfo();
if (serviceInfoDTO != null) {
ObjectMapper mapper = new ObjectMapper();
JSONParser parser = new JSONParser();
JSONObject serviceInfoJson;
String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
try {
int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
serviceInfoJson = (JSONObject) parser.parse(mapper.writeValueAsString(serviceInfoDTO));
ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
ServiceEntry service = serviceCatalog.getServiceByKey(dto.getServiceInfo().getKey(), tenantId);
// Set the md5 of the service which is already available in the system to the API model
if (service == null) {
if (log.isDebugEnabled()) {
log.debug("A service with key" + dto.getServiceInfo().getKey() + " referenced in the API " + "information is not available in the service catalog");
}
} else {
serviceInfoJson.put("md5", service.getMd5());
}
model.setServiceInfo(serviceInfoJson);
} catch (JsonProcessingException | ParseException e) {
String msg = "Error while getting json representation of APIServiceInfo";
handleException(msg, e);
} catch (UserStoreException e) {
String msg = "Error while getting tenantId from the given tenant domain " + tenantDomain;
handleException(msg, e);
}
}
if (dto.getAudience() != null) {
model.setAudience(dto.getAudience().toString());
}
if (dto.getGatewayVendor() != null) {
model.setGatewayVendor(dto.getGatewayVendor());
}
if (dto.getAsyncTransportProtocols() != null) {
String asyncTransports = StringUtils.join(dto.getAsyncTransportProtocols(), ',');
model.setAsyncTransportProtocols(asyncTransports);
}
return model;
}
use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class ServicesApiServiceImpl method validateVerifier.
private Map<String, Boolean> validateVerifier(String verifier, int tenantId) throws APIManagementException {
Map<String, Boolean> validationResults = new HashMap<>();
JSONArray verifierArray = new JSONArray(verifier);
for (int i = 0; i < verifierArray.length(); i++) {
JSONObject verifierJson = verifierArray.getJSONObject(i);
ServiceEntry service = serviceCatalog.getServiceByKey(verifierJson.get("key").toString(), tenantId);
if (service != null) {
if (service.getMd5().equals(verifierJson.get("md5").toString())) {
validationResults.put(service.getKey(), true);
} else {
validationResults.put(service.getKey(), false);
}
}
}
return validationResults;
}
use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class ServicesApiServiceImpl method updateService.
@Override
public Response updateService(String serviceId, ServiceDTO serviceDTO, InputStream definitionFileInputStream, Attachment definitionFileDetail, String inlineContent, MessageContext messageContext) {
String userName = RestApiCommonUtil.getLoggedInUsername();
int tenantId = APIUtil.getTenantId(userName);
if (StringUtils.isEmpty(serviceId)) {
RestApiUtil.handleBadRequest("The service Id should not be empty", log);
}
validateInputParams(definitionFileInputStream, definitionFileDetail, inlineContent);
try {
ServiceEntry existingService = serviceCatalog.getServiceByUUID(serviceId, tenantId);
byte[] definitionFileByteArray;
if (definitionFileInputStream != null) {
definitionFileByteArray = getDefinitionFromInput(definitionFileInputStream);
} else {
definitionFileByteArray = inlineContent.getBytes();
}
ServiceEntry service = ServiceCatalogUtils.createServiceFromDTO(serviceDTO, definitionFileByteArray);
if (!validateAndRetrieveServiceDefinition(definitionFileByteArray, serviceDTO.getServiceUrl(), service.getDefinitionType()).isValid()) {
String errorMsg = "The Service import has been failed as invalid service definition provided";
return Response.status(Response.Status.BAD_REQUEST).entity(getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400L, errorMsg, StringUtils.EMPTY)).build();
}
if (!existingService.getKey().equals(service.getKey()) || !existingService.getName().equals(service.getName()) || !existingService.getDefinitionType().equals(service.getDefinitionType()) || !existingService.getVersion().equals(service.getVersion())) {
RestApiUtil.handleBadRequest("Cannot update the name or version or key or definition type of an " + "existing service", log);
}
service.setUuid(existingService.getUuid());
serviceCatalog.updateService(service, tenantId, userName);
ServiceEntry createdService = serviceCatalog.getServiceByUUID(serviceId, tenantId);
return Response.ok().entity(ServiceEntryMappingUtil.fromServiceToDTO(createdService, false)).build();
} catch (APIManagementException e) {
if (RestApiUtil.isDueToResourceNotFound(e)) {
RestApiUtil.handleResourceNotFoundError("Service", serviceId, e, log);
}
RestApiUtil.handleInternalServerError("Error when validating the service definition", log);
} catch (IOException e) {
RestApiUtil.handleInternalServerError("Error when reading the file content", log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class ServicesApiServiceImpl method exportService.
@Override
public Response exportService(String name, String version, MessageContext messageContext) {
File exportedServiceArchiveFile = null;
// creates a directory in default temporary-file directory
String pathToExportDir = FileBasedServicesImportExportManager.createDir(RestApiConstants.JAVA_IO_TMPDIR);
String userName = RestApiCommonUtil.getLoggedInUsername();
int tenantId = APIUtil.getTenantId(userName);
String archiveName = name + APIConstants.KEY_SEPARATOR + version;
ServiceEntry serviceEntry;
String exportedFileName = null;
ExportArchive exportArchive;
if (StringUtils.isBlank(name) || StringUtils.isBlank(version)) {
RestApiUtil.handleBadRequest("Service name or owner should not be empty or null.", log);
}
try {
serviceEntry = serviceCatalog.getServiceByNameAndVersion(name, version, tenantId);
if (serviceEntry != null) {
FileBasedServicesImportExportManager importExportManager = new FileBasedServicesImportExportManager(pathToExportDir);
exportArchive = importExportManager.createArchiveFromExportedServices(ServiceEntryMappingUtil.generateServiceFiles(serviceEntry), pathToExportDir, archiveName);
exportedServiceArchiveFile = new File(exportArchive.getArchiveName());
exportedFileName = exportedServiceArchiveFile.getName();
Response.ResponseBuilder responseBuilder = Response.status(Response.Status.OK).entity(exportedServiceArchiveFile).type(MediaType.APPLICATION_OCTET_STREAM);
responseBuilder.header("Content-Disposition", "attachment; filename=\"" + exportedFileName + "\"");
return responseBuilder.build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error while exporting Services: " + archiveName, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class ServicesApiServiceImpl method getServiceById.
@Override
public Response getServiceById(String serviceId, MessageContext messageContext) {
String userName = RestApiCommonUtil.getLoggedInUsername();
int tenantId = APIUtil.getTenantId(userName);
try {
ServiceEntry service = serviceCatalog.getServiceByUUID(serviceId, tenantId);
ServiceDTO serviceDTO = ServiceEntryMappingUtil.fromServiceToDTO(service, false);
return Response.ok().entity(serviceDTO).build();
} catch (APIManagementException e) {
if (RestApiUtil.isDueToResourceNotFound(e)) {
RestApiUtil.handleResourceNotFoundError("Service", serviceId, e, log);
} else {
RestApiUtil.handleInternalServerError("Error while fetching the Service with ID " + serviceId, e, log);
}
}
return null;
}
Aggregations