org.wso2.carbon.apimgt.api.model.URITemplate Java Examples

The following examples show how to use org.wso2.carbon.apimgt.api.model.URITemplate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: APIKeyValidationService.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public ArrayList<URITemplate> getAPIProductURITemplates(String context, String version)
        throws APIManagementException {
    Timer timer6 = MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO, MetricManager.name(
            APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "GET_URI_TEMPLATE"));
    Timer.Context timerContext6 = timer6.start();
    if (log.isDebugEnabled()) {
        log.debug("getAllURITemplates request from gateway to keymanager: requestTime="
                + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date())
                + " ,for:" + context);
    }
    ArrayList<URITemplate> templates = getTemplates(context, version);
    if (log.isDebugEnabled()) {
        log.debug("getAllURITemplates response from keyManager to gateway for:" + context + " at "
                + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
    }
    timerContext6.stop();
    return templates;
}
 
Example #2
Source File: APIAuthenticationAdminClient.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public void invalidateResourceCache(String apiContext, String apiVersion, Set<URITemplate> uriTemplates) {

        JSONObject api = new JSONObject();
        api.put("apiContext", apiContext);
        api.put("apiVersion", apiVersion);
        JSONArray resources = new JSONArray();
        for (URITemplate uriTemplate : uriTemplates) {
            JSONObject resource = new JSONObject();
            resource.put("resourceURLContext", uriTemplate.getUriTemplate());
            resource.put("httpVerb", uriTemplate.getHTTPVerb());
            resources.add(resource);
        }
        api.put("resources", resources);

        Object[] objectData = new Object[]{APIConstants.RESOURCE_CACHE_NAME, api.toJSONString()};
        log.debug("Sending Resource Invalidation Message");
        Event event = new Event(APIConstants.CACHE_INVALIDATION_STREAM_ID, System.currentTimeMillis(),
                null, null, objectData);
        APIUtil.publishEventToEventHub(null, event);
    }
 
Example #3
Source File: AMDefaultKeyManagerImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method will be used to update the local scopes and resource to scope attachments of an API in the
 * authorization server.
 *
 * @param api               API
 * @param oldLocalScopeKeys Old local scopes of the API before update (excluding the versioned local scopes
 * @param newLocalScopes    New local scopes of the API after update
 * @param oldURITemplates   Old URI templates of the API before update
 * @param newURITemplates   New URI templates of the API after update
 * @throws APIManagementException if fails to update resources scopes
 */
@Override
public void updateResourceScopes(API api, Set<String> oldLocalScopeKeys, Set<Scope> newLocalScopes,
                                 Set<URITemplate> oldURITemplates, Set<URITemplate> newURITemplates)
        throws APIManagementException {

    detachResourceScopes(api, oldURITemplates);
    // remove the old local scopes from the KM
    for (String oldScope : oldLocalScopeKeys) {
        deleteScope(oldScope);
    }
    //Register scopes
    for (Scope scope : newLocalScopes) {
        String scopeKey = scope.getKey();
        // Check if key already registered in KM. Scope Key may be already registered for a different version.
        if (!isScopeExists(scopeKey)) {
            //register scope in KM
            registerScope(scope);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Scope: " + scopeKey + " already registered in KM. Skipping registering scope.");
            }
        }
    }
    attachResourceScopes(api, newURITemplates);
}
 
Example #4
Source File: GraphQLSchemaDefinition.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Extract GraphQL Operations from given schema
 * @param schema graphQL Schema
 * @return the arrayList of APIOperationsDTOextractGraphQLOperationList
 *
 */
public List<URITemplate> extractGraphQLOperationList(String schema, String type) {
    List<URITemplate> operationArray = new ArrayList<>();
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeRegistry = schemaParser.parse(schema);
    Map<java.lang.String, TypeDefinition> operationList = typeRegistry.types();
    for (Map.Entry<String, TypeDefinition> entry : operationList.entrySet()) {
        if (entry.getValue().getName().equals(APIConstants.GRAPHQL_QUERY) ||
                entry.getValue().getName().equals(APIConstants.GRAPHQL_MUTATION)
                || entry.getValue().getName().equals(APIConstants.GRAPHQL_SUBSCRIPTION)) {
            if (type == null) {
                addOperations(entry, operationArray);
            } else if (type.equals(entry.getValue().getName().toUpperCase())) {
                addOperations(entry, operationArray);
            }
        }
    }
    return operationArray;
}
 
