use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO 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.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getAPISubscriptionPolicies.
@Override
public Response getAPISubscriptionPolicies(String apiId, String ifNoneMatch, String xWSO2Tenant, MessageContext messageContext) throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIDTO apiInfo = getAPIByID(apiId, apiProvider, organization);
List<Tier> availableThrottlingPolicyList = new ThrottlingPoliciesApiServiceImpl().getThrottlingPolicyList(ThrottlingPolicyDTO.PolicyLevelEnum.SUBSCRIPTION.toString(), true);
if (apiInfo != null) {
List<String> apiPolicies = apiInfo.getPolicies();
if (apiPolicies != null && !apiPolicies.isEmpty()) {
List<Tier> apiThrottlingPolicies = new ArrayList<>();
for (Tier tier : availableThrottlingPolicyList) {
if (apiPolicies.contains(tier.getName())) {
apiThrottlingPolicies.add(tier);
}
}
return Response.ok().entity(apiThrottlingPolicies).build();
}
}
return null;
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method restoreAPIRevision.
/**
* Restore a revision to the working copy of the API
*
* @param apiId UUID of the API
* @param revisionId Revision ID of the API
* @param messageContext message context object
* @return response with 200 status code
*/
@Override
public Response restoreAPIRevision(String apiId, String revisionId, MessageContext messageContext) throws APIManagementException {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
String organization = RestApiUtil.getValidatedOrganization(messageContext);
// validate if api exists
APIInfo apiInfo = validateAPIExistence(apiId);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(apiInfo.getStatus().toString());
apiProvider.restoreAPIRevision(apiId, revisionId, organization);
APIDTO apiToReturn = getAPIByID(apiId, apiProvider, organization);
Response.Status status = Response.Status.CREATED;
return Response.status(status).entity(apiToReturn).build();
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method importOpenAPIDefinition.
/**
* Importing an OpenAPI definition and create an API
*
* @param fileInputStream InputStream for the provided file
* @param fileDetail File meta-data
* @param url URL of the OpenAPI definition
* @param additionalProperties API object (json) including additional properties like name, version, context
* @param inlineApiDefinition Swagger API definition String
* @param messageContext CXF message context
* @return API Import using OpenAPI definition response
* @throws APIManagementException when error occurs while importing the OpenAPI definition
*/
@Override
public Response importOpenAPIDefinition(InputStream fileInputStream, Attachment fileDetail, String url, String additionalProperties, String inlineApiDefinition, MessageContext messageContext) throws APIManagementException {
// validate 'additionalProperties' json
if (StringUtils.isBlank(additionalProperties)) {
RestApiUtil.handleBadRequest("'additionalProperties' is required and should not be null", log);
}
// Convert the 'additionalProperties' json into an APIDTO object
ObjectMapper objectMapper = new ObjectMapper();
APIDTO apiDTOFromProperties;
try {
apiDTOFromProperties = objectMapper.readValue(additionalProperties, APIDTO.class);
} catch (IOException e) {
throw RestApiUtil.buildBadRequestException("Error while parsing 'additionalProperties'", e);
}
// validate sandbox and production endpoints
if (!PublisherCommonUtils.validateEndpoints(apiDTOFromProperties)) {
throw new APIManagementException("Invalid/Malformed endpoint URL(s) detected", ExceptionCodes.INVALID_ENDPOINT_URL);
}
try {
LinkedHashMap endpointConfig = (LinkedHashMap) apiDTOFromProperties.getEndpointConfig();
// OAuth 2.0 backend protection: API Key and API Secret encryption
PublisherCommonUtils.encryptEndpointSecurityOAuthCredentials(endpointConfig, CryptoUtil.getDefaultCryptoUtil(), StringUtils.EMPTY, StringUtils.EMPTY, apiDTOFromProperties);
// Import the API and Definition
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIDTO createdApiDTO = importOpenAPIDefinition(fileInputStream, url, inlineApiDefinition, apiDTOFromProperties, fileDetail, null, organization);
if (createdApiDTO != null) {
// This URI used to set the location header of the POST response
URI createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdApiDTO.getId());
return Response.created(createdApiUri).entity(createdApiDTO).build();
}
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving API location : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (CryptoException e) {
String errorMessage = "Error while encrypting the secret key of API : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion();
throw new APIManagementException(errorMessage, e);
}
return null;
}
use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method importGraphQLSchema.
/**
* Import a GraphQL Schema
* @param type APIType
* @param fileInputStream input file
* @param fileDetail file Detail
* @param additionalProperties api object as string format
* @param ifMatch If--Match header value
* @param messageContext messageContext
* @return Response with GraphQL API
*/
@Override
public Response importGraphQLSchema(String ifMatch, String type, InputStream fileInputStream, Attachment fileDetail, String additionalProperties, MessageContext messageContext) {
APIDTO additionalPropertiesAPI = null;
String schema = "";
try {
if (fileInputStream == null || StringUtils.isBlank(additionalProperties)) {
String errorMessage = "GraphQL schema and api details cannot be empty.";
RestApiUtil.handleBadRequest(errorMessage, log);
} else {
schema = IOUtils.toString(fileInputStream, RestApiConstants.CHARSET);
}
if (!StringUtils.isBlank(additionalProperties) && !StringUtils.isBlank(schema)) {
if (log.isDebugEnabled()) {
log.debug("Deseriallizing additionalProperties: " + additionalProperties + "/n" + "importing schema: " + schema);
}
}
additionalPropertiesAPI = new ObjectMapper().readValue(additionalProperties, APIDTO.class);
additionalPropertiesAPI.setType(APIDTO.TypeEnum.GRAPHQL);
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
API apiToAdd = PublisherCommonUtils.prepareToCreateAPIByDTO(additionalPropertiesAPI, apiProvider, RestApiCommonUtil.getLoggedInUsername(), organization);
// Save swagger definition of graphQL
APIDefinition parser = new OAS3Parser();
SwaggerData swaggerData = new SwaggerData(apiToAdd);
String apiDefinition = parser.generateAPIDefinition(swaggerData);
apiToAdd.setSwaggerDefinition(apiDefinition);
// adding the api
API createdApi = apiProvider.addAPI(apiToAdd);
apiProvider.saveGraphqlSchemaDefinition(createdApi.getUuid(), schema, organization);
APIDTO createdApiDTO = APIMappingUtil.fromAPItoDTO(createdApi);
// This URI used to set the location header of the POST response
URI createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdApiDTO.getId());
return Response.created(createdApiUri).entity(createdApiDTO).build();
} catch (APIManagementException e) {
String errorMessage = "Error while adding new API : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion() + " - " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving API location : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (IOException e) {
String errorMessage = "Error while retrieving content from file : " + additionalPropertiesAPI.getProvider() + "-" + additionalPropertiesAPI.getName() + "-" + additionalPropertiesAPI.getVersion();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
Aggregations