Search in sources :

Example 6 with CORSConfiguration

use of org.wso2.carbon.apimgt.api.model.CORSConfiguration in project carbon-apimgt by wso2.

the class MappingUtil method toAPI.

/**
 * This method converts the API model object from the DTO object.
 *
 * @param apidto APIDTO object with API data
 * @return APIBuilder object
 */
public static API.APIBuilder toAPI(APIDTO apidto) throws JsonProcessingException {
    BusinessInformation businessInformation = new BusinessInformation();
    API_businessInformationDTO apiBusinessInformationDTO = apidto.getBusinessInformation();
    if (apiBusinessInformationDTO != null) {
        businessInformation.setBusinessOwner(apiBusinessInformationDTO.getBusinessOwner());
        businessInformation.setBusinessOwnerEmail(apiBusinessInformationDTO.getBusinessOwnerEmail());
        businessInformation.setTechnicalOwner(apiBusinessInformationDTO.getTechnicalOwner());
        businessInformation.setTechnicalOwnerEmail(apiBusinessInformationDTO.getTechnicalOwnerEmail());
    }
    API_corsConfigurationDTO apiCorsConfigurationDTO = apidto.getCorsConfiguration();
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    if (apiCorsConfigurationDTO != null) {
        corsConfiguration.setAllowCredentials(apiCorsConfigurationDTO.getAccessControlAllowCredentials());
        corsConfiguration.setAllowHeaders(apiCorsConfigurationDTO.getAccessControlAllowHeaders());
        corsConfiguration.setAllowMethods(apiCorsConfigurationDTO.getAccessControlAllowMethods());
        corsConfiguration.setAllowOrigins(apiCorsConfigurationDTO.getAccessControlAllowOrigins());
        corsConfiguration.setEnabled(apiCorsConfigurationDTO.getCorsConfigurationEnabled());
    }
    List<API_operationsDTO> operationList = apidto.getOperations();
    Map<String, UriTemplate> uriTemplateList = new HashMap<>();
    for (API_operationsDTO operationsDTO : operationList) {
        UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder();
        uriTemplateBuilder.uriTemplate(operationsDTO.getUritemplate());
        uriTemplateBuilder.authType(operationsDTO.getAuthType());
        uriTemplateBuilder.httpVerb(operationsDTO.getHttpVerb());
        uriTemplateBuilder.policy(new APIPolicy(operationsDTO.getPolicy()));
        uriTemplateBuilder.scopes(operationsDTO.getScopes());
        if (operationsDTO.getEndpoint() != null && !operationsDTO.getEndpoint().isEmpty()) {
            uriTemplateBuilder.endpoint(fromEndpointListToMap(operationsDTO.getEndpoint()));
        }
        if (operationsDTO.getId() != null) {
            uriTemplateBuilder.templateId(operationsDTO.getId());
        } else {
            uriTemplateBuilder.templateId(APIUtils.generateOperationIdFromPath(operationsDTO.getUritemplate(), operationsDTO.getHttpVerb()));
        }
        uriTemplateList.put(uriTemplateBuilder.getTemplateId(), uriTemplateBuilder.build());
    }
    Set<Policy> subscriptionPolicies = new HashSet<>();
    apidto.getPolicies().forEach(v -> subscriptionPolicies.add(new SubscriptionPolicy(v)));
    API.APIBuilder apiBuilder = new API.APIBuilder(apidto.getProvider(), apidto.getName(), apidto.getVersion()).id(apidto.getId()).context(apidto.getContext()).description(apidto.getDescription()).lifeCycleStatus(apidto.getLifeCycleStatus()).endpoint(fromEndpointListToMap(apidto.getEndpoint())).visibleRoles(new HashSet<>(apidto.getVisibleRoles())).policies(subscriptionPolicies).apiPermission(apidto.getPermission()).tags(new HashSet<>(apidto.getTags())).labels(new ArrayList<>(apidto.getLabels())).transport(new HashSet<>(apidto.getTransport())).isResponseCachingEnabled(Boolean.valueOf(apidto.getResponseCaching())).businessInformation(businessInformation).uriTemplates(uriTemplateList).corsConfiguration(corsConfiguration).wsdlUri(apidto.getWsdlUri()).scopes(apidto.getScopes()).securityScheme(mapSecuritySchemeListToInt(apidto.getSecurityScheme()));
    if (apidto.getIsDefaultVersion() != null) {
        apiBuilder.isDefaultVersion(apidto.getIsDefaultVersion());
    }
    if (apidto.getVisibility() != null) {
        apiBuilder.visibility(API.Visibility.valueOf(apidto.getVisibility().toString()));
    }
    if (apidto.getCacheTimeout() != null) {
        apiBuilder.cacheTimeout(apidto.getCacheTimeout());
    }
    if (apidto.getApiPolicy() != null) {
        Policy policy = new APIPolicy(apidto.getApiPolicy());
        apiBuilder.apiPolicy(policy);
    }
    if (apidto.getHasOwnGateway() != null) {
        apiBuilder.hasOwnGateway(apidto.getHasOwnGateway());
    }
    if (apidto.getThreatProtectionPolicies() != null) {
        API_threatProtectionPoliciesDTO threatProtectionPoliciesDTO = apidto.getThreatProtectionPolicies();
        List<API_threatProtectionPolicies_listDTO> threatProtectionPolicies_listDTO = threatProtectionPoliciesDTO.getList();
        Set<String> policyIdSet = new HashSet<>();
        for (API_threatProtectionPolicies_listDTO listDTO : threatProtectionPolicies_listDTO) {
            policyIdSet.add(listDTO.getPolicyId());
        }
        apiBuilder.threatProtectionPolicies(policyIdSet);
    }
    return apiBuilder;
}
Also used : SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) ThreatProtectionPolicy(org.wso2.carbon.apimgt.core.models.policy.ThreatProtectionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) HashMap(java.util.HashMap) API_threatProtectionPolicies_listDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_threatProtectionPolicies_listDTO) API_operationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_operationsDTO) API_threatProtectionPoliciesDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_threatProtectionPoliciesDTO) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) API_businessInformationDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_businessInformationDTO) API_corsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_corsConfigurationDTO) HashSet(java.util.HashSet) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) API(org.wso2.carbon.apimgt.core.models.API) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy)

