use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method getGeneratedMockScriptsOfAPI.
/**
* Gets generated scripts
*
* @param apiId API Id
* @param ifNoneMatch If-None-Match header value
* @param messageContext message context
* @return list of policies of generated sample payload
* @throws APIManagementException
*/
@Override
public Response getGeneratedMockScriptsOfAPI(String apiId, String ifNoneMatch, MessageContext messageContext) throws APIManagementException {
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
API originalAPI = apiProvider.getAPIbyUUID(apiId, organization);
APIIdentifier apiIdentifier = originalAPI.getId();
String apiDefinition = apiProvider.getOpenAPIDefinition(apiIdentifier, organization);
Map<String, Object> examples = OASParserUtil.generateExamples(apiDefinition);
List<APIResourceMediationPolicy> policies = (List<APIResourceMediationPolicy>) examples.get(APIConstants.MOCK_GEN_POLICY_LIST);
return Response.ok().entity(APIMappingUtil.fromMockPayloadsToListDTO(policies)).build();
}
use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method createAuditApi.
/**
* Send API Definition to Security Audit for the first time
* @param collectionId Collection ID in which the Definition should be sent to
* @param apiToken API Token to access Security Audit
* @param apiIdentifier API Identifier object
* @param apiDefinition API Definition of API
* @param baseUrl Base URL to communicate with Security Audit
* @param isDebugEnabled Boolean whether debug is enabled
* @param organization Organization
* @return String UUID of API in Security Audit
* @throws IOException In the event of any problems in the request
* @throws APIManagementException In the event of unexpected response
* @throws ParseException In the event of any parse errors from the response
*/
private String createAuditApi(String collectionId, String apiToken, APIIdentifier apiIdentifier, String apiDefinition, String baseUrl, boolean isDebugEnabled, String organization) throws IOException, APIManagementException, ParseException {
HttpURLConnection httpConn;
OutputStream outputStream;
PrintWriter writer;
String auditUuid = null;
URL url = new URL(baseUrl);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
// indicates POST method
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestProperty(APIConstants.HEADER_CONTENT_TYPE, APIConstants.MULTIPART_CONTENT_TYPE + APIConstants.MULTIPART_FORM_BOUNDARY);
httpConn.setRequestProperty(APIConstants.HEADER_ACCEPT, APIConstants.APPLICATION_JSON_MEDIA_TYPE);
httpConn.setRequestProperty(APIConstants.HEADER_API_TOKEN, apiToken);
httpConn.setRequestProperty(APIConstants.HEADER_USER_AGENT, APIConstants.USER_AGENT_APIM);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true);
// Name property
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"name\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(apiIdentifier.getApiName()).append(APIConstants.MULTIPART_LINE_FEED);
writer.flush();
// Specfile property
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"specfile\"; filename=\"swagger.json\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.HEADER_CONTENT_TYPE + ": " + APIConstants.APPLICATION_JSON_MEDIA_TYPE).append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(apiDefinition).append(APIConstants.MULTIPART_LINE_FEED);
writer.flush();
// CollectionID property
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY).append(APIConstants.MULTIPART_LINE_FEED).append("Content-Disposition: form-data; name=\"cid\"").append(APIConstants.MULTIPART_LINE_FEED).append(APIConstants.MULTIPART_LINE_FEED).append(collectionId).append(APIConstants.MULTIPART_LINE_FEED);
writer.flush();
writer.append("--" + APIConstants.MULTIPART_FORM_BOUNDARY + "--").append(APIConstants.MULTIPART_LINE_FEED);
writer.close();
// Checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
if (isDebugEnabled) {
log.debug("HTTP status " + status);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8));
String inputLine;
StringBuilder responseString = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
responseString.append(inputLine);
}
reader.close();
httpConn.disconnect();
JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
auditUuid = (String) ((JSONObject) responseJson.get(APIConstants.DESC)).get(APIConstants.ID);
ApiMgtDAO.getInstance().addAuditApiMapping(apiIdentifier, auditUuid, organization);
} else {
if (httpConn.getErrorStream() != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getErrorStream(), StandardCharsets.UTF_8));
String inputLine;
StringBuilder responseString = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
responseString.append(inputLine);
}
reader.close();
httpConn.disconnect();
JSONObject responseJson = (JSONObject) new JSONParser().parse(responseString.toString());
String errorMessage = httpConn.getResponseMessage();
if (responseJson.containsKey("message")) {
errorMessage = (String) responseJson.get("message");
}
throw new APIManagementException("Error while retrieving data for the API Security Audit Report. Found http status: " + httpConn.getResponseCode() + " - " + errorMessage);
} else {
throw new APIManagementException("Error while retrieving data for the API Security Audit Report. Found http status: " + httpConn.getResponseCode() + " - " + httpConn.getResponseMessage());
}
}
return auditUuid;
}
use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method apisApiIdAsyncapiPut.
@Override
public Response apisApiIdAsyncapiPut(String apiId, String ifMatch, String apiDefinition, String url, InputStream fileInputStream, Attachment fileDetail, MessageContext messageContext) throws APIManagementException {
try {
String updatedAsyncAPIDefinition;
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());
// Handle URL and file based definition imports
if (url != null || fileInputStream != null) {
// Validate and retrieve the AsyncAPI definition
Map validationResponseMap = validateAsyncAPISpecification(url, fileInputStream, fileDetail, true, false);
APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
if (!validationResponse.isValid()) {
RestApiUtil.handleBadRequest(validationResponse.getErrorItems(), log);
}
updatedAsyncAPIDefinition = PublisherCommonUtils.updateAsyncAPIDefinition(apiId, validationResponse, organization);
} else {
updatedAsyncAPIDefinition = updateAsyncAPIDefinition(apiId, apiDefinition, organization);
}
return Response.ok().entity(updatedAsyncAPIDefinition).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 AsyncAPI definition of API: " + apiId, e, log);
} else {
String errorMessage = "Error while updating the AsyncAPI 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 ImportUtils method checkAPIProductResourcesValid.
/**
* This method checks whether the resources in the API Product are valid.
*
* @param path Location of the extracted folder of the API Product
* @param currentUser The current logged in user
* @param apiProvider API provider
* @param apiProductDto API Product DTO
* @param preserveProvider
* @param organization
* @throws IOException If there is an error while reading an API file
* @throws APIManagementException If failed to get the API Provider of an API,
* or failed when checking the existence of an API
*/
private static void checkAPIProductResourcesValid(String path, String currentUser, APIProvider apiProvider, APIProductDTO apiProductDto, Boolean preserveProvider, String organization) throws IOException, APIManagementException {
// Get dependent APIs in the API Product
List<ProductAPIDTO> apis = apiProductDto.getApis();
String apisDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY;
File apisDirectory = new File(apisDirectoryPath);
File[] apisDirectoryListing = apisDirectory.listFiles();
if (apisDirectoryListing != null) {
for (File apiDirectory : apisDirectoryListing) {
String apiDirectoryPath = path + File.separator + ImportExportConstants.APIS_DIRECTORY + File.separator + apiDirectory.getName();
JsonElement jsonObject = retrieveValidatedDTOObject(apiDirectoryPath, preserveProvider, currentUser, ImportExportConstants.TYPE_API);
APIDTO apiDto = new Gson().fromJson(jsonObject, APIDTO.class);
String apiName = apiDto.getName();
String apiVersion = apiDto.getVersion();
String swaggerContent = loadSwaggerFile(apiDirectoryPath);
APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent);
Set<URITemplate> apiUriTemplates = apiDefinition.getURITemplates(swaggerContent);
for (ProductAPIDTO apiFromProduct : apis) {
if (StringUtils.equals(apiFromProduct.getName(), apiName) && StringUtils.equals(apiFromProduct.getVersion(), apiVersion)) {
List<APIOperationsDTO> invalidApiOperations = filterInvalidProductResources(apiFromProduct.getOperations(), apiUriTemplates);
// dependent APIs inside the directory) check whether those are already inside APIM
if (!invalidApiOperations.isEmpty()) {
// Get the provider of the API if the API is in current user's tenant domain.
API api = retrieveApiToOverwrite(apiName, apiVersion, MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(currentUser)), apiProvider, Boolean.FALSE, organization);
invalidApiOperations = filterInvalidProductResources(invalidApiOperations, api.getUriTemplates());
}
// inside the APIM
if (!invalidApiOperations.isEmpty()) {
throw new APIMgtResourceNotFoundException("Cannot find API resources for some API Product resources.");
}
}
}
}
}
}
use of org.wso2.carbon.apimgt.api.doc.model.APIDefinition in project carbon-apimgt by wso2.
the class SettingsApiServiceImpl method GetScopeList.
/**
* This method returns the scope list from the publisher-api.yaml
* @return List<String> scope list
* @throws APIManagementException
*/
private List<String> GetScopeList() throws APIManagementException {
String definition = null;
try {
definition = IOUtils.toString(RestApiUtil.class.getResourceAsStream("/publisher-api.yaml"), "UTF-8");
} catch (IOException e) {
log.error("Error while reading the swagger definition", e);
}
APIDefinition parser = OASParserUtil.getOASParser(definition);
Set<Scope> scopeSet = parser.getScopes(definition);
List<String> scopeList = new ArrayList<>();
for (Scope entry : scopeSet) {
scopeList.add(entry.getKey());
}
return scopeList;
}
Aggregations