Search in sources :

Example 26 with CORSConfiguration

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

the class MappingUtil method toAPIDto.

/**
 * This method converts the API Object from models into APIDTO object.
 *
 * @param api API object
 * @return APIDTO object with provided API object
 */
public static APIDTO toAPIDto(API api) throws IOException {
    APIDTO apidto = new APIDTO();
    apidto.setId(api.getId());
    apidto.setName(api.getName());
    apidto.version(api.getVersion());
    apidto.setContext(api.getContext());
    apidto.setDescription(api.getDescription());
    apidto.setIsDefaultVersion(api.isDefaultVersion());
    apidto.setVisibility(APIDTO.VisibilityEnum.valueOf(api.getVisibility().toString()));
    apidto.setResponseCaching(Boolean.toString(api.isResponseCachingEnabled()));
    apidto.setCacheTimeout(api.getCacheTimeout());
    apidto.setVisibleRoles(new ArrayList<>(api.getVisibleRoles()));
    apidto.setProvider(api.getProvider());
    apidto.setPermission(api.getApiPermission());
    apidto.setLifeCycleStatus(api.getLifeCycleStatus());
    apidto.setWorkflowStatus(api.getWorkflowStatus());
    apidto.setTags(new ArrayList<>(api.getTags()));
    apidto.hasOwnGateway(api.hasOwnGateway());
    apidto.setLabels(new ArrayList<>(api.getLabels()));
    apidto.setTransport(new ArrayList<>(api.getTransport()));
    apidto.setUserPermissionsForApi(api.getUserSpecificApiPermissions());
    apidto.setSecurityScheme(mapSecuritySchemeIntToList(api.getSecurityScheme()));
    for (Policy policy : api.getPolicies()) {
        apidto.addPoliciesItem(policy.getPolicyName());
    }
    apidto.setScopes(api.getScopes());
    BusinessInformation businessInformation = api.getBusinessInformation();
    API_businessInformationDTO apiBusinessInformationDTO = new API_businessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(businessInformation.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(businessInformation.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(businessInformation.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(businessInformation.getTechnicalOwnerEmail());
    apidto.setBusinessInformation(apiBusinessInformationDTO);
    CorsConfiguration corsConfiguration = api.getCorsConfiguration();
    API_corsConfigurationDTO apiCorsConfigurationDTO = new API_corsConfigurationDTO();
    apiCorsConfigurationDTO.setAccessControlAllowCredentials(corsConfiguration.isAllowCredentials());
    apiCorsConfigurationDTO.setAccessControlAllowHeaders(corsConfiguration.getAllowHeaders());
    apiCorsConfigurationDTO.setAccessControlAllowMethods(corsConfiguration.getAllowMethods());
    apiCorsConfigurationDTO.setAccessControlAllowOrigins(corsConfiguration.getAllowOrigins());
    apiCorsConfigurationDTO.setCorsConfigurationEnabled(corsConfiguration.isEnabled());
    apidto.setCorsConfiguration(apiCorsConfigurationDTO);
    apidto.setEndpoint(fromEndpointToList(api.getEndpoint()));
    for (UriTemplate uriTemplate : api.getUriTemplates().values()) {
        API_operationsDTO apiOperationsDTO = new API_operationsDTO();
        apiOperationsDTO.setId(uriTemplate.getTemplateId());
        apiOperationsDTO.setUritemplate(uriTemplate.getUriTemplate());
        apiOperationsDTO.setAuthType(uriTemplate.getAuthType());
        apiOperationsDTO.setEndpoint(fromEndpointToList(uriTemplate.getEndpoint()));
        apiOperationsDTO.setHttpVerb(uriTemplate.getHttpVerb());
        apiOperationsDTO.setPolicy(uriTemplate.getPolicy().getPolicyName());
        apiOperationsDTO.setScopes(uriTemplate.getScopes());
        apidto.addOperationsItem(apiOperationsDTO);
    }
    if (api.getApiPolicy() != null) {
        apidto.setApiPolicy(api.getApiPolicy().getPolicyName());
    }
    apidto.setCreatedTime(api.getCreatedTime().toString());
    apidto.setLastUpdatedTime(api.getLastUpdatedTime().toString());
    if (api.getThreatProtectionPolicies() != null) {
        List<String> policyIdList = new ArrayList<>(api.getThreatProtectionPolicies());
        List<API_threatProtectionPolicies_listDTO> listDTOS = new ArrayList<>();
        for (String policyId : policyIdList) {
            API_threatProtectionPolicies_listDTO threatProtectionPoliciesListDTO = new API_threatProtectionPolicies_listDTO();
            threatProtectionPoliciesListDTO.setPolicyId(policyId);
            // set priority when implementing
            // threatProtectionPoliciesListDTO.setPriority(10);
            listDTOS.add(threatProtectionPoliciesListDTO);
        }
        API_threatProtectionPoliciesDTO threatProtectionPoliciesDTO = new API_threatProtectionPoliciesDTO();
        threatProtectionPoliciesDTO.setList(listDTOS);
        apidto.setThreatProtectionPolicies(threatProtectionPoliciesDTO);
    }
    return apidto;
}
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) ArrayList(java.util.ArrayList) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) 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) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO) API_threatProtectionPoliciesDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_threatProtectionPoliciesDTO) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) API_businessInformationDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_businessInformationDTO) API_corsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.API_corsConfigurationDTO)

Example 27 with CORSConfiguration

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

the class APIUtilTest method testGetAPI.

@Test
public void testGetAPI() throws Exception {
    API expectedAPI = getUniqueAPI();
    final String provider = expectedAPI.getId().getProviderName();
    final String tenantDomain = org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    final int tenantId = -1234;
    GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
    Registry registry = Mockito.mock(Registry.class);
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    Resource resource = Mockito.mock(Resource.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class);
    SubscriptionPolicy policy = Mockito.mock(SubscriptionPolicy.class);
    SubscriptionPolicy[] policies = new SubscriptionPolicy[] { policy };
    QuotaPolicy quotaPolicy = Mockito.mock(QuotaPolicy.class);
    RequestCountLimit limit = Mockito.mock(RequestCountLimit.class);
    PowerMockito.mockStatic(ApiMgtDAO.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    Mockito.when(apiMgtDAO.getAPIID(Mockito.any(String.class))).thenReturn(123);
    Mockito.when(artifact.getId()).thenReturn("");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).thenReturn(provider);
    Mockito.when(MultitenantUtils.getTenantDomain(provider)).thenReturn(tenantDomain);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
    String artifactPath = "";
    PowerMockito.mockStatic(GovernanceUtils.class);
    Mockito.when(GovernanceUtils.getArtifactPath(registry, "")).thenReturn(artifactPath);
    Mockito.when(registry.get(artifactPath)).thenReturn(resource);
    Mockito.when(resource.getLastModified()).thenReturn(expectedAPI.getLastUpdated());
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
    Mockito.when(apiMgtDAO.getSubscriptionPolicies(tenantId)).thenReturn(policies);
    Mockito.when(policy.getPolicyName()).thenReturn("policy");
    Mockito.when(policy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
    Mockito.when(quotaPolicy.getLimit()).thenReturn(limit);
    Mockito.when(registry.getTags(artifactPath)).thenReturn(getTagsFromSet(expectedAPI.getTags()));
    HashMap<String, String> urlPatterns = getURLTemplatePattern(expectedAPI.getUriTemplates());
    Mockito.when(apiMgtDAO.getURITemplatesPerAPIAsString(Mockito.any(String.class))).thenReturn(urlPatterns);
    CORSConfiguration corsConfiguration = expectedAPI.getCorsConfiguration();
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS)).thenReturn(corsConfiguration.getAccessControlAllowHeaders().toString());
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_METHODS)).thenReturn(corsConfiguration.getAccessControlAllowMethods().toString());
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN)).thenReturn(corsConfiguration.getAccessControlAllowOrigins().toString());
    API api = APIUtil.getAPI(artifact, registry);
    Assert.assertNotNull(api);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) Resource(org.wso2.carbon.registry.core.Resource) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIUtil.getOAuthConfigurationFromTenantRegistry(org.wso2.carbon.apimgt.impl.utils.APIUtil.getOAuthConfigurationFromTenantRegistry) Registry(org.wso2.carbon.registry.core.Registry) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) RealmService(org.wso2.carbon.user.core.service.RealmService) API(org.wso2.carbon.apimgt.api.model.API) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 28 with CORSConfiguration

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

the class OAS2Parser 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 {
    Swagger swagger = getSwagger(apiDefinition);
    Map<String, Object> extensions = swagger.getVendorExtensions();
    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) Swagger(io.swagger.models.Swagger)

Example 29 with CORSConfiguration

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

the class APIUtilTest method testGetAPIWithGovernanceArtifact.

@Test
public void testGetAPIWithGovernanceArtifact() throws Exception {
    System.setProperty("carbon.home", APIUtilTest.class.getResource("/").getFile());
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        API expectedAPI = getUniqueAPI();
        final String provider = expectedAPI.getId().getProviderName();
        final String tenantDomain = org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        final int tenantId = -1234;
        System.setProperty("carbon.home", "");
        File siteConfFile = new File(Thread.currentThread().getContextClassLoader().getResource("tenant-conf.json").getFile());
        String tenantConfValue = FileUtils.readFileToString(siteConfFile);
        GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
        Registry registry = Mockito.mock(Registry.class);
        ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
        Resource resource = Mockito.mock(Resource.class);
        ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
        RealmService realmService = Mockito.mock(RealmService.class);
        TenantManager tenantManager = Mockito.mock(TenantManager.class);
        APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
        APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
        ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class);
        SubscriptionPolicy policy = Mockito.mock(SubscriptionPolicy.class);
        SubscriptionPolicy[] policies = new SubscriptionPolicy[] { policy };
        QuotaPolicy quotaPolicy = Mockito.mock(QuotaPolicy.class);
        RequestCountLimit limit = Mockito.mock(RequestCountLimit.class);
        PrivilegedCarbonContext carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
        RegistryService registryService = Mockito.mock(RegistryService.class);
        UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
        PowerMockito.mockStatic(ApiMgtDAO.class);
        PowerMockito.mockStatic(GovernanceUtils.class);
        PowerMockito.mockStatic(MultitenantUtils.class);
        PowerMockito.mockStatic(ServiceReferenceHolder.class);
        Mockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
        Mockito.when(apiMgtDAO.getAPIID(Mockito.any(String.class))).thenReturn(123);
        Mockito.when(apiMgtDAO.getPolicyNames(PolicyConstants.POLICY_LEVEL_SUB, provider)).thenReturn(new String[] { "Unlimited" });
        Mockito.when(artifact.getId()).thenReturn("");
        Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).thenReturn(provider);
        Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT)).thenReturn("15");
        Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_TIER)).thenReturn("Unlimited");
        Mockito.when(MultitenantUtils.getTenantDomain(provider)).thenReturn(tenantDomain);
        Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
        APIMConfigService apimConfigService = Mockito.mock(APIMConfigService.class);
        Mockito.when(serviceReferenceHolder.getApimConfigService()).thenReturn(apimConfigService);
        Mockito.when(apimConfigService.getTenantConfig(tenantDomain)).thenReturn(tenantConfValue);
        Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
        Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
        Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
        Mockito.when(registryService.getConfigSystemRegistry(tenantId)).thenReturn(userRegistry);
        String artifactPath = "";
        Mockito.when(GovernanceUtils.getArtifactPath(registry, "")).thenReturn(artifactPath);
        Mockito.when(registry.get(artifactPath)).thenReturn(resource);
        Mockito.when(resource.getLastModified()).thenReturn(expectedAPI.getLastUpdated());
        Mockito.when(resource.getCreatedTime()).thenReturn(expectedAPI.getLastUpdated());
        Mockito.when(resource.getContent()).thenReturn(tenantConfValue.getBytes());
        Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
        Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
        Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
        Mockito.when(apiMgtDAO.getSubscriptionPolicies(tenantId)).thenReturn(policies);
        Mockito.when(policy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
        Mockito.when(quotaPolicy.getLimit()).thenReturn(limit);
        Mockito.when(registry.getTags(artifactPath)).thenReturn(getTagsFromSet(expectedAPI.getTags()));
        ArrayList<URITemplate> urlList = getURLTemplateList(expectedAPI.getUriTemplates());
        Mockito.when(apiMgtDAO.getAllURITemplates(Mockito.anyString(), Mockito.anyString())).thenReturn(urlList);
        CORSConfiguration corsConfiguration = expectedAPI.getCorsConfiguration();
        Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS)).thenReturn(corsConfiguration.getAccessControlAllowHeaders().toString());
        Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_METHODS)).thenReturn(corsConfiguration.getAccessControlAllowMethods().toString());
        Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN)).thenReturn(corsConfiguration.getAccessControlAllowOrigins().toString());
        API api = APIUtil.getAPI(artifact);
        Assert.assertNotNull(api);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) Resource(org.wso2.carbon.registry.core.Resource) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIUtil.getOAuthConfigurationFromTenantRegistry(org.wso2.carbon.apimgt.impl.utils.APIUtil.getOAuthConfigurationFromTenantRegistry) Registry(org.wso2.carbon.registry.core.Registry) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) RealmService(org.wso2.carbon.user.core.service.RealmService) API(org.wso2.carbon.apimgt.api.model.API) File(java.io.File) APIMConfigService(org.wso2.carbon.apimgt.impl.config.APIMConfigService) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 30 with CORSConfiguration

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

the class TemplateBuilderUtil method getAPITemplateBuilder.

public static APITemplateBuilderImpl getAPITemplateBuilder(API api, String tenantDomain, List<ClientCertificateDTO> clientCertificateDTOS, List<SoapToRestMediationDto> soapToRestInMediationDtos, List<SoapToRestMediationDto> soapToRestMediationDtos) throws APIManagementException {
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    APITemplateBuilderImpl vtb = new APITemplateBuilderImpl(api, soapToRestInMediationDtos, soapToRestMediationDtos);
    Map<String, String> latencyStatsProperties = new HashMap<String, String>();
    latencyStatsProperties.put(APIConstants.API_UUID, api.getUUID());
    if (!APIUtil.isStreamingApi(api)) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIMgtLatencyStatsHandler", latencyStatsProperties);
    }
    Map<String, String> corsProperties = new HashMap<String, String>();
    corsProperties.put(APIConstants.CORSHeaders.IMPLEMENTATION_TYPE_HANDLER_VALUE, api.getImplementation());
    // Get authorization header from the API object or from the tenant registry
    String authorizationHeader;
    if (!StringUtils.isBlank(api.getAuthorizationHeader())) {
        authorizationHeader = api.getAuthorizationHeader();
    } else {
        // Retrieves the auth configuration from tenant registry or api-manager.xml if not available
        // in tenant registry
        authorizationHeader = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.AUTHORIZATION_HEADER);
    }
    if (!StringUtils.isBlank(authorizationHeader)) {
        corsProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
    }
    if (!(APIConstants.APITransportType.WS.toString().equals(api.getType()))) {
        if (api.getCorsConfiguration() != null && api.getCorsConfiguration().isCorsConfigurationEnabled()) {
            CORSConfiguration corsConfiguration = api.getCorsConfiguration();
            if (corsConfiguration.getAccessControlAllowHeaders() != null) {
                StringBuilder allowHeaders = new StringBuilder();
                for (String header : corsConfiguration.getAccessControlAllowHeaders()) {
                    allowHeaders.append(header).append(',');
                }
                if (allowHeaders.length() != 0) {
                    allowHeaders.deleteCharAt(allowHeaders.length() - 1);
                    corsProperties.put(APIConstants.CORSHeaders.ALLOW_HEADERS_HANDLER_VALUE, allowHeaders.toString());
                }
            }
            if (corsConfiguration.getAccessControlAllowOrigins() != null) {
                StringBuilder allowOrigins = new StringBuilder();
                for (String origin : corsConfiguration.getAccessControlAllowOrigins()) {
                    allowOrigins.append(origin).append(',');
                }
                if (allowOrigins.length() != 0) {
                    allowOrigins.deleteCharAt(allowOrigins.length() - 1);
                    corsProperties.put(APIConstants.CORSHeaders.ALLOW_ORIGIN_HANDLER_VALUE, allowOrigins.toString());
                }
            }
            if (corsConfiguration.getAccessControlAllowMethods() != null) {
                StringBuilder allowedMethods = new StringBuilder();
                for (String methods : corsConfiguration.getAccessControlAllowMethods()) {
                    allowedMethods.append(methods).append(',');
                }
                if (allowedMethods.length() != 0) {
                    allowedMethods.deleteCharAt(allowedMethods.length() - 1);
                    corsProperties.put(APIConstants.CORSHeaders.ALLOW_METHODS_HANDLER_VALUE, allowedMethods.toString());
                }
            }
            if (corsConfiguration.isAccessControlAllowCredentials()) {
                corsProperties.put(APIConstants.CORSHeaders.ALLOW_CREDENTIALS_HANDLER_VALUE, String.valueOf(corsConfiguration.isAccessControlAllowCredentials()));
            }
            vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
        } else if (APIUtil.isCORSEnabled()) {
            vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
        }
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIStatusHandler", Collections.emptyMap());
    }
    Map<String, String> clientCertificateObject = null;
    CertificateMgtUtils certificateMgtUtils = CertificateMgtUtils.getInstance();
    if (clientCertificateDTOS != null) {
        clientCertificateObject = new HashMap<>();
        for (ClientCertificateDTO clientCertificateDTO : clientCertificateDTOS) {
            clientCertificateObject.put(certificateMgtUtils.getUniqueIdentifierOfCertificate(clientCertificateDTO.getCertificate()), clientCertificateDTO.getTierName());
        }
    }
    Map<String, String> authProperties = new HashMap<>();
    if (!StringUtils.isBlank(authorizationHeader)) {
        authProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
    }
    String apiSecurity = api.getApiSecurity();
    String apiLevelPolicy = api.getApiLevelPolicy();
    authProperties.put(APIConstants.API_SECURITY, apiSecurity);
    authProperties.put(APIConstants.API_LEVEL_POLICY, apiLevelPolicy);
    if (clientCertificateObject != null) {
        authProperties.put(APIConstants.CERTIFICATE_INFORMATION, clientCertificateObject.toString());
    }
    // Get RemoveHeaderFromOutMessage from tenant registry or api-manager.xml
    String removeHeaderFromOutMessage = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE);
    if (!StringUtils.isBlank(removeHeaderFromOutMessage)) {
        authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, removeHeaderFromOutMessage);
    } else {
        authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE_DEFAULT);
    }
    authProperties.put(APIConstants.API_UUID, api.getUUID());
    authProperties.put("keyManagers", String.join(",", api.getKeyManagers()));
    if (APIConstants.GRAPHQL_API.equals(api.getType())) {
        Map<String, String> apiUUIDProperty = new HashMap<String, String>();
        apiUUIDProperty.put(APIConstants.API_UUID, api.getUUID());
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.graphQL.GraphQLAPIHandler", apiUUIDProperty);
    }
    if (APIConstants.APITransportType.WEBSUB.toString().equals(api.getType())) {
        authProperties.put(APIConstants.WebHookProperties.EVENT_RECEIVING_RESOURCE_PATH, APIConstants.WebHookProperties.DEFAULT_SUBSCRIPTION_RESOURCE_PATH);
        authProperties.put(APIConstants.WebHookProperties.TOPIC_QUERY_PARAM_NAME, APIConstants.WebHookProperties.DEFAULT_TOPIC_QUERY_PARAM_NAME);
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.streaming.webhook.WebhookApiHandler", authProperties);
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.streaming.webhook." + "WebhooksExtensionHandler", Collections.emptyMap());
    } else if (APIConstants.APITransportType.SSE.toString().equals(api.getType())) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.streaming.sse.SseApiHandler", authProperties);
    } else if (!(APIConstants.APITransportType.WS.toString().equals(api.getType()))) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler", authProperties);
    }
    if (APIConstants.GRAPHQL_API.equals(api.getType())) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.graphQL.GraphQLQueryAnalysisHandler", Collections.emptyMap());
    }
    if (!APIUtil.isStreamingApi(api)) {
        Map<String, String> properties = new HashMap<String, String>();
        if (api.getProductionMaxTps() != null) {
            properties.put("productionMaxCount", api.getProductionMaxTps());
        }
        if (api.getSandboxMaxTps() != null) {
            properties.put("sandboxMaxCount", api.getSandboxMaxTps());
        }
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler", properties);
        properties = new HashMap<String, String>();
        properties.put("configKey", APIConstants.GA_CONF_KEY);
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.analytics.APIMgtGoogleAnalyticsTrackingHandler", properties);
        String extensionHandlerPosition = getExtensionHandlerPosition(tenantDomain);
        if ("top".equalsIgnoreCase(extensionHandlerPosition)) {
            vtb.addHandlerPriority("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap(), 2);
        } else {
            vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap());
        }
    }
    return vtb;
}
Also used : CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) HashMap(java.util.HashMap) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) CertificateMgtUtils(org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils) APITemplateBuilderImpl(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APITemplateBuilderImpl)

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