Example 7 with CORSConfiguration

use of org.wso2.carbon.apimgt.api.model.CORSConfiguration in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createDefaultAPI.

public static API.APIBuilder createDefaultAPI() {
    Set<String> transport = new HashSet<>();
    transport.add(HTTP);
    transport.add(HTTPS);
    Set<String> tags = new HashSet<>();
    tags.add(TAG_CLIMATE);
    Set<Policy> policies = new HashSet<>();
    policies.add(goldSubscriptionPolicy);
    policies.add(silverSubscriptionPolicy);
    policies.add(bronzeSubscriptionPolicy);
    BusinessInformation businessInformation = new BusinessInformation();
    businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
    businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
    businessInformation.setTechnicalOwner(NAME_TECHNICAL_OWNER_1);
    businessInformation.setTechnicalOwnerEmail(EMAIL_TECHNICAL_OWNER_1);
    String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
    Set<String> visibleRoles = new HashSet<>();
    visibleRoles.add("testRple");
    List<String> labels = new ArrayList<>();
    labels.add("testLabel");
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setEnabled(true);
    corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
    corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setAllowOrigins(Arrays.asList("*"));
    Map<String, Endpoint> endpointMap = new HashMap<>();
    endpointMap.put("TestEndpoint", createMockEndpoint());
    API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).wsdlUri("http://localhost:9443/echo?wsdl").isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(visibleRoles).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).workflowStatus(WORKFLOW_STATUS).labels(labels).endpoint(endpointMap);
    Map map = new HashMap();
    map.put(DEVELOPER_ROLE_ID, 6);
    map.put(ADMIN_ROLE_ID, 15);
    apiBuilder.permissionMap(map);
    return apiBuilder;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) API(org.wso2.carbon.apimgt.core.models.API) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 8 with CORSConfiguration

use of org.wso2.carbon.apimgt.api.model.CORSConfiguration in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createUniqueAPI.

/**
 * Create an unique API.
 *
 * @return APIBuilder with unique API details
 */
