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;
}
use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class ServicesApiServiceImpl method getServiceDefinition.
@Override
public Response getServiceDefinition(String serviceId, MessageContext messageContext) {
String user = RestApiCommonUtil.getLoggedInUsername();
int tenantId = APIUtil.getTenantId(user);
String contentType = StringUtils.EMPTY;
try {
ServiceEntry service = serviceCatalog.getServiceByUUID(serviceId, tenantId);
if (ServiceDTO.DefinitionTypeEnum.OAS3.equals(ServiceDTO.DefinitionTypeEnum.fromValue(service.getDefinitionType().name())) || ServiceDTO.DefinitionTypeEnum.OAS2.equals(ServiceDTO.DefinitionTypeEnum.fromValue(service.getDefinitionType().name())) || ServiceDTO.DefinitionTypeEnum.ASYNC_API.equals(ServiceDTO.DefinitionTypeEnum.fromValue(service.getDefinitionType().name()))) {
contentType = "application/yaml";
} else if (ServiceDTO.DefinitionTypeEnum.WSDL1.equals(ServiceDTO.DefinitionTypeEnum.fromValue(service.getDefinitionType().name()))) {
contentType = "text/xml";
}
InputStream serviceDefinition = service.getEndpointDef();
if (serviceDefinition == null) {
RestApiUtil.handleResourceNotFoundError("Service definition not found for service with ID: " + serviceId, log);
} else {
return Response.ok(serviceDefinition).type(contentType).build();
}
} catch (APIManagementException e) {
if (RestApiUtil.isDueToResourceNotFound(e)) {
RestApiUtil.handleResourceNotFoundError("Service", serviceId, e, log);
} else if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving the definition" + " of service with ID: " + serviceId, e, log);
} else {
RestApiUtil.handleInternalServerError("Error when retrieving the endpoint definition of service " + "with id " + serviceId, e, log);
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class ServicesApiServiceImpl method importService.
@Override
public Response importService(InputStream fileInputStream, Attachment fileDetail, Boolean overwrite, String verifier, MessageContext messageContext) throws APIManagementException {
String userName = RestApiCommonUtil.getLoggedInUsername();
int tenantId = APIUtil.getTenantId(userName);
String tempDirPath = FileBasedServicesImportExportManager.createDir(RestApiConstants.JAVA_IO_TMPDIR);
List<ServiceInfoDTO> serviceList;
HashMap<String, ServiceEntry> serviceEntries;
HashMap<String, String> newResourcesHash;
List<ServiceEntry> serviceListToImport = new ArrayList<>();
List<ServiceEntry> serviceListToIgnore = new ArrayList<>();
List<ServiceEntry> servicesWithInvalidDefinition = new ArrayList<>();
// unzip the uploaded zip
try {
FileBasedServicesImportExportManager importExportManager = new FileBasedServicesImportExportManager(tempDirPath);
importExportManager.importService(fileInputStream);
} catch (APIMgtResourceAlreadyExistsException e) {
RestApiUtil.handleResourceAlreadyExistsError("Error while importing Service", e, log);
}
newResourcesHash = Md5HashGenerator.generateHash(tempDirPath);
serviceEntries = ServiceEntryMappingUtil.fromDirToServiceEntryMap(tempDirPath);
Map<String, Boolean> validationResults = new HashMap<>();
if (overwrite && StringUtils.isNotEmpty(verifier)) {
validationResults = validateVerifier(verifier, tenantId);
}
try {
for (Map.Entry<String, ServiceEntry> entry : serviceEntries.entrySet()) {
String key = entry.getKey();
serviceEntries.get(key).setMd5(newResourcesHash.get(key));
ServiceEntry service = serviceEntries.get(key);
byte[] definitionFileByteArray = getDefinitionFromInput(service.getEndpointDef());
if (validateAndRetrieveServiceDefinition(definitionFileByteArray, service.getDefUrl(), service.getDefinitionType()).isValid() || (ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType()) && APIMWSDLReader.validateWSDLFile(definitionFileByteArray).isValid())) {
service.setEndpointDef(new ByteArrayInputStream(definitionFileByteArray));
} else {
servicesWithInvalidDefinition.add(service);
}
if (overwrite) {
if (StringUtils.isNotEmpty(verifier) && validationResults.containsKey(service.getKey()) && !validationResults.get(service.getKey())) {
serviceListToIgnore.add(service);
} else {
serviceListToImport.add(service);
}
} else {
serviceListToImport.add(service);
}
}
} catch (IOException e) {
RestApiUtil.handleInternalServerError("Error when reading the service definition content", log);
}
if (servicesWithInvalidDefinition.size() > 0) {
serviceList = ServiceEntryMappingUtil.fromServiceListToDTOList(servicesWithInvalidDefinition);
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, new JSONArray(serviceList).toString())).build();
}
if (serviceListToIgnore.size() > 0) {
serviceList = ServiceEntryMappingUtil.fromServiceListToDTOList(serviceListToIgnore);
String errorMsg = "The Service import has been failed since to verifier validation fails";
return Response.status(Response.Status.BAD_REQUEST).entity(getErrorDTO(RestApiConstants.STATUS_BAD_REQUEST_MESSAGE_DEFAULT, 400L, errorMsg, new JSONArray(serviceList).toString())).build();
} else {
List<ServiceEntry> importedServiceList = new ArrayList<>();
List<ServiceEntry> retrievedServiceList = new ArrayList<>();
try {
if (serviceListToImport.size() > 0) {
importedServiceList = serviceCatalog.importServices(serviceListToImport, tenantId, userName, overwrite);
}
} catch (APIManagementException e) {
if (ExceptionCodes.SERVICE_IMPORT_FAILED_WITHOUT_OVERWRITE.getErrorCode() == e.getErrorHandler().getErrorCode()) {
RestApiUtil.handleBadRequest("Cannot update existing services when overwrite is false", log);
} else {
RestApiUtil.handleInternalServerError("Error when importing services to service catalog", e, log);
}
}
if (importedServiceList == null) {
RestApiUtil.handleBadRequest("Cannot update the name or version or key or definition type of an " + "existing service", log);
}
for (ServiceEntry service : importedServiceList) {
retrievedServiceList.add(serviceCatalog.getServiceByKey(service.getKey(), tenantId));
}
serviceList = ServiceEntryMappingUtil.fromServiceListToDTOList(retrievedServiceList);
return Response.ok().entity(ServiceEntryMappingUtil.fromServiceInfoDTOToServiceInfoListDTO(serviceList)).build();
}
}
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;
}
Aggregations