Example #5
Source File: RestApiUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to get the URI template set for the relevant REST API using the given base path.
 *
 * @param basePath Base path of the REST API
 * @return Set of URI templates for the REST API
 */
public static Set<URITemplate> getURITemplatesForBasePath(String basePath) {
    Set<URITemplate> uriTemplates = new HashSet<>();
    //get URI templates using the base path in the request
    if (basePath.contains(RestApiConstants.REST_API_PUBLISHER_CONTEXT_FULL_0)) {
        uriTemplates = RestApiUtil.getPublisherAppResourceMapping(RestApiConstants.REST_API_PUBLISHER_VERSION_0);
    } else if (basePath.contains(RestApiConstants.REST_API_PUBLISHER_CONTEXT_FULL_1)) {
        uriTemplates = RestApiUtil.getPublisherAppResourceMapping(RestApiConstants.REST_API_PUBLISHER_VERSION_1);
    } else if (basePath.contains(RestApiConstants.REST_API_STORE_CONTEXT_FULL_0)) {
        uriTemplates = RestApiUtil.getStoreAppResourceMapping(RestApiConstants.REST_API_STORE_VERSION_0);
    } else if (basePath.contains(RestApiConstants.REST_API_STORE_CONTEXT_FULL_1)) {
        uriTemplates = RestApiUtil.getStoreAppResourceMapping(RestApiConstants.REST_API_STORE_VERSION_1);
    } else if (basePath.contains(RestApiConstants.REST_API_ADMIN_CONTEXT_FULL_0)) {
        uriTemplates = RestApiUtil.getAdminAPIAppResourceMapping(RestApiConstants.REST_API_ADMIN_VERSION_0);
    } else if (basePath.contains(RestApiConstants.REST_API_ADMIN_CONTEXT_FULL_1)) {
        uriTemplates = RestApiUtil.getAdminAPIAppResourceMapping(RestApiConstants.REST_API_ADMIN_VERSION_1);
    }
    return uriTemplates;
}
 
Example #6
Source File: RestApiUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public static Boolean checkETagSkipList(String path, String httpMethod) {
    //Check if the accessing URI is ETag skipped
    try {
        Dictionary<org.wso2.uri.template.URITemplate, List<String>> eTagSkipListToMethodsMap = RestApiUtil.getETagSkipListToMethodsMap();
        Enumeration<org.wso2.uri.template.URITemplate> uriTemplateSet = eTagSkipListToMethodsMap.keys();

        while (uriTemplateSet.hasMoreElements()) {
            org.wso2.uri.template.URITemplate uriTemplate = uriTemplateSet.nextElement();
            if (uriTemplate.matches(path, new HashMap<String, String>())) {
                List<String> ETagDisableHttpVerbs = eTagSkipListToMethodsMap.get(uriTemplate);
                return ETagDisableHttpVerbs.contains(httpMethod);
            }
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Unable to resolve ETag skip list in api-manager.xml", e, log);
    }
    return false;
}
 
Example #7
Source File: APIMgtDAOTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
 public void testAddAndConvertNullThrottlingTiers() throws APIManagementException {

     //Adding an API with a null THROTTLING_TIER should automatically convert it to Unlimited
     APIIdentifier apiIdentifier = new APIIdentifier("testAddAndGetApi", "testAddAndGetApi", "1.0.0");
     API api = new API(apiIdentifier);
     api.setContext("/testAddAndGetApi");
     api.setContextTemplate("/testAddAndGetApi/{version}");
     Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
     uriTemplates.add(getUriTemplate("/abc", "GET", "Any", "read", null));
     api.setUriTemplates(uriTemplates);
     api.setScopes(getScopes());
     api.setStatus(APIConstants.PUBLISHED);
     api.setAsDefaultVersion(true);
     int apiId = apiMgtDAO.addAPI(api, -1234);
     apiMgtDAO.addURITemplates(apiId, api, -1234);
     HashMap<String, String> result1 = apiMgtDAO.getURITemplatesPerAPIAsString(apiIdentifier);
     Assert.assertTrue(result1.containsKey("/abc::GET::Any::Unlimited::abcd defgh fff"));

     //Change the inserted throttling tier back to Null and test the convertNullThrottlingTier method
     updateThrottlingTierToNull();
     apiMgtDAO.convertNullThrottlingTiers();
     HashMap<String, String> result2 = apiMgtDAO.getURITemplatesPerAPIAsString(apiIdentifier);
     Assert.assertTrue(result2.containsKey("/abc::GET::Any::Unlimited::abcd defgh fff"));
}
 
Example #8
Source File: APIMgtDAOTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: WSAPIKeyDataStore.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@MethodStats
public ArrayList<URITemplate> getAPIProductURITemplates(String context, String apiVersion)
                                                                            throws APISecurityException {
    APIKeyValidatorClient client = null;
    try {
        client = clientPool.get();
        return client.getAPIProductURITemplates(context, apiVersion);
    } catch (Exception e) {
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
                "Error while accessing backend services for API key validation", e);
    } finally {
        try {
            if (client != null) {
                clientPool.release(client);
            }
        } catch (Exception exception) {
            if (log.isDebugEnabled()) {
                log.debug("Releasing client from client pool caused an exception = " + exception.getMessage());
            }
        }
    }
}
 
Example #10
Source File: APIKeyValidationService.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Return the URI Templates for an API
 *
 * @param context Requested context
 * @param version API Version
 * @return APIKeyValidationInfoDTO with authorization info and tier info if authorized. If it is not
 * authorized, tier information will be <pre>null</pre>
 * @throws APIKeyMgtException Error occurred when accessing the underlying database or registry.
 */
public ArrayList<URITemplate> getAllURITemplates(String context, String version)
        throws APIKeyMgtException, APIManagementException {
    Timer timer6 = MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO, MetricManager.name(
            APIConstants.METRICS_PREFIX, this.getClass().getSimpleName(), "GET_URI_TEMPLATE"));
    Timer.Context timerContext6 = timer6.start();
    if (log.isDebugEnabled()) {
        log.debug("getAllURITemplates request from gateway to keymanager: requestTime="
                + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date())
                + " ,for:" + context);
    }
    ArrayList<URITemplate> templates = getTemplates(context, version);
    if (log.isDebugEnabled()) {
        log.debug("getAllURITemplates response from keyManager to gateway for:" + context + " at "
                + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
    }
    timerContext6.stop();
    return templates;
}
 
Example #11
Source File: APIKeyValidator.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@MethodStats
protected ArrayList<URITemplate> getAPIProductURITemplates(MessageContext messageContext, String context, String apiVersion)
        throws APISecurityException {
    if (uriTemplates == null) {
        synchronized (this) {
            if (uriTemplates == null) {
                String swagger = (String) messageContext.getProperty(APIMgtGatewayConstants.OPEN_API_STRING);
                if (swagger != null) {
                    APIDefinition oasParser;
                    try {
                        oasParser = OASParserUtil.getOASParser(swagger);
                        uriTemplates = new ArrayList<>();
                        uriTemplates.addAll(oasParser.getURITemplates(swagger));
                        return uriTemplates;
                    } catch (APIManagementException e) {
                        log.error("Error while parsing swagger content to get URI Templates", e);
                    }
                }
                uriTemplates = dataStore.getAPIProductURITemplates(context, apiVersion);
            }
        }
    }
    return uriTemplates;
}
 
Example #12
Source File: OASTestBase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public void testGenerateAPIDefinition(APIDefinition parser) throws Exception {
    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)));

    String definition = parser.generateAPIDefinition(new SwaggerData(api));
    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(1, uriTemplates.size());
    Assert.assertTrue(uriTemplates.contains(petGet));

    Set<Scope> scopes = parser.getScopes(definition);
    Assert.assertEquals(2, scopes.size());
    Assert.assertTrue(scopes.contains(sampleScope));
    Assert.assertTrue(scopes.contains(extensionScope));
}
 
Example #13
Source File: WSAPIKeyDataStore.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@MethodStats
public ArrayList<URITemplate> getAllURITemplates(String context, String apiVersion
)
        throws APISecurityException {
    APIKeyValidatorClient client = null;
    try {
        client = clientPool.get();
        return client.getAllURITemplates(context, apiVersion);
    } catch (Exception e) {
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
                                       "Error while accessing backend services for API key validation", e);
    } finally {
        try {
            if (client != null) {
                clientPool.release(client);
            }
        } catch (Exception exception) {
            if (log.isDebugEnabled()) {
                log.debug("Releasing client from client pool caused an exception = " + exception.getMessage());
            }
        }
    }
}
 
Example #14
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the scopes to the URL template object using the given list of scopes
 *
 * @param template URL template
 * @param resourceScopes   list of scopes of the resource
 * @param apiScopes set of scopes defined for the API
 * @return URL template after setting the scopes
 */
public static URITemplate setScopesToTemplate(URITemplate template, List<String> resourceScopes,
                                              Set<Scope> apiScopes) throws APIManagementException {

    for (String scopeName : resourceScopes) {
        Scope scope = APIUtil.findScopeByKey(apiScopes, scopeName);
        if (scope == null) {
            throw new APIManagementException("Resource Scope '" + scopeName + "' not found.");
        }
        template.setScopes(scope);
    }
    return template;
}
 
Example #15
Source File: APIProductImportUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method filter the invalid resources in the API Product by matching with the URI Templates of a particular
 * dependent API.
 *
 * @param apiUriTemplates         URI Templates of the dependent API (either inside the import directory or already inside the APIM)
 * @param apiProductResource      API Product Resource
 * @param productResources        API Product Resources list to be filtered
 */
private static void filterInvalidProductResources(Set<URITemplate> apiUriTemplates, APIProductResource apiProductResource,
                                                                       List<APIProductResource> productResources) {
    for (URITemplate apiUriTemplate: apiUriTemplates) {
        URITemplate apiProductUriTemplate = apiProductResource.getUriTemplate();
        if (StringUtils.equals(apiProductUriTemplate.getHTTPVerb(), apiUriTemplate.getHTTPVerb()) &&
                StringUtils.equals(apiProductUriTemplate.getUriTemplate(), apiUriTemplate.getUriTemplate())) {
            // If the URI Template is Available in the API, remove it from the list since it is valid
            productResources.remove(apiProductResource);
        }
    }
}
 
Example #16
Source File: ResourceConfigContext.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public VelocityContext getContext() {
    VelocityContext context = super.getContext();

    if (api != null) {
        context.put("resources", api.getUriTemplates());
        context.put("apiStatus", api.getStatus());
        context.put("faultSequence", faultSeqExt != null ? faultSeqExt : api.getFaultSequence());
    } else if (apiProduct != null) {
        //Here we aggregate duplicate resourceURIs of an API and populate httpVerbs set in the uri template
        List<APIProductResource> productResources = apiProduct.getProductResources();
        List<APIProductResource> aggregateResources = new ArrayList<APIProductResource>();
        List<String> uriTemplateNames = new ArrayList<String>();

        for (APIProductResource productResource : productResources) {
            URITemplate uriTemplate = productResource.getUriTemplate();
            String productResourceKey = productResource.getApiIdentifier() + ":" + uriTemplate.getUriTemplate();
            if (uriTemplateNames.contains(productResourceKey)) {
                for (APIProductResource resource : aggregateResources) {
                    String resourceKey = resource.getApiIdentifier() + ":" + resource.getUriTemplate().getUriTemplate();
                    if (resourceKey.equals(productResourceKey)) {
                        resource.getUriTemplate().setHttpVerbs(uriTemplate.getHTTPVerb());
                    }
                }
            } else {
                uriTemplate.setHttpVerbs(uriTemplate.getHTTPVerb());
                aggregateResources.add(productResource);
                uriTemplateNames.add(productResourceKey);
            }
        }

        context.put("apiStatus", apiProduct.getState());
        context.put("aggregates", aggregateResources);
    }

    return context;  //To change body of implemented methods use File | Settings | File Templates.
}
 
Example #17
Source File: OASTestBase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
protected URITemplate getUriTemplate(String httpVerb, String authType, String uriTemplateString) {
    URITemplate uriTemplate = new URITemplate();
    uriTemplate.setAuthTypes(authType);
    uriTemplate.setAuthType(authType);
    uriTemplate.setHTTPVerb(httpVerb);
    uriTemplate.setHttpVerbs(httpVerb);
    uriTemplate.setUriTemplate(uriTemplateString);
    uriTemplate.setThrottlingTier("Unlimited");
    uriTemplate.setThrottlingTiers("Unlimited");
    uriTemplate.setScope(null);
    return uriTemplate;
}
 
Example #18
Source File: GraphQLSchemaDefinition.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param entry Entry
 * @param operationArray operationArray
 */
private void addOperations(Map.Entry<String, TypeDefinition> entry, List<URITemplate> operationArray) {
    for (FieldDefinition fieldDef : ((ObjectTypeDefinition) entry.getValue()).getFieldDefinitions()) {
        URITemplate operation = new URITemplate();
        operation.setHTTPVerb(entry.getKey());
        operation.setUriTemplate(fieldDef.getName());
        operationArray.add(operation);
    }
}
 
Example #19
Source File: OASTestBase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public String testGenerateAPIDefinitionWithExtension(APIDefinition parser, String content) throws Exception {
    JSONObject jsonObject = new JSONObject(content);
    String equalNoOfResourcesWithExtension = jsonObject.getJSONObject("equalNoOfResourcesWithExtension").toString();

    Scope newScope = new Scope();
    newScope.setName("newScope");
    newScope.setKey("newScope");
    newScope.setRoles("admin");
    newScope.setDescription("newScopeDescription");

    URITemplate updatedItemGet = new URITemplate();
    updatedItemGet.setUriTemplate("/items");
    updatedItemGet.setAuthType("Application & Application User");
    updatedItemGet.setAuthTypes("Application & Application User");
    updatedItemGet.setHTTPVerb("GET");
    updatedItemGet.setHttpVerbs("GET");
    updatedItemGet.setThrottlingTier("Unlimited");
    updatedItemGet.setThrottlingTiers("Unlimited");
    updatedItemGet.setScope(newScope);
    updatedItemGet.setScopes(newScope);

    APIIdentifier identifier = new APIIdentifier("admin", "simple", "1.0.0");
    API api = new API(identifier);
    api.setScopes(new HashSet<>(Arrays.asList(sampleScope, extensionScope, newScope)));
    api.setUriTemplates(new HashSet<>(Arrays.asList(petPost, updatedItemGet)));

    String definition = parser.generateAPIDefinition(new SwaggerData(api), equalNoOfResourcesWithExtension);
    APIDefinitionValidationResponse response = parser.validateAPIDefinition(definition, false);
    Assert.assertTrue(response.isValid());
    return definition;
}
 
Example #20
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static void readPathsAndScopes(PathItem srcPathItem, URITemplate uriTemplate,
                                       final Set<Scope> allScopes, SwaggerUpdateContext context) {
    Map<PathItem.HttpMethod, Operation> srcOperations = srcPathItem.readOperationsMap();

    PathItem.HttpMethod httpMethod = PathItem.HttpMethod.valueOf(uriTemplate.getHTTPVerb().toUpperCase());
    Operation srcOperation = srcOperations.get(httpMethod);

    Paths paths = context.getPaths();
    Set<Scope> aggregatedScopes = context.getAggregatedScopes();

    if (!paths.containsKey(uriTemplate.getUriTemplate())) {
        paths.put(uriTemplate.getUriTemplate(), new PathItem());
    }

    PathItem pathItem = paths.get(uriTemplate.getUriTemplate());
    pathItem.operation(httpMethod, srcOperation);

    readReferenceObjects(srcOperation, context);

    List<SecurityRequirement> srcOperationSecurity = srcOperation.getSecurity();
    if (srcOperationSecurity != null) {
        for (SecurityRequirement requirement : srcOperationSecurity) {
            List<String> scopes = requirement.get(OAS3Parser.OPENAPI_SECURITY_SCHEMA_KEY);
            if (scopes != null) {
                for (String scopeKey : scopes) {
                    for (Scope scope : allScopes) {
                        if (scope.getKey().equals(scopeKey)) {
                            aggregatedScopes.add(scope);
                        }
                    }
                }
            }
        }
    }
}
 
Example #21
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private HashMap<String, String> getURLTemplatePattern(Set<URITemplate> uriTemplates) {
    HashMap<String, String> pattern = new HashMap<String, String>();

    for (URITemplate uriTemplate : uriTemplates) {
        String key = uriTemplate.getUriTemplate() + "::" + uriTemplate.getHTTPVerb() + "::" +
                uriTemplate.getAuthType() + "::" + uriTemplate.getThrottlingTier();
        pattern.put(key, uriTemplate.getHTTPVerb());
    }

    return pattern;
}
 
Example #22
Source File: OASTestBase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public void testGetURITemplates(APIDefinition parser, String content) throws Exception {
    JSONObject jsonObject = new JSONObject(content);

    URITemplate exUriTemplate = new URITemplate();
    exUriTemplate.setUriTemplate("/pets");
    exUriTemplate.setAuthType("Application & Application User");
    exUriTemplate.setAuthTypes("Application & Application User");
    exUriTemplate.setHTTPVerb("GET");
    exUriTemplate.setHttpVerbs("GET");
    exUriTemplate.setThrottlingTier("Unlimited");
    exUriTemplate.setThrottlingTiers("Unlimited");
    exUriTemplate.setScope(extensionScope);
    exUriTemplate.setScopes(extensionScope);

    String scopesOnlyInSecurity = jsonObject.getJSONObject("scopesOnlyInSecurity").toString();
    Set<URITemplate> uriTemplates = parser.getURITemplates(scopesOnlyInSecurity);
    Assert.assertEquals(1, uriTemplates.size());
    Assert.assertTrue(uriTemplates.contains(petGet));

    String scopesOnlyInExtension = jsonObject.getJSONObject("scopesOnlyInExtension").toString();
    uriTemplates = parser.getURITemplates(scopesOnlyInExtension);
    Assert.assertEquals(1, uriTemplates.size());
    Assert.assertTrue(uriTemplates.contains(exUriTemplate));

    String scopesInExtensionAndSec = jsonObject.getJSONObject("scopesInExtensionAndSec").toString();
    uriTemplates = parser.getURITemplates(scopesInExtensionAndSec);
    Assert.assertEquals(1, uriTemplates.size());
    Assert.assertTrue(uriTemplates.contains(petGet));
}
 
Example #23
Source File: APIMgtDAOTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private Set<URITemplate> getUriTemplateSet() {
    Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
    uriTemplates.add(getUriTemplate("/abc", "GET", "Any", "read",
            "Unlimited"));
    uriTemplates.add(getUriTemplate("/abc", "GET", "Any", null,
            "Unlimited"));
    return uriTemplates;
}
 
Example #24
Source File: ResourceConfigContextTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private Set<URITemplate> setAPIUriTemplates(){
    Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
    URITemplate template = new URITemplate();
    template.setUriTemplate("/test");
    template.setHTTPVerb("GET");
    template.setThrottlingTier("Unlimited");
    template.setAuthType("Application");
    template.setResourceURI("http://maps.googleapis.com/maps/api/geocode/json?address=Colombo");
    template.setResourceSandboxURI("http://maps.googleapis.com/maps/api/geocode/json?address=Colombo");
    uriTemplates.add(template);
    return  uriTemplates;
}
 
Example #25
Source File: OAS2ParserTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetURITemplatesOfOpenAPI20Spec() throws Exception {
    String relativePath = "definitions" + File.separator + "oas2" + File.separator + "oas2_uri_template.json";
    String swagger = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");
    Set<URITemplate> uriTemplates = new LinkedHashSet<>();
    uriTemplates.add(getUriTemplate("POST", "Application User", "/*"));
    uriTemplates.add(getUriTemplate("GET", "Application", "/*"));
    uriTemplates.add(getUriTemplate("PUT", "None", "/*"));
    uriTemplates.add(getUriTemplate("DELETE", "Any", "/*"));
    uriTemplates.add(getUriTemplate("GET", "Application & Application User", "/abc"));
    Set<URITemplate> uriTemplateSet = oas2Parser.getURITemplates(swagger);
    Assert.assertEquals(uriTemplateSet, uriTemplates);
}
 
Example #26
Source File: OAS3ParserTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetURITemplatesOfOpenAPI300Spec() throws Exception {
    String relativePath = "definitions" + File.separator + "oas3" + File.separator + "oas3_uri_template.json";
    String openAPISpec300 =
            IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");
    Set<URITemplate> uriTemplates = new LinkedHashSet<>();
    uriTemplates.add(getUriTemplate("POST", "Application User", "/*"));
    uriTemplates.add(getUriTemplate("GET", "Application", "/*"));
    uriTemplates.add(getUriTemplate("PUT", "None", "/*"));
    uriTemplates.add(getUriTemplate("DELETE", "Any", "/*"));
    uriTemplates.add(getUriTemplate("GET", "Any", "/abc"));
    Set<URITemplate> uriTemplateSet = oas3Parser.getURITemplates(openAPISpec300);
    Assert.assertEquals(uriTemplateSet, uriTemplates);

}
 
Example #27
Source File: OAS3ParserTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testOpenApi3WithNonHttpVerbElementInPathItem() throws Exception {
    String relativePath = "definitions" + File.separator + "oas3" + File.separator + "oas3_non_httpverb.json";
    String openApi = IOUtils.toString(getClass().getClassLoader().getResourceAsStream(relativePath), "UTF-8");
    Set<URITemplate> expectedTemplates = new LinkedHashSet<>();
    expectedTemplates.add(getUriTemplate("GET", "Application", "/item"));
    Set<URITemplate> actualTemplates = oas3Parser.getURITemplates(openApi);
    Assert.assertEquals(actualTemplates, expectedTemplates);
}
 
Example #28
Source File: APIKeyValidator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private APIInfoDTO mapToAPIInfo(ArrayList<URITemplate> uriTemplates, String context, String apiVersion) {
    APIInfoDTO apiInfoDTO = new APIInfoDTO();

    apiInfoDTO.setApiName(context);
    apiInfoDTO.setContext(context);
    apiInfoDTO.setVersion(apiVersion);
    apiInfoDTO.setResources(new LinkedHashSet<ResourceInfoDTO>());

    ResourceInfoDTO resourceInfoDTO = null;
    VerbInfoDTO verbInfoDTO = null;

    // The following map is used to retrieve already created ResourceInfoDTO rather than iterating -
    // the resource Set in apiInfoDTO.
    LinkedHashMap<String, ResourceInfoDTO> resourcesMap = new LinkedHashMap<String, ResourceInfoDTO>();
    for (URITemplate uriTemplate : uriTemplates) {
        resourceInfoDTO = resourcesMap.get(uriTemplate.getUriTemplate());
        if (null == resourceInfoDTO) {
            resourceInfoDTO = new ResourceInfoDTO();
            resourceInfoDTO.setUrlPattern(uriTemplate.getUriTemplate());
            resourceInfoDTO.setHttpVerbs(new LinkedHashSet());
            apiInfoDTO.getResources().add(resourceInfoDTO);
            resourcesMap.put(uriTemplate.getUriTemplate(), resourceInfoDTO);
        }
        verbInfoDTO = new VerbInfoDTO();
        verbInfoDTO.setHttpVerb(uriTemplate.getHTTPVerb());
        verbInfoDTO.setAuthType(uriTemplate.getAuthType());
        verbInfoDTO.setThrottling(uriTemplate.getThrottlingTier());
        verbInfoDTO.setContentAware(uriTemplate.checkContentAwareFromThrottlingTiers());
        verbInfoDTO.setThrottlingConditions(uriTemplate.getThrottlingConditions());
        verbInfoDTO.setConditionGroups(uriTemplate.getConditionGroups());
        verbInfoDTO.setApplicableLevel(uriTemplate.getApplicableLevel());
        resourceInfoDTO.getHttpVerbs().add(verbInfoDTO);
    }

    return apiInfoDTO;
}
 
Example #29
Source File: APIKeyValidatorClient.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public ArrayList<URITemplate> getAllURITemplates(String context, String apiVersion
                                                ) throws APISecurityException {

    try {
        return apiKeyValidationService.getAllURITemplates(context, apiVersion);
    } catch (APIKeyMgtException | APIManagementException e) {
        log.error("Error while retrieving data from datastore", e);
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
                "Error while retrieving data from datastore", e);
    }
}
 
Example #30
Source File: APIKeyValidatorClient.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public ArrayList<URITemplate> getAPIProductURITemplates(String context, String apiVersion
                                                       ) throws APISecurityException {

    try {
        return apiKeyValidationService.getAPIProductURITemplates(context, apiVersion);
    } catch (APIManagementException e) {
        log.error("Error while retrieving data from datastore", e);
        throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
                "Error while retrieving data from datastore", e);
    }
}