use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition 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;
}
use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method generateMockScripts.
/**
* Generates Mock response examples for Inline prototyping
* of a swagger
*
* @param apiId API Id
* @param ifNoneMatch If-None-Match header value
* @param messageContext message context
* @return apiDefinition
* @throws APIManagementException
*/
@Override
public Response generateMockScripts(String apiId, String ifNoneMatch, MessageContext messageContext) throws APIManagementException {
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));
}
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
API originalAPI = apiProvider.getAPIbyUUID(apiId, organization);
String apiDefinition = apiProvider.getOpenAPIDefinition(apiId, organization);
apiDefinition = String.valueOf(OASParserUtil.generateExamples(apiDefinition).get(APIConstants.SWAGGER));
apiProvider.saveSwaggerDefinition(originalAPI, apiDefinition, organization);
return Response.ok().entity(apiDefinition).build();
}
use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method updateAPISwagger.
/**
* Updates the swagger definition of an existing API
*
* @param apiId API identifier
* @param apiDefinition Swagger definition
* @param url Swagger definition URL
* @param fileInputStream Swagger definition input file content
* @param fileDetail file meta information as Attachment
* @param ifMatch If-match header value
* @return updated swagger document of the API
*/
@Override
public Response updateAPISwagger(String apiId, String ifMatch, String apiDefinition, String url, InputStream fileInputStream, Attachment fileDetail, MessageContext messageContext) {
try {
String updatedSwagger;
// validate if api exists
APIInfo apiInfo = validateAPIExistence(apiId);
// validate API update operation permitted based on the LC state
validateAPIOperationsPerLC(apiInfo.getStatus().getStatus());
String organization = RestApiUtil.getValidatedOrganization(messageContext);
// Handle URL and file based definition imports
if (url != null || fileInputStream != null) {
// Validate and retrieve the OpenAPI definition
Map validationResponseMap = validateOpenAPIDefinition(url, fileInputStream, fileDetail, null, true, false);
APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
if (!validationResponse.isValid()) {
RestApiUtil.handleBadRequest(validationResponse.getErrorItems(), log);
}
updatedSwagger = PublisherCommonUtils.updateSwagger(apiId, validationResponse, false, organization);
} else {
updatedSwagger = updateSwagger(apiId, apiDefinition, organization);
}
return Response.ok().entity(updatedSwagger).build();
} catch (APIManagementException e) {
// to expose the existence of the resource
if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
} else if (isAuthorizationFailure(e)) {
RestApiUtil.handleAuthorizationFailure("Authorization failure while updating swagger definition of API: " + apiId, e, log);
} else {
String errorMessage = "Error while updating the swagger definition of the API: " + apiId + " - " + e.getMessage();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
} catch (FaultGatewaysException e) {
String errorMessage = "Error while updating API : " + apiId;
RestApiUtil.handleInternalServerError(errorMessage, e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method importSOAPAPI.
/**
* Import an API from WSDL as a SOAP API
*
* @param fileInputStream file data as input stream
* @param fileDetail file details
* @param url URL of the WSDL
* @param apiToAdd API object to be added to the system (which is not added yet)
* @param organization Organization
* @param service service
* @return API added api
*/
private API importSOAPAPI(InputStream fileInputStream, Attachment fileDetail, String url, API apiToAdd, String organization, ServiceEntry service) {
try {
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
// adding the api
apiProvider.addAPI(apiToAdd);
if (StringUtils.isNotBlank(url)) {
apiToAdd.setWsdlUrl(url);
apiProvider.addWSDLResource(apiToAdd.getUuid(), null, url, organization);
} else if (fileDetail != null && fileInputStream != null) {
PublisherCommonUtils.addWsdl(fileDetail.getContentType().toString(), fileInputStream, apiToAdd, apiProvider, organization);
} else if (service != null && fileInputStream == null) {
RestApiUtil.handleBadRequest("Error while importing WSDL to create a SOAP API", log);
} else if (service != null) {
PublisherCommonUtils.addWsdl(RestApiConstants.APPLICATION_OCTET_STREAM, fileInputStream, apiToAdd, apiProvider, organization);
}
// add the generated swagger definition to SOAP
APIDefinition oasParser = new OAS2Parser();
SwaggerData swaggerData = new SwaggerData(apiToAdd);
String apiDefinition = generateSOAPAPIDefinition(oasParser.generateAPIDefinition(swaggerData));
apiProvider.saveSwaggerDefinition(apiToAdd, apiDefinition, organization);
APIIdentifier createdApiId = apiToAdd.getId();
// Retrieve the newly added API to send in the response payload
API createdApi = apiProvider.getAPIbyUUID(apiToAdd.getUuid(), organization);
return createdApi;
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Error while importing WSDL to create a SOAP API", e, log);
}
return null;
}
use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method updateAuditApi.
/**
* Update API Definition before retrieving Security Audit Report
* @param apiDefinition API Definition of API
* @param apiToken API Token to access Security Audit
* @param auditUuid Respective UUID of API in Security Audit
* @param baseUrl Base URL to communicate with Security Audit
* @param isDebugEnabled Boolean whether debug is enabled
* @throws IOException In the event of any problems with the request
* @throws APIManagementException In the event of unexpected response
*/
private void updateAuditApi(String apiDefinition, String apiToken, String auditUuid, String baseUrl, boolean isDebugEnabled) throws IOException, APIManagementException {
// Set the property to be attached in the body of the request
// Attach API Definition to property called specfile to be sent in the request
JSONObject jsonBody = new JSONObject();
jsonBody.put("specfile", Base64Utils.encode(apiDefinition.getBytes(StandardCharsets.UTF_8)));
// Logic for HTTP Request
String putUrl = baseUrl + "/" + auditUuid;
URL updateApiUrl = new URL(putUrl);
try (CloseableHttpClient httpClient = (CloseableHttpClient) APIUtil.getHttpClient(updateApiUrl.getPort(), updateApiUrl.getProtocol())) {
HttpPut httpPut = new HttpPut(putUrl);
// Set the header properties of the request
httpPut.setHeader(APIConstants.HEADER_ACCEPT, APIConstants.APPLICATION_JSON_MEDIA_TYPE);
httpPut.setHeader(APIConstants.HEADER_CONTENT_TYPE, APIConstants.APPLICATION_JSON_MEDIA_TYPE);
httpPut.setHeader(APIConstants.HEADER_API_TOKEN, apiToken);
httpPut.setHeader(APIConstants.HEADER_USER_AGENT, APIConstants.USER_AGENT_APIM);
httpPut.setEntity(new StringEntity(jsonBody.toJSONString()));
// Code block for processing the response
try (CloseableHttpResponse response = httpClient.execute(httpPut)) {
if (isDebugEnabled) {
log.debug("HTTP status " + response.getStatusLine().getStatusCode());
}
if (!(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)) {
throw new APIManagementException("Error while sending data to the API Security Audit Feature. Found http status " + response.getStatusLine());
}
} finally {
httpPut.releaseConnection();
}
}
}
Aggregations