use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method createNewAPIVersion.
@Override
public Response createNewAPIVersion(String newVersion, String apiId, Boolean defaultVersion, String serviceVersion, MessageContext messageContext) throws APIManagementException {
URI newVersionedApiUri;
APIDTO newVersionedApi = new APIDTO();
ServiceEntry service = new ServiceEntry();
try {
APIIdentifier apiIdentifierFromTable = APIMappingUtil.getAPIIdentifierFromUUID(apiId);
if (apiIdentifierFromTable == null) {
throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
}
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
int tenantId = APIUtil.getInternalOrganizationId(organization);
API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
if (existingAPI == null) {
throw new APIMgtResourceNotFoundException("API not found for id " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
}
if (newVersion.equals(existingAPI.getId().getVersion())) {
throw new APIMgtResourceAlreadyExistsException("Version " + newVersion + " exists for api " + existingAPI.getId().getApiName(), ExceptionCodes.from(API_VERSION_ALREADY_EXISTS, newVersion, existingAPI.getId().getApiName()));
}
if (StringUtils.isNotEmpty(serviceVersion)) {
String serviceName = existingAPI.getServiceInfo("name");
ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
service = serviceCatalog.getServiceByNameAndVersion(serviceName, serviceVersion, tenantId);
if (service == null) {
throw new APIManagementException("No matching service version found", ExceptionCodes.SERVICE_VERSION_NOT_FOUND);
}
}
if (StringUtils.isNotEmpty(serviceVersion) && !serviceVersion.equals(existingAPI.getServiceInfo("version"))) {
APIDTO apidto = createAPIDTO(existingAPI, newVersion);
if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
newVersionedApi = importOpenAPIDefinition(service.getEndpointDef(), null, null, apidto, null, service, organization);
} else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
newVersionedApi = importAsyncAPISpecification(service.getEndpointDef(), null, apidto, null, service, organization);
}
} else {
API versionedAPI = apiProvider.createNewAPIVersion(apiId, newVersion, defaultVersion, organization);
newVersionedApi = APIMappingUtil.fromAPItoDTO(versionedAPI);
}
// This URI used to set the location header of the POST response
newVersionedApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + newVersionedApi.getId());
return Response.created(newVersionedApiUri).entity(newVersionedApi).build();
} catch (APIManagementException e) {
if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while copying API : " + apiId, e, log);
} else {
throw e;
}
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving API location of " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method importAsyncAPISpecification.
private APIDTO importAsyncAPISpecification(InputStream definition, String definitionUrl, APIDTO apiDTOFromProperties, Attachment fileDetail, ServiceEntry service, String organization) {
// validate and retrieve the AsyncAPI specification
Map validationResponseMap = null;
boolean isServiceAPI = false;
try {
if (service != null) {
isServiceAPI = true;
}
validationResponseMap = validateAsyncAPISpecification(definitionUrl, definition, fileDetail, true, isServiceAPI);
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error occurred while validating API Definition", e, log);
}
AsyncAPISpecificationValidationResponseDTO validationResponseDTO = (AsyncAPISpecificationValidationResponseDTO) validationResponseMap.get(RestApiConstants.RETURN_DTO);
APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
if (!validationResponseDTO.isIsValid()) {
ErrorDTO errorDTO = APIMappingUtil.getErrorDTOFromErrorListItems(validationResponseDTO.getErrors());
throw RestApiUtil.buildBadRequestException(errorDTO);
}
// Import the API and Definition
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String definitionToAdd = validationResponse.getJsonContent();
String protocol = validationResponse.getProtocol();
if (isServiceAPI) {
apiDTOFromProperties.setType(PublisherCommonUtils.getAPIType(service.getDefinitionType(), protocol));
}
if (!APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(apiDTOFromProperties.getGatewayVendor())) {
apiDTOFromProperties.getPolicies().add(APIConstants.DEFAULT_SUB_POLICY_ASYNC_UNLIMITED);
apiDTOFromProperties.setAsyncTransportProtocols(AsyncApiParser.getTransportProtocolsForAsyncAPI(definitionToAdd));
}
API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(apiDTOFromProperties, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
if (isServiceAPI) {
apiToAdd.setServiceInfo("key", service.getKey());
apiToAdd.setServiceInfo("md5", service.getMd5());
if (!APIConstants.API_TYPE_WEBSUB.equals(protocol.toUpperCase())) {
apiToAdd.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), protocol));
}
}
apiToAdd.setAsyncApiDefinition(definitionToAdd);
// load topics from AsyncAPI
apiToAdd.setUriTemplates(new AsyncApiParser().getURITemplates(definitionToAdd, APIConstants.API_TYPE_WS.equals(apiToAdd.getType()) || !APIConstants.WSO2_GATEWAY_ENVIRONMENT.equals(apiToAdd.getGatewayVendor())));
apiToAdd.setOrganization(organization);
apiToAdd.setAsyncApiDefinition(definitionToAdd);
apiProvider.addAPI(apiToAdd);
return APIMappingUtil.fromAPItoDTO(apiProvider.getAPIbyUUID(apiToAdd.getUuid(), organization));
} catch (APIManagementException e) {
String errorMessage = "Error while adding new API : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion() + " - " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class Md5HashGenerator method validateInputParams.
/**
* This traversal through the directories and calculate md5
*
* @param files list of files available directory location
* @return HashMap<String, String>
*/
private static HashMap<String, String> validateInputParams(File[] files) {
for (File file : files) {
if (file.isDirectory()) {
// Else is not required since this for taking only the directories. If it is an empty zip, then
// the final map will be empty.
File[] fileArray = file.listFiles();
if (fileArray != null) {
// Order files according to the alphabetical order of file names when concatenating hashes.
Arrays.sort(fileArray, NameFileComparator.NAME_COMPARATOR);
String key = null;
for (File yamlFile : fileArray) {
if (yamlFile.getName().startsWith(APIConstants.METADATA_FILE_NAME)) {
// This if only check whether the file start with the name "metadata".
try {
ServiceEntry service = fromFileToServiceEntry(yamlFile, null);
key = service.getKey();
} catch (IOException e) {
RestApiUtil.handleBadRequest("Failed to fetch metadata information", log);
}
}
}
try {
endpoints.put(key, calculateHash(fileArray));
} catch (NoSuchAlgorithmException | IOException e) {
RestApiUtil.handleInternalServerError("Failed to generate MD5 Hash due to " + e.getMessage(), log);
} catch (ArrayIndexOutOfBoundsException e) {
RestApiUtil.handleBadRequest("Required metadata.yaml or definition.yaml is missing", log);
}
}
}
}
return endpoints;
}
use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class ServiceEntryMappingUtil method fromServiceToDTO.
public static ServiceDTO fromServiceToDTO(ServiceEntry service, boolean shrink) {
ServiceDTO serviceDTO = new ServiceDTO();
serviceDTO.setId(service.getUuid());
serviceDTO.setName(service.getName());
serviceDTO.setVersion(service.getVersion());
serviceDTO.setMd5(service.getMd5());
serviceDTO.setServiceKey(service.getKey());
if (!shrink) {
serviceDTO.setServiceUrl(service.getServiceUrl());
serviceDTO.setDefinitionType(ServiceDTO.DefinitionTypeEnum.fromValue(service.getDefinitionType().toString()));
serviceDTO.setDefinitionUrl(service.getDefUrl());
serviceDTO.setDescription(service.getDescription());
serviceDTO.setSecurityType(ServiceDTO.SecurityTypeEnum.fromValue(service.getSecurityType().toString()));
serviceDTO.setMutualSSLEnabled(service.isMutualSSLEnabled());
serviceDTO.setCreatedTime(String.valueOf(service.getCreatedTime()));
serviceDTO.setLastUpdatedTime(String.valueOf(service.getLastUpdatedTime()));
serviceDTO.setUsage(service.getUsage());
}
return serviceDTO;
}
use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class ServicesApiServiceImpl method addService.
@Override
public Response addService(ServiceDTO serviceDTO, InputStream definitionFileInputStream, Attachment definitionFileDetail, String inlineContent, MessageContext messageContext) {
String userName = RestApiCommonUtil.getLoggedInUsername();
int tenantId = APIUtil.getTenantId(userName);
try {
validateInputParams(definitionFileInputStream, definitionFileDetail, inlineContent);
ServiceEntry existingService = serviceCatalog.getServiceByKey(serviceDTO.getServiceKey(), tenantId);
if (existingService != null) {
RestApiUtil.handleResourceAlreadyExistsError("Error while adding Service : A service already " + "exists with key: " + serviceDTO.getServiceKey(), log);
}
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();
}
String serviceId = serviceCatalog.addService(service, tenantId, userName);
ServiceEntry createdService = serviceCatalog.getServiceByUUID(serviceId, tenantId);
return Response.ok().entity(ServiceEntryMappingUtil.fromServiceToDTO(createdService, false)).build();
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error when validating the service definition", log);
} catch (IOException e) {
RestApiUtil.handleInternalServerError("Error when reading the file content", log);
}
return null;
}
Aggregations