public static API.APIBuilder createUniqueAPI() {
    Set<String> transport = new HashSet<>();
    transport.add(HTTP);
    Set<String> tags = new HashSet<>();
    tags.add(TAG_FOOD);
    tags.add(TAG_BEVERAGE);
    Set<Policy> policies = new HashSet<>();
    policies.add(silverSubscriptionPolicy);
    policies.add(bronzeSubscriptionPolicy);
    BusinessInformation businessInformation = new BusinessInformation();
    businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
    businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
    businessInformation.setTechnicalOwner(NAME_BUSINESS_OWNER_2);
    businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_2);
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setEnabled(true);
    corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
    corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setAllowOrigins(Arrays.asList("*"));
    String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\"]}]";
    Map permissionMap = new HashMap();
    permissionMap.put(DEVELOPER_ROLE_ID, 6);
    permissionMap.put(ADMIN_ROLE_ID, 7);
    API.APIBuilder apiBuilder = new API.APIBuilder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), API_VERSION).id(UUID.randomUUID().toString()).context(UUID.randomUUID().toString()).description("Get Food & Beverage Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).endpoint(Collections.emptyMap()).wsdlUri(SAMPLE_API_WSDL).isResponseCachingEnabled(true).cacheTimeout(120).isDefaultVersion(true).apiPolicy(goldApiPolicy).transport(transport).tags(tags).policies(policies).visibility(API.Visibility.RESTRICTED).visibleRoles(new HashSet<>(Arrays.asList(CUSTOMER_ROLE, MANAGER_ROLE, EMPLOYEE_ROLE))).businessInformation(businessInformation).corsConfiguration(corsConfiguration).apiPermission(permissionJson).permissionMap(permissionMap).createdTime(LocalDateTime.now()).createdBy(API_CREATOR).uriTemplates(Collections.emptyMap()).apiDefinition(apiDefinition).lastUpdatedTime(LocalDateTime.now()).threatProtectionPolicies(new HashSet<>(Arrays.asList("a", "b")));
    return apiBuilder;
}
Also used : ThreatProtectionPolicy(org.wso2.carbon.apimgt.core.models.policy.ThreatProtectionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) CustomPolicy(org.wso2.carbon.apimgt.core.models.policy.CustomPolicy) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) HashMap(java.util.HashMap) API(org.wso2.carbon.apimgt.core.models.API) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 9 with CORSConfiguration

use of org.wso2.carbon.apimgt.api.model.CORSConfiguration in project carbon-apimgt by wso2.

the class APIPublisherImpl method addApiFromDefinition.

/**
 * Create api from Definition
 *
 * @param apiDefinition API definition stream.
 * @return UUID of the added API.
 * @throws APIManagementException If failed to add the API.
 */
