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 ApisApiServiceImpl method importOpenAPIDefinition.
private APIDTO importOpenAPIDefinition(InputStream definition, String definitionUrl, String inlineDefinition, APIDTO apiDTOFromProperties, Attachment fileDetail, ServiceEntry service, String organization) throws APIManagementException {
// Validate and retrieve the OpenAPI definition
Map validationResponseMap = null;
boolean isServiceAPI = false;
try {
if (service != null) {
isServiceAPI = true;
}
validationResponseMap = validateOpenAPIDefinition(definitionUrl, definition, fileDetail, inlineDefinition, true, isServiceAPI);
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error occurred while validating API Definition", e, log);
}
OpenAPIDefinitionValidationResponseDTO validationResponseDTO = (OpenAPIDefinitionValidationResponseDTO) 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);
}
// Only HTTP or WEBHOOK type APIs should be allowed
if (!(APIDTO.TypeEnum.HTTP.equals(apiDTOFromProperties.getType()) || APIDTO.TypeEnum.WEBHOOK.equals(apiDTOFromProperties.getType()))) {
throw RestApiUtil.buildBadRequestException("The API's type is not supported when importing an OpenAPI definition");
}
// Import the API and Definition
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
if (isServiceAPI) {
apiDTOFromProperties.setType(PublisherCommonUtils.getAPIType(service.getDefinitionType(), null));
}
API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(apiDTOFromProperties, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
if (isServiceAPI) {
apiToAdd.setServiceInfo("key", service.getKey());
apiToAdd.setServiceInfo("md5", service.getMd5());
apiToAdd.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), null));
}
boolean syncOperations = apiDTOFromProperties.getOperations().size() > 0;
// Rearrange paths according to the API payload and save the OpenAPI definition
APIDefinition apiDefinition = validationResponse.getParser();
SwaggerData swaggerData;
String definitionToAdd = validationResponse.getJsonContent();
if (syncOperations) {
PublisherCommonUtils.validateScopes(apiToAdd);
swaggerData = new SwaggerData(apiToAdd);
definitionToAdd = apiDefinition.populateCustomManagementInfo(definitionToAdd, swaggerData);
}
definitionToAdd = OASParserUtil.preProcess(definitionToAdd);
Set<URITemplate> uriTemplates = apiDefinition.getURITemplates(definitionToAdd);
Set<Scope> scopes = apiDefinition.getScopes(definitionToAdd);
apiToAdd.setUriTemplates(uriTemplates);
apiToAdd.setScopes(scopes);
// Set extensions from API definition to API object
apiToAdd = OASParserUtil.setExtensionsToAPI(definitionToAdd, apiToAdd);
if (!syncOperations) {
PublisherCommonUtils.validateScopes(apiToAdd);
swaggerData = new SwaggerData(apiToAdd);
definitionToAdd = apiDefinition.populateCustomManagementInfo(validationResponse.getJsonContent(), swaggerData);
}
// adding the API and definition
apiToAdd.setSwaggerDefinition(definitionToAdd);
API addedAPI = apiProvider.addAPI(apiToAdd);
// apiProvider.saveSwaggerDefinition(apiToAdd, definitionToAdd);
// retrieving the added API for returning as the response
// this would provide the updated templates
addedAPI = apiProvider.getAPIbyUUID(addedAPI.getUuid(), organization);
return APIMappingUtil.fromAPItoDTO(addedAPI);
}
use of org.wso2.carbon.apimgt.api.model.ServiceEntry in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method importServiceFromCatalog.
@Override
public Response importServiceFromCatalog(String serviceKey, APIDTO apiDto, MessageContext messageContext) {
if (StringUtils.isEmpty(serviceKey)) {
RestApiUtil.handleBadRequest("Required parameter serviceKey is missing", log);
}
try {
ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
String username = RestApiCommonUtil.getLoggedInUsername();
int tenantId = APIUtil.getTenantId(username);
ServiceEntry service = serviceCatalog.getServiceByKey(serviceKey, tenantId);
if (service == null) {
RestApiUtil.handleResourceNotFoundError("Service", serviceKey, log);
}
APIDTO createdApiDTO = null;
String organization = RestApiUtil.getValidatedOrganization(messageContext);
if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
createdApiDTO = importOpenAPIDefinition(service.getEndpointDef(), null, null, apiDto, null, service, organization);
} else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
createdApiDTO = importAsyncAPISpecification(service.getEndpointDef(), null, apiDto, null, service, organization);
} else if (ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
apiDto.setProvider(RestApiCommonUtil.getLoggedInUsername());
apiDto.setType(APIDTO.TypeEnum.fromValue("SOAP"));
API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(apiDto, RestApiCommonUtil.getLoggedInUserProvider(), username, organization);
apiToAdd.setServiceInfo("key", service.getKey());
apiToAdd.setServiceInfo("md5", service.getMd5());
apiToAdd.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), null));
API api = importSOAPAPI(service.getEndpointDef(), null, null, apiToAdd, organization, service);
createdApiDTO = APIMappingUtil.fromAPItoDTO(api);
}
if (createdApiDTO != null) {
URI createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdApiDTO.getId());
return Response.created(createdApiUri).entity(createdApiDTO).build();
} else {
RestApiUtil.handleBadRequest("Unsupported definition type provided. Cannot create API " + "using the service type " + service.getDefinitionType().name(), log);
}
} catch (APIManagementException e) {
if (RestApiUtil.isDueToResourceNotFound(e)) {
RestApiUtil.handleResourceNotFoundError("Service", serviceKey, e, log);
} else {
String errorMessage = "Error while creating API using Service with Id : " + serviceKey + " from Service Catalog";
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving API location : " + apiDto.getName() + "-" + apiDto.getVersion();
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 reimportServiceFromCatalog.
@Override
public Response reimportServiceFromCatalog(String apiId, MessageContext messageContext) throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String username = RestApiCommonUtil.getLoggedInUsername();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
int tenantId = APIUtil.getTenantId(username);
try {
// validate if api exists
APIInfo apiInfo = validateAPIExistence(apiId);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(apiInfo.getStatus().toString());
API api = apiProvider.getLightweightAPIByUUID(apiId, organization);
API originalAPI = apiProvider.getAPIbyUUID(apiId, organization);
String serviceKey = apiProvider.retrieveServiceKeyByApiId(originalAPI.getId().getId(), tenantId);
ServiceCatalogImpl serviceCatalog = new ServiceCatalogImpl();
ServiceEntry service = serviceCatalog.getServiceByKey(serviceKey, tenantId);
JSONObject serviceInfo = new JSONObject();
serviceInfo.put("name", service.getName());
serviceInfo.put("version", service.getVersion());
serviceInfo.put("key", service.getKey());
serviceInfo.put("md5", service.getMd5());
api.setServiceInfo(serviceInfo);
Map validationResponseMap = new HashMap();
if (ServiceEntry.DefinitionType.OAS2.equals(service.getDefinitionType()) || ServiceEntry.DefinitionType.OAS3.equals(service.getDefinitionType())) {
validationResponseMap = validateOpenAPIDefinition(null, service.getEndpointDef(), null, null, true, true);
} else if (ServiceEntry.DefinitionType.ASYNC_API.equals(service.getDefinitionType())) {
validationResponseMap = validateAsyncAPISpecification(null, service.getEndpointDef(), null, true, true);
} else if (!ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
RestApiUtil.handleBadRequest("Unsupported definition type provided. Cannot re-import service to " + "API using the service type " + service.getDefinitionType(), log);
}
APIDefinitionValidationResponse validationAPIResponse = null;
if (ServiceEntry.DefinitionType.WSDL1.equals(service.getDefinitionType())) {
PublisherCommonUtils.addWsdl(RestApiConstants.APPLICATION_OCTET_STREAM, service.getEndpointDef(), api, apiProvider, organization);
} else {
validationAPIResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
if (!validationAPIResponse.isValid()) {
RestApiUtil.handleBadRequest(validationAPIResponse.getErrorItems(), log);
}
}
String protocol = (validationAPIResponse != null ? validationAPIResponse.getProtocol() : "");
if (!APIConstants.API_TYPE_WEBSUB.equalsIgnoreCase(protocol)) {
api.setEndpointConfig(PublisherCommonUtils.constructEndpointConfigForService(service.getServiceUrl(), protocol));
}
API updatedApi = apiProvider.updateAPI(api, originalAPI);
if (validationAPIResponse != null) {
PublisherCommonUtils.updateAPIDefinition(apiId, validationAPIResponse, service, organization);
}
return Response.ok().entity(APIMappingUtil.fromAPItoDTO(updatedApi)).build();
} catch (APIManagementException e) {
if (ExceptionCodes.MISSING_PROTOCOL_IN_ASYNC_API_DEFINITION.getErrorCode() == e.getErrorHandler().getErrorCode()) {
RestApiUtil.handleBadRequest("Missing protocol in the Service Definition", log);
} else if (ExceptionCodes.UNSUPPORTED_PROTOCOL_SPECIFIED_IN_ASYNC_API_DEFINITION.getErrorCode() == e.getErrorHandler().getErrorCode()) {
RestApiUtil.handleBadRequest("Unsupported protocol specified in the Service Definition. Protocol " + "should be either sse or websub or ws", log);
}
RestApiUtil.handleInternalServerError("Error while retrieving the service key of the service " + "associated with API with id " + apiId, log);
} catch (FaultGatewaysException e) {
String errorMessage = "Error while updating API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
Aggregations