Search in sources :

Example 61 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class PublisherCommonUtils method addAPIWithGeneratedSwaggerDefinition.

/**
 * Add API with the generated swagger from the DTO.
 *
 * @param apiDto     API DTO of the API
 * @param oasVersion Open API Definition version
 * @param username   Username
 * @param organization  Organization Identifier
 * @return Created API object
 * @throws APIManagementException Error while creating the API
 * @throws CryptoException        Error while encrypting
 */
public static API addAPIWithGeneratedSwaggerDefinition(APIDTO apiDto, String oasVersion, String username, String organization) throws APIManagementException, CryptoException {
    if (APIUtil.isOnPremResolver()) {
        String name = apiDto.getName();
        // replace all white spaces in the API Name
        apiDto.setName(name.replaceAll("\\s+", ""));
    }
    if (APIDTO.TypeEnum.ASYNC.equals(apiDto.getType())) {
        throw new APIManagementException("ASYNC API type does not support API creation from scratch", ExceptionCodes.API_CREATION_NOT_SUPPORTED_FOR_ASYNC_TYPE_APIS);
    }
    boolean isWSAPI = APIDTO.TypeEnum.WS.equals(apiDto.getType());
    boolean isAsyncAPI = isWSAPI || APIDTO.TypeEnum.WEBSUB.equals(apiDto.getType()) || APIDTO.TypeEnum.SSE.equals(apiDto.getType()) || APIDTO.TypeEnum.ASYNC.equals(apiDto.getType());
    username = StringUtils.isEmpty(username) ? RestApiCommonUtil.getLoggedInUsername() : username;
    APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
    // validate web socket api endpoint configurations
    if (isWSAPI && !PublisherCommonUtils.isValidWSAPI(apiDto)) {
        throw new APIManagementException("Endpoint URLs should be valid web socket URLs", ExceptionCodes.INVALID_ENDPOINT_URL);
    }
    // validate sandbox and production endpoints
    if (!PublisherCommonUtils.validateEndpoints(apiDto)) {
        throw new APIManagementException("Invalid/Malformed endpoint URL(s) detected", ExceptionCodes.INVALID_ENDPOINT_URL);
    }
    Map endpointConfig = (Map) apiDto.getEndpointConfig();
    CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
    // OAuth 2.0 backend protection: API Key and API Secret encryption
    encryptEndpointSecurityOAuthCredentials(endpointConfig, cryptoUtil, StringUtils.EMPTY, StringUtils.EMPTY, apiDto);
    // AWS Lambda: secret key encryption while creating the API
    if (apiDto.getEndpointConfig() != null) {
        if (endpointConfig.containsKey(APIConstants.AMZN_SECRET_KEY)) {
            String secretKey = (String) endpointConfig.get(APIConstants.AMZN_SECRET_KEY);
            if (!StringUtils.isEmpty(secretKey)) {
                String encryptedSecretKey = cryptoUtil.encryptAndBase64Encode(secretKey.getBytes());
                endpointConfig.put(APIConstants.AMZN_SECRET_KEY, encryptedSecretKey);
                apiDto.setEndpointConfig(endpointConfig);
            }
        }
    }
    /* if (isWSAPI) {
            ArrayList<String> websocketTransports = new ArrayList<>();
            websocketTransports.add(APIConstants.WS_PROTOCOL);
            websocketTransports.add(APIConstants.WSS_PROTOCOL);
            apiDto.setTransport(websocketTransports);
        }*/
    API apiToAdd = prepareToCreateAPIByDTO(apiDto, apiProvider, username, organization);
    validateScopes(apiToAdd);
    // validate API categories
    List<APICategory> apiCategories = apiToAdd.getApiCategories();
    List<APICategory> apiCategoriesList = new ArrayList<>();
    for (APICategory category : apiCategories) {
        category.setOrganization(organization);
        apiCategoriesList.add(category);
    }
    apiToAdd.setApiCategories(apiCategoriesList);
    if (apiCategoriesList.size() > 0) {
        if (!APIUtil.validateAPICategories(apiCategoriesList, organization)) {
            throw new APIManagementException("Invalid API Category name(s) defined", ExceptionCodes.from(ExceptionCodes.API_CATEGORY_INVALID));
        }
    }
    if (!isAsyncAPI) {
        APIDefinition oasParser;
        if (RestApiConstants.OAS_VERSION_2.equalsIgnoreCase(oasVersion)) {
            oasParser = new OAS2Parser();
        } else {
            oasParser = new OAS3Parser();
        }
        SwaggerData swaggerData = new SwaggerData(apiToAdd);
        String apiDefinition = oasParser.generateAPIDefinition(swaggerData);
        apiToAdd.setSwaggerDefinition(apiDefinition);
    } else {
        AsyncApiParser asyncApiParser = new AsyncApiParser();
        String asyncApiDefinition = asyncApiParser.generateAsyncAPIDefinition(apiToAdd);
        apiToAdd.setAsyncApiDefinition(asyncApiDefinition);
    }
    apiToAdd.setOrganization(organization);
    if (isAsyncAPI) {
        AsyncApiParser asyncApiParser = new AsyncApiParser();
        String apiDefinition = asyncApiParser.generateAsyncAPIDefinition(apiToAdd);
        apiToAdd.setAsyncApiDefinition(apiDefinition);
    }
    // adding the api
    apiProvider.addAPI(apiToAdd);
    return apiToAdd;
}
Also used : OAS2Parser(org.wso2.carbon.apimgt.impl.definitions.OAS2Parser) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) ArrayList(java.util.ArrayList) OAS3Parser(org.wso2.carbon.apimgt.impl.definitions.OAS3Parser) AsyncApiParser(org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) CryptoUtil(org.wso2.carbon.core.util.CryptoUtil) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) API(org.wso2.carbon.apimgt.api.model.API) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 62 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class SecurityConfigContext method getContext.