@Override
public String addApiFromDefinition(InputStream apiDefinition) throws APIManagementException {
    try {
        String apiDefinitionString = IOUtils.toString(apiDefinition);
        validateScope(apiDefinitionString);
        API.APIBuilder apiBuilder = apiDefinitionFromSwagger20.generateApiFromSwaggerResource(getUsername(), apiDefinitionString);
        Map<String, String> scopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(apiDefinitionString);
        for (Map.Entry<String, String> scopeEntry : scopes.entrySet()) {
            getKeyManager().registerScope(new Scope(scopeEntry.getKey(), scopeEntry.getValue()));
        }
        apiBuilder.corsConfiguration(new CorsConfiguration());
        apiBuilder.apiDefinition(apiDefinitionString);
        addAPI(apiBuilder);
        return apiBuilder.getId();
    } catch (IOException e) {
        throw new APIManagementException("Couldn't Generate ApiDefinition from file", ExceptionCodes.API_DEFINITION_MALFORMED);
    }
}
Also used : Scope(org.wso2.carbon.apimgt.core.models.Scope) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) API(org.wso2.carbon.apimgt.core.models.API) IOException(java.io.IOException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 10 with CORSConfiguration

use of org.wso2.carbon.apimgt.api.model.CORSConfiguration in project carbon-apimgt by wso2.

the class OAS3Parser method setExtensionsToAPI.

/**
 * This method returns api that is attached with api extensions related to micro-gw
 *
 * @param apiDefinition String
 * @param api           API
 * @return API
 */
@Override
public API setExtensionsToAPI(String apiDefinition, API api) throws APIManagementException {
    OpenAPI openAPI = getOpenAPI(apiDefinition);
    Map<String, Object> extensions = openAPI.getExtensions();
    if (extensions == null) {
        return api;
    }
    // Setup Custom auth header for API
    String authHeader = OASParserUtil.getAuthorizationHeaderFromSwagger(extensions);
    if (StringUtils.isNotBlank(authHeader)) {
        api.setAuthorizationHeader(authHeader);
    }
    // Setup application Security
    List<String> applicationSecurity = OASParserUtil.getApplicationSecurityTypes(extensions);
    Boolean isOptional = OASParserUtil.getAppSecurityStateFromSwagger(extensions);
    if (!applicationSecurity.isEmpty()) {
        String securityList = api.getApiSecurity();
        securityList = securityList == null ? "" : securityList;
        for (String securityType : applicationSecurity) {
            if (APIConstants.DEFAULT_API_SECURITY_OAUTH2.equals(securityType) && !securityList.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
                securityList = securityList + "," + APIConstants.DEFAULT_API_SECURITY_OAUTH2;
            }
            if (APIConstants.API_SECURITY_BASIC_AUTH.equals(securityType) && !securityList.contains(APIConstants.API_SECURITY_BASIC_AUTH)) {
                securityList = securityList + "," + APIConstants.API_SECURITY_BASIC_AUTH;
            }
            if (APIConstants.API_SECURITY_API_KEY.equals(securityType) && !securityList.contains(APIConstants.API_SECURITY_API_KEY)) {
                securityList = securityList + "," + APIConstants.API_SECURITY_API_KEY;
            }
        }
        if (!(isOptional || securityList.contains(APIConstants.MANDATORY))) {
            securityList = securityList + "," + APIConstants.MANDATORY;
        }
        api.setApiSecurity(securityList);
    }
    // Setup mutualSSL configuration
    String mutualSSL = OASParserUtil.getMutualSSLEnabledFromSwagger(extensions);
    if (StringUtils.isNotBlank(mutualSSL)) {
        String securityList = api.getApiSecurity();
        if (StringUtils.isBlank(securityList)) {
            securityList = APIConstants.DEFAULT_API_SECURITY_OAUTH2;
        }
        if (APIConstants.OPTIONAL.equals(mutualSSL) && !securityList.contains(APIConstants.API_SECURITY_MUTUAL_SSL)) {
            securityList = securityList + "," + APIConstants.API_SECURITY_MUTUAL_SSL;
        } else if (APIConstants.MANDATORY.equals(mutualSSL) && !securityList.contains(APIConstants.API_SECURITY_MUTUAL_SSL_MANDATORY)) {
            securityList = securityList + "," + APIConstants.API_SECURITY_MUTUAL_SSL + "," + APIConstants.API_SECURITY_MUTUAL_SSL_MANDATORY;
        }
        api.setApiSecurity(securityList);
    }
    // Setup CORSConfigurations
    CORSConfiguration corsConfiguration = OASParserUtil.getCorsConfigFromSwagger(extensions);
    if (corsConfiguration != null) {
        api.setCorsConfiguration(corsConfiguration);
    }
    // Setup Response cache enabling
    boolean responseCacheEnable = OASParserUtil.getResponseCacheFromSwagger(extensions);
    if (responseCacheEnable) {
        api.setResponseCache(APIConstants.ENABLED);
    }
    // Setup cache timeOut
    int cacheTimeOut = OASParserUtil.getCacheTimeOutFromSwagger(extensions);
    if (cacheTimeOut != 0) {
        api.setCacheTimeout(cacheTimeOut);
    }
    // Setup Transports
    String transports = OASParserUtil.getTransportsFromSwagger(extensions);
    if (StringUtils.isNotBlank(transports)) {
        api.setTransports(transports);
    }
    // Setup Throttlingtiers
    String throttleTier = OASParserUtil.getThrottleTierFromSwagger(extensions);
    if (StringUtils.isNotBlank(throttleTier)) {
        api.setApiLevelPolicy(throttleTier);
    }
    return api;
}
Also used : CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) JSONObject(org.json.simple.JSONObject) OpenAPI(io.swagger.v3.oas.models.OpenAPI)

Aggregations

CorsConfiguration (org.wso2.carbon.apimgt.core.models.CorsConfiguration)17 HashSet (java.util.HashSet)16 BusinessInformation (org.wso2.carbon.apimgt.core.models.BusinessInformation)16 HashMap (java.util.HashMap)15 CORSConfiguration (org.wso2.carbon.apimgt.api.model.CORSConfiguration)15 API (org.wso2.carbon.apimgt.core.models.API)13 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)13 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)13 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)13 Map (java.util.Map)10 ArrayList (java.util.ArrayList)9 ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)8 API (org.wso2.carbon.apimgt.api.model.API)7 QuotaPolicy (org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy)7 ThreatProtectionPolicy (org.wso2.carbon.apimgt.core.models.policy.ThreatProtectionPolicy)7 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)6 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)6 Test (org.junit.Test)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 Tier (org.wso2.carbon.apimgt.api.model.Tier)5