Search in sources :

Example 76 with Scope

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

the class OASTestBase method testGenerateAPIDefinition2.

public void testGenerateAPIDefinition2(APIDefinition parser, String content, OASParserEvaluator evaluator) throws Exception {
    JSONObject jsonObject = new JSONObject(content);
    String equalNoOfResources = jsonObject.getJSONObject("equalNoOfResources").toString();
    APIIdentifier identifier = new APIIdentifier("admin", "simple", "1.0.0");
    API api = new API(identifier);
    api.setScopes(new HashSet<>(Arrays.asList(sampleScope, extensionScope)));
    api.setUriTemplates(new HashSet<>(Arrays.asList(petGet, petPost, itemGet, itemPost)));
    String definition = parser.generateAPIDefinition(new SwaggerData(api), equalNoOfResources);
    APIDefinitionValidationResponse response = parser.validateAPIDefinition(definition, false);
    Assert.assertTrue(response.isValid());
    Assert.assertTrue(response.getParser().getClass().equals(parser.getClass()));
    Set<URITemplate> uriTemplates = parser.getURITemplates(definition);
    Assert.assertEquals(4, uriTemplates.size());
    Assert.assertTrue(uriTemplates.contains(petGet));
    Assert.assertTrue(uriTemplates.contains(petPost));
    Assert.assertTrue(uriTemplates.contains(itemGet));
    Assert.assertTrue(uriTemplates.contains(itemPost));
    Set<Scope> scopes = parser.getScopes(definition);
    Assert.assertEquals(2, scopes.size());
    Assert.assertTrue(scopes.contains(sampleScope));
    Assert.assertTrue(scopes.contains(extensionScope));
    // Remove operation and path from API object
    String extraResourcesInDefinition = jsonObject.getJSONObject("extraResourcesInDefinition").toString();
    api.setUriTemplates(new HashSet<>(Arrays.asList(itemGet, itemPost)));
    definition = parser.generateAPIDefinition(new SwaggerData(api), extraResourcesInDefinition);
    response = parser.validateAPIDefinition(definition, false);
    Assert.assertTrue(response.isValid());
    Assert.assertTrue(response.getParser().getClass().equals(parser.getClass()));
    uriTemplates = parser.getURITemplates(definition);
    Assert.assertEquals(2, uriTemplates.size());
    // assert generated paths
    if (evaluator != null) {
        evaluator.eval(definition);
    }
    Iterator iterator = uriTemplates.iterator();
    while (iterator.hasNext()) {
        URITemplate element = (URITemplate) iterator.next();
        if ("/pets".equalsIgnoreCase(element.getUriTemplate())) {
            Assert.fail("Removed paths from API operation should not present.");
        }
        if ("/items".equalsIgnoreCase(element.getUriTemplate()) && "PUT".equalsIgnoreCase(element.getHTTPVerb())) {
            Assert.fail("Removed item from API operation should not present.");
        }
    }
    Assert.assertTrue(uriTemplates.contains(itemGet));
    Assert.assertTrue(uriTemplates.contains(itemPost));
    // Add operation and path to API object
    String lessResourcesInDefinition = jsonObject.getJSONObject("lessResourcesInDefinition").toString();
    api.setUriTemplates(new HashSet<>(Arrays.asList(petGet, petPost, itemGet, itemPost)));
    definition = parser.generateAPIDefinition(new SwaggerData(api), lessResourcesInDefinition);
    response = parser.validateAPIDefinition(definition, false);
    Assert.assertTrue(response.isValid());
    Assert.assertTrue(response.getParser().getClass().equals(parser.getClass()));
    uriTemplates = parser.getURITemplates(definition);
    Assert.assertEquals(4, uriTemplates.size());
    Assert.assertTrue(uriTemplates.contains(petGet));
    Assert.assertTrue(uriTemplates.contains(petPost));
    Assert.assertTrue(uriTemplates.contains(itemGet));
    Assert.assertTrue(uriTemplates.contains(itemPost));
}
Also used : JSONObject(org.json.JSONObject) Scope(org.wso2.carbon.apimgt.api.model.Scope) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Iterator(java.util.Iterator) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 77 with Scope

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

the class APIMgtDAOTest method getUriTemplate.

private URITemplate getUriTemplate(String resourceString, String httpVerb, String authType, String scope, String throtlingTier) {
    URITemplate uriTemplate = new URITemplate();
    uriTemplate.setUriTemplate(resourceString);
    uriTemplate.setHTTPVerb(httpVerb);
    uriTemplate.setThrottlingTier(throtlingTier);
    uriTemplate.setAuthType(authType);
    uriTemplate.setMediationScript("abcd defgh fff");
    if (scope != null) {
        Scope scope1 = new Scope();
        scope1.setId("0");
        scope1.setDescription("");
        scope1.setKey(scope);
        scope1.setName(scope);
        scope1.setRoles("admin");
        uriTemplate.setScope(scope1);
        uriTemplate.setScopes(scope1);
    }
    return uriTemplate;
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate)

Example 78 with Scope

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

the class OAuthClient method getTokenResponse.

/**
 * Method to retrieve the token response sent from the backend
 * @param response CloseableHttpResponse object
 * @return TokenResponse object containing the details retrieved from the backend
 * @throws APIManagementException In the event of an unexpected HTTP status code from the backend
 * @throws IOException In the event of a problem parsing the response from the backend
 */
private static TokenResponse getTokenResponse(CloseableHttpResponse response) throws APIManagementException, IOException, ParseException {
    int responseCode = response.getStatusLine().getStatusCode();
    if (!(responseCode == HttpStatus.SC_OK)) {
        throw new APIManagementException("Error while accessing the Token URL. " + "Found http status " + response.getStatusLine());
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
    String inputLine;
    StringBuilder stringBuilder = new StringBuilder();
    while ((inputLine = reader.readLine()) != null) {
        stringBuilder.append(inputLine);
    }
    JSONParser parser = new JSONParser();
    JSONObject jsonResponse = (JSONObject) parser.parse(stringBuilder.toString());
    TokenResponse tokenResponse = new TokenResponse();
    if (jsonResponse.containsKey("access_token")) {
        tokenResponse.setAccessToken((String) jsonResponse.get("access_token"));
        if (jsonResponse.containsKey("refresh_token")) {
            tokenResponse.setRefreshToken((String) jsonResponse.get("refresh_token"));
        }
        if (jsonResponse.containsKey("scope")) {
            Set<String> scopeSet = Stream.of(jsonResponse.get("scope").toString().trim().split("\\s*,\\s*")).collect(Collectors.toSet());
            tokenResponse.setScope(scopeSet);
        }
        if (jsonResponse.containsKey("token_type")) {
            tokenResponse.setTokenType((String) jsonResponse.get("token_type"));
        }
        if (jsonResponse.containsKey("expires_in")) {
            tokenResponse.setExpiresIn(jsonResponse.get("expires_in").toString());
            long currentTimeInSeconds = System.currentTimeMillis() / 1000;
            long expiryTimeInSeconds = currentTimeInSeconds + Long.parseLong(tokenResponse.getExpiresIn());
            tokenResponse.setValidTill(expiryTimeInSeconds);
        } else if (null != APIUtil.getMediationConfigurationFromAPIMConfig(APIConstants.OAuthConstants.OAUTH_MEDIATION_CONFIG + APIConstants.OAuthConstants.EXPIRES_IN_CONFIG)) {
            tokenResponse.setExpiresIn(APIUtil.getMediationConfigurationFromAPIMConfig(APIConstants.OAuthConstants.OAUTH_MEDIATION_CONFIG + APIConstants.OAuthConstants.EXPIRES_IN_CONFIG));
            long currentTimeInSeconds = System.currentTimeMillis() / 1000;
            long expiryTimeInSeconds = currentTimeInSeconds + Long.parseLong(tokenResponse.getExpiresIn());
            tokenResponse.setValidTill(expiryTimeInSeconds);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Response: [status-code] " + responseCode + " [message] " + stringBuilder.toString());
    }
    if (tokenResponse.getAccessToken() != null) {
        return tokenResponse;
    } else {
        return null;
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) InputStreamReader(java.io.InputStreamReader) JSONObject(org.json.simple.JSONObject) BufferedReader(java.io.BufferedReader) JSONParser(org.json.simple.parser.JSONParser)

Example 79 with Scope

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

the class APIMappingUtil method fromDTOtoAPIProduct.

public static APIProduct fromDTOtoAPIProduct(APIProductDTO dto, String provider) throws APIManagementException {
    APIProduct product = new APIProduct();
    APIProductIdentifier id = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), dto.getName(), // todo: replace this with dto.getVersion
    APIConstants.API_PRODUCT_VERSION);
    product.setID(id);
    product.setUuid(dto.getId());
    product.setDescription(dto.getDescription());
    String context = dto.getContext();
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    context = context.startsWith("/") ? context : ("/" + context);
    String providerDomain = MultitenantUtils.getTenantDomain(provider);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain) && dto.getId() == null) {
        // Create tenant aware context for API
        context = "/t/" + providerDomain + context;
    }
    product.setType(APIConstants.API_PRODUCT_IDENTIFIER_TYPE.replaceAll("\\s", ""));
    product.setContext(context);
    context = checkAndSetVersionParam(context);
    product.setContextTemplate(context);
    List<String> apiProductTags = dto.getTags();
    Set<String> tagsToReturn = new HashSet<>(apiProductTags);
    product.addTags(tagsToReturn);
    if (dto.isEnableSchemaValidation() != null) {
        product.setEnableSchemaValidation(dto.isEnableSchemaValidation());
    }
    product.setEnableStore(true);
    if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
        product.setResponseCache(APIConstants.ENABLED);
    } else {
        product.setResponseCache(APIConstants.DISABLED);
    }
    if (dto.getCacheTimeout() != null) {
        product.setCacheTimeout(dto.getCacheTimeout());
    } else {
        product.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
    }
    if (dto.getBusinessInformation() != null) {
        product.setBusinessOwner(dto.getBusinessInformation().getBusinessOwner());
        product.setBusinessOwnerEmail(dto.getBusinessInformation().getBusinessOwnerEmail());
        product.setTechnicalOwner(dto.getBusinessInformation().getTechnicalOwner());
        product.setTechnicalOwnerEmail(dto.getBusinessInformation().getTechnicalOwnerEmail());
    }
    Set<Tier> apiTiers = new HashSet<>();
    List<String> tiersFromDTO = dto.getPolicies();
    if (dto.getVisibility() != null) {
        product.setVisibility(mapVisibilityFromDTOtoAPIProduct(dto.getVisibility()));
    }
    if (dto.getVisibleRoles() != null) {
        String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
        product.setVisibleRoles(visibleRoles);
    }
    if (dto.getVisibleTenants() != null) {
        String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
        product.setVisibleTenants(visibleTenants);
    }
    List<String> accessControlRoles = dto.getAccessControlRoles();
    if (accessControlRoles == null || accessControlRoles.isEmpty()) {
        product.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
        product.setAccessControlRoles("null");
    } else {
        product.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
        product.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
    }
    for (String tier : tiersFromDTO) {
        apiTiers.add(new Tier(tier));
    }
    product.setAvailableTiers(apiTiers);
    product.setProductLevelPolicy(dto.getApiThrottlingPolicy());
    product.setGatewayVendor(dto.getGatewayVendor());
    if (dto.getSubscriptionAvailability() != null) {
        product.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPIProduct(dto.getSubscriptionAvailability()));
    }
    List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
    if (additionalProperties != null) {
        for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
            if (property.isDisplay()) {
                product.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
            } else {
                product.addProperty(property.getName(), property.getValue());
            }
        }
    }
    if (dto.getSubscriptionAvailableTenants() != null) {
        product.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
    }
    String transports = StringUtils.join(dto.getTransport(), ',');
    product.setTransports(transports);
    List<APIProductResource> productResources = new ArrayList<APIProductResource>();
    Set<String> verbResourceCombo = new HashSet<>();
    for (ProductAPIDTO res : dto.getApis()) {
        List<APIOperationsDTO> productAPIOperationsDTO = res.getOperations();
        for (APIOperationsDTO resourceItem : productAPIOperationsDTO) {
            if (!verbResourceCombo.add(resourceItem.getVerb() + resourceItem.getTarget())) {
                throw new APIManagementException("API Product resource: " + resourceItem.getTarget() + ", with verb: " + resourceItem.getVerb() + " , is duplicated for id " + id, ExceptionCodes.from(ExceptionCodes.API_PRODUCT_DUPLICATE_RESOURCE, resourceItem.getTarget(), resourceItem.getVerb()));
            }
            URITemplate template = new URITemplate();
            template.setHTTPVerb(resourceItem.getVerb());
            template.setHttpVerbs(resourceItem.getVerb());
            template.setResourceURI(resourceItem.getTarget());
            template.setUriTemplate(resourceItem.getTarget());
            template.setOperationPolicies(OperationPolicyMappingUtil.fromDTOToAPIOperationPoliciesList(resourceItem.getOperationPolicies()));
            APIProductResource resource = new APIProductResource();
            resource.setApiId(res.getApiId());
            resource.setUriTemplate(template);
            productResources.add(resource);
        }
    }
    Set<Scope> scopes = getScopes(dto);
    product.setScopes(scopes);
    APICorsConfigurationDTO apiCorsConfigurationDTO = dto.getCorsConfiguration();
    CORSConfiguration corsConfiguration;
    if (apiCorsConfigurationDTO != null) {
        corsConfiguration = new CORSConfiguration(apiCorsConfigurationDTO.isCorsConfigurationEnabled(), apiCorsConfigurationDTO.getAccessControlAllowOrigins(), apiCorsConfigurationDTO.isAccessControlAllowCredentials(), apiCorsConfigurationDTO.getAccessControlAllowHeaders(), apiCorsConfigurationDTO.getAccessControlAllowMethods());
    } else {
        corsConfiguration = APIUtil.getDefaultCorsConfiguration();
    }
    product.setCorsConfiguration(corsConfiguration);
    product.setProductResources(productResources);
    product.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
    product.setAuthorizationHeader(dto.getAuthorizationHeader());
    // attach api categories to API model
    setAPICategoriesToModel(dto, product, provider);
    return product;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) ArrayList(java.util.ArrayList) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 80 with Scope

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

the class ScopesApiServiceImpl method deleteSharedScope.

/**
 * Delete shared scope.
 *
 * @param scopeId        Scope UUID
 * @param messageContext CXF Message Context
 * @return Deletion Response
 * @throws APIManagementException If an error occurs while deleting shared scope
 */
@Override
public Response deleteSharedScope(String scopeId, MessageContext messageContext) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    if (StringUtils.isEmpty(scopeId)) {
        throw new APIManagementException("Scope Id cannot be null or empty", ExceptionCodes.SHARED_SCOPE_ID_NOT_SPECIFIED);
    }
    Scope existingScope = apiProvider.getSharedScopeByUUID(scopeId, tenantDomain);
    if (apiProvider.isScopeKeyAssignedToAPI(existingScope.getKey(), tenantDomain)) {
        throw new APIManagementException("Cannot remove the Shared Scope " + scopeId + " as it is used by one " + "or more APIs", ExceptionCodes.from(ExceptionCodes.SHARED_SCOPE_ALREADY_ATTACHED, scopeId));
    }
    apiProvider.deleteSharedScope(existingScope.getKey(), tenantDomain);
    return Response.ok().build();
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Aggregations

Scope (org.wso2.carbon.apimgt.api.model.Scope)97 HashMap (java.util.HashMap)76 ArrayList (java.util.ArrayList)58 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)50 Scope (org.wso2.carbon.apimgt.core.models.Scope)41 Map (java.util.Map)39 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)39 LinkedHashSet (java.util.LinkedHashSet)32 LinkedHashMap (java.util.LinkedHashMap)29 HashSet (java.util.HashSet)26 RestVariable (org.wso2.carbon.bpmn.rest.engine.variable.RestVariable)25 List (java.util.List)24 Test (org.testng.annotations.Test)23 JSONObject (org.json.simple.JSONObject)22 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)19 PreparedStatement (java.sql.PreparedStatement)17 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)17 SQLException (java.sql.SQLException)16 Gson (com.google.gson.Gson)15 Connection (java.sql.Connection)15