public VelocityContext getContext() {
    VelocityContext context = super.getContext();
    boolean isSecureVaultEnabled = Boolean.parseBoolean(getApiManagerConfiguration().getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE));
    if (api != null) {
        Map<String, EndpointSecurityModel> endpointSecurityModelMap = new HashMap<>();
        endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_PRODUCTION, new EndpointSecurityModel());
        endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_SANDBOX, new EndpointSecurityModel());
        if (StringUtils.isNotEmpty(api.getEndpointConfig())) {
            if (productionEndpointSecurity != null) {
                EndpointSecurityModel endpointSecurityModel = new ObjectMapper().convertValue(productionEndpointSecurity, EndpointSecurityModel.class);
                endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, api.getId().getApiName(), api.getId().getVersion(), api.getUuid(), APIConstants.ENDPOINT_SECURITY_PRODUCTION, null);
                if (endpointSecurityModel != null) {
                    endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_PRODUCTION, endpointSecurityModel);
                }
            }
            if (sandboxEndpointSecurity != null) {
                EndpointSecurityModel endpointSecurityModel = new ObjectMapper().convertValue(sandboxEndpointSecurity, EndpointSecurityModel.class);
                endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, api.getId().getApiName(), api.getId().getVersion(), api.getUuid(), APIConstants.ENDPOINT_SECURITY_SANDBOX, null);
                if (endpointSecurityModel != null) {
                    endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_SANDBOX, endpointSecurityModel);
                }
            }
        }
        context.put("endpoint_security", endpointSecurityModelMap);
    } else if (apiProduct != null) {
        Map<String, Map<String, EndpointSecurityModel>> endpointSecurityModelMap = new HashMap<>();
        for (APIProductResource apiProductResource : apiProduct.getProductResources()) {
            APIDTO apidto = associatedAPIMap.get(apiProductResource.getApiId());
            String alias = apiProduct.getId().getName() + "--v" + apiProduct.getId().getVersion();
            Map<String, EndpointSecurityModel> stringEndpointSecurityModelMap = new HashMap<>();
            Map<String, EndpointSecurity> endpointSecurityMap = apiProductResource.getEndpointSecurityMap();
            for (Map.Entry<String, EndpointSecurity> endpointSecurityEntry : endpointSecurityMap.entrySet()) {
                EndpointSecurityModel endpointSecurityModel = new EndpointSecurityModel(endpointSecurityEntry.getValue());
                endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, apidto.getName(), apidto.getVersion(), apidto.getId(), endpointSecurityEntry.getKey(), alias);
                stringEndpointSecurityModelMap.put(endpointSecurityEntry.getKey(), endpointSecurityModel);
            }
            endpointSecurityModelMap.put(apiProductResource.getApiId(), stringEndpointSecurityModelMap);
        }
        context.put("endpoint_security", endpointSecurityModelMap);
    }
    context.put("isSecureVaultEnabled", isSecureVaultEnabled);
    return context;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) HashMap(java.util.HashMap) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) VelocityContext(org.apache.velocity.VelocityContext) HashMap(java.util.HashMap) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 63 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class AdditionalSubscriptionInfoMappingUtil method setEndpointURLsForApiDto.

/**
 * Sets the Endpoint URLs for the APIDTO object using solace protocols
 *
 * @param api          API object
 * @param tenantDomain Tenant Domain
 * @return List containing AdditionalSubscriptionInfoSolaceEndpointURLsDTOs
 * @throws APIManagementException if error occurred when retrieving protocols URLs
 */
public static List<String> setEndpointURLsForApiDto(API api, String tenantDomain) throws APIManagementException {
    List<AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO> urlsList = setSolaceEnvironmentDetailsForSubscription(api, tenantDomain);
    List<String> urlsStringList = new ArrayList<>();
    if (!urlsList.isEmpty()) {
        for (AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO item : urlsList) {
            List<AdditionalSubscriptionInfoSolaceURLsDTO> protocols = item.getSolaceURLs();
            for (AdditionalSubscriptionInfoSolaceURLsDTO protocol : protocols) {
                // Create Json string to return
                JSONObject asyncProtocolsObj = new JSONObject();
                asyncProtocolsObj.put("protocol", protocol.getProtocol());
                asyncProtocolsObj.put("endPointUrl", protocol.getEndpointURL());
                urlsStringList.add(asyncProtocolsObj.toString());
            }
        }
    }
    return urlsStringList;
}
Also used : AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO) JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) AdditionalSubscriptionInfoSolaceURLsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdditionalSubscriptionInfoSolaceURLsDTO)

Example 64 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.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);
}
Also used : SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.api.model.Scope) OpenAPIDefinitionValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OpenAPIDefinitionValidationResponseDTO) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Example 65 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.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;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) ArrayList(java.util.ArrayList) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Aggregations

APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)29 HashMap (java.util.HashMap)28 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)27 ArrayList (java.util.ArrayList)25 API (org.wso2.carbon.apimgt.api.model.API)25 IOException (java.io.IOException)18 API (org.wso2.carbon.apimgt.core.models.API)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)15 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO)15 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)14 File (java.io.File)12 Response (javax.ws.rs.core.Response)12 Map (java.util.Map)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)11 Test (org.junit.Test)10 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)10 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)10 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)10 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)10