Search in sources :

Example 36 with APIDefinition

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();
}
Also used : APIResourceMediationPolicy(org.wso2.carbon.apimgt.api.model.APIResourceMediationPolicy) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONObject(org.json.simple.JSONObject) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 37 with APIDefinition

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;
}
Also used : InputStreamReader(java.io.InputStreamReader) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) JSONParser(org.json.simple.parser.JSONParser) PrintWriter(java.io.PrintWriter)

Example 38 with APIDefinition

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;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 39 with APIDefinition

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.");
                    }
                }
            }
        }
    }
}
Also used : URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) JsonElement(com.google.gson.JsonElement) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) API(org.wso2.carbon.apimgt.api.model.API) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) File(java.io.File)

Example 40 with APIDefinition

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;
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) ArrayList(java.util.ArrayList) IOException(java.io.IOException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 HashMap (java.util.HashMap)30 APIDefinition (org.wso2.carbon.apimgt.api.APIDefinition)30 API (org.wso2.carbon.apimgt.core.models.API)30 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)25 ArrayList (java.util.ArrayList)23 API (org.wso2.carbon.apimgt.api.model.API)20 Map (java.util.Map)19 IOException (java.io.IOException)18 Test (org.testng.annotations.Test)18 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)18 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)16 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)15 Scope (org.wso2.carbon.apimgt.api.model.Scope)15 HashSet (java.util.HashSet)13 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)13 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)12 SwaggerData (org.wso2.carbon.apimgt.api.model.SwaggerData)12 BusinessInformation (org.wso2.carbon.apimgt.core.models.BusinessInformation)12 CorsConfiguration (org.wso2.carbon.apimgt.core.models.CorsConfiguration)12