Search in sources :

Example 66 with Group

use of org.wso2.charon3.core.objects.Group in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createDefaultSiddhiAppForAPIThrottlePolicy.

public static String createDefaultSiddhiAppForAPIThrottlePolicy() {
    APIPolicy apiPolicy = createDefaultAPIPolicy();
    String siddhiApp = "\n@App:name('resource_" + apiPolicy.getPolicyName() + "_condition_0')" + "\n@App:description('ExecutionPlan for resource_" + apiPolicy.getPolicyName() + "_condition_0')\n" + "\n@source(type='inMemory', topic='apim', @map(type='passThrough'))" + "\ndefine stream RequestStream (messageID string, appKey string, appTier string, " + "subscriptionKey string," + " apiKey string, apiTier string, subscriptionTier string, resourceKey string," + " resourceTier string, userId string,  apiContext string, apiVersion string, " + "appTenant string, apiTenant " + "string, appId string, apiName string, propertiesMap string);\n" + "\n@sink(type='jms', @map(type='text')," + "\nfactory.initial='org.wso2.andes.jndi.PropertiesFileInitialContextFactory'," + " provider.url='tcp://localhost:5672', " + "destination='TEST.FOO', connection.factory.type='topic'," + "\nconnection.factory.jndi.name='TopicConnectionFactory')" + "\ndefine stream GlobalThrottleStream (throttleKey string, isThrottled bool," + " expiryTimeStamp long);\n" + "\nFROM RequestStream" + "\nSELECT messageID, (resourceTier == 'SampleAPIPolicy' AND (regex:find('Chrome'," + "cast(map:get(propertiesMap,'Browser')," + "'string'))) AND (regex:find('attributed'," + "cast(map:get(propertiesMap,'/path/path2'),'string'))) AND " + "(cast(map:get(propertiesMap,'Location'),'string')=='Colombo'))" + " AS isEligible, str:concat(resourceKey," + "'_condition_0') AS throttleKey, propertiesMap" + "\nINSERT INTO EligibilityStream;\n" + "\nFROM EligibilityStream[isEligible==true]#throttler:timeBatch(1 s, 0)" + "\nselect throttleKey, (count(messageID) >= 1000) as isThrottled," + " expiryTimeStamp group by throttleKey" + "\nINSERT ALL EVENTS into ResultStream;\n" + "\nfrom ResultStream#throttler:emitOnStateChange(throttleKey, isThrottled)" + "\nselect *" + "\ninsert into GlobalThrottleStream;\n";
    return siddhiApp;
}
Also used : APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy)

Example 67 with Group

use of org.wso2.charon3.core.objects.Group in project carbon-apimgt by wso2.

the class SampleTestObjectCreator method createDefaultSiddhiAppforSubscriptionPolicy.

public static String createDefaultSiddhiAppforSubscriptionPolicy() {
    SubscriptionPolicy policy = createDefaultSubscriptionPolicy();
    RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
    String siddhiApp = "@App:name('subscription_" + policy.getPolicyName() + "')\n" + "\n@App:description('ExecutionPlan for subscription_" + policy.getPolicyName() + "')\n" + "\n@source(type='inMemory', topic='apim', @map(type='passThrough'))\n" + "define stream RequestStream (messageID string, appKey string, appTier string," + " subscriptionKey string," + " apiKey string, apiTier string, subscriptionTier string, resourceKey string, resourceTier string," + " userId string,  apiContext string, apiVersion string, appTenant string, apiTenant string, " + "appId string, apiName string, propertiesMap string);\n" + "\n@sink(type='jms', @map(type='text'),\n" + "factory.initial='org.wso2.andes.jndi.PropertiesFileInitialContextFactory'," + " provider.url='tcp://localhost:5672', destination='TEST.FOO', connection.factory." + "type='topic',\n" + "connection.factory.jndi.name='TopicConnectionFactory')\n" + "define stream GlobalThrottleStream (throttleKey string, isThrottled bool" + ", expiryTimeStamp long);\n" + "\nFROM RequestStream\n" + "SELECT messageID, (subscriptionTier == '" + policy.getPolicyName() + "')" + " AS isEligible, subscriptionKey AS throttleKey, propertiesMap\n" + "INSERT INTO EligibilityStream;\n" + "\nFROM EligibilityStream[isEligible==true]#throttler:timeBatch(" + policy.getDefaultQuotaPolicy().getLimit().getUnitTime() + " " + policy.getDefaultQuotaPolicy().getLimit().getTimeUnit() + ", 0)\n" + "select throttleKey, (count(messageID) >= " + limit.getRequestCount() + ")" + " as isThrottled, expiryTimeStamp group by throttleKey\n" + "INSERT ALL EVENTS into ResultStream;\n" + "\nfrom ResultStream#throttler:emitOnStateChange(throttleKey, isThrottled)" + " select * " + "insert into GlobalThrottleStream;\n";
    return siddhiApp;
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)

Example 68 with Group

use of org.wso2.charon3.core.objects.Group in project carbon-apimgt by wso2.

the class ApiDAOImplIT method testGetAPIsWhenUserIsProvider.

@Test(description = "Tests getting the APIs when the user is the provider of the API")
public void testGetAPIsWhenUserIsProvider() throws Exception {
    ApiDAO apiDAO = DAOFactory.getApiDAO();
    Set<String> rolesOfUser = new HashSet<>();
    // The ID here is the group ID of the provider of the API. This ID is not assigned permissions for the API
    rolesOfUser.add(ALTERNATIVE_USER_ROLE_ID);
    // But this user is the provider of the API
    List<API> apiList = apiDAO.getAPIs(rolesOfUser, ADMIN);
    Assert.assertTrue(apiList.isEmpty());
    API.APIBuilder builder = SampleTestObjectCreator.createDefaultAPI();
    API api1 = builder.build();
    testAddGetEndpoint();
    apiDAO.addAPI(api1);
    apiList = apiDAO.getAPIs(rolesOfUser, ADMIN);
    List<API> expectedAPIs = new ArrayList<>();
    expectedAPIs.add(SampleTestObjectCreator.copyAPISummary(api1));
    // The provider will have all permissions for the API by default
    Assert.assertTrue(apiList.size() == 1);
    Assert.assertTrue(APIUtils.isListsEqualIgnoreOrder(apiList, expectedAPIs, new APIComparator()), TestUtil.printDiff(apiList, expectedAPIs));
}
Also used : ArrayList(java.util.ArrayList) APIComparator(org.wso2.carbon.apimgt.core.util.APIComparator) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 69 with Group

use of org.wso2.charon3.core.objects.Group in project carbon-apimgt by wso2.

the class CommonThrottleMappingUtil method fromPipelineToConditionalGroupDTO.

/**
 * Converts a single Pipeline object into a Conditional Group DTO object
 *
 * @param pipeline Pipeline object
 * @return Derived DTO object from Pipeline object
 * @throws UnsupportedThrottleLimitTypeException - If error occurs
 * @throws UnsupportedThrottleConditionTypeException - If error occurs
 */
public static ConditionalGroupDTO fromPipelineToConditionalGroupDTO(Pipeline pipeline) throws UnsupportedThrottleLimitTypeException, UnsupportedThrottleConditionTypeException {
    ConditionalGroupDTO groupDTO = new ConditionalGroupDTO();
    groupDTO.setDescription(pipeline.getDescription());
    groupDTO.setLimit(fromQuotaPolicyToDTO(pipeline.getQuotaPolicy()));
    List<ThrottleConditionDTO> conditionDTOList = fromConditionListToDTOList(pipeline.getConditions());
    groupDTO.setConditions(conditionDTOList);
    return groupDTO;
}
Also used : ConditionalGroupDTO(org.wso2.carbon.apimgt.rest.api.admin.dto.ConditionalGroupDTO) ThrottleConditionDTO(org.wso2.carbon.apimgt.rest.api.admin.dto.ThrottleConditionDTO)

Example 70 with Group

use of org.wso2.charon3.core.objects.Group in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetRoleId.

@Test
public void testGetRoleId() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validRoleName = "engineer";
    final String validRoleSearchQuery = "displayName Eq " + validRoleName;
    final String expectedRoleId = "ac093278-9343-466c-8a71-af47921a575b";
    String invalidRoleName = "invalid_role";
    final String invalidRoleSearchQuery = "displayName Eq " + invalidRoleName;
    String roleReturningNullResponse = "invalid_user_giving_null_response";
    final String roleReturningNullResponseSearchQuery = "displayName Eq " + roleReturningNullResponse;
    // happy path
    String responseBody = "{\"totalResults\":1,\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"Resources\":" + "[{\"displayName\":\"PRIMARY/engineer\",\"meta\":{\"created\":\"2017-06-02T10:14:42\"," + "\"location\":\"https://localhost:9443/wso2/scim/Groups/ac093278-9343-466c-8a71-af47921a575b\"," + "\"lastModified\":\"2017-06-02T10:14:42\"},\"id\":\"ac093278-9343-466c-8a71-af47921a575b\"}]}";
    Response createdResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(responseBody.getBytes()).build();
    Mockito.when(scimServiceStub.searchGroups(validRoleSearchQuery)).thenReturn(createdResponse);
    try {
        String roleId = idpImpl.getRoleId(validRoleName);
        Assert.assertEquals(roleId, expectedRoleId);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error path
    // Assuming the role cannot be found - when returning a not 200 response
    String errorResponseBody = "{\"Errors\":[{\"code\":\"404\",\"description\":\"Group not found in the user store.\"}]}";
    Response createdResponseNoSuchRole = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.searchGroups(invalidRoleSearchQuery)).thenReturn(createdResponseNoSuchRole);
    try {
        idpImpl.getRoleId(invalidRoleName);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of role " + invalidRoleName + ". Error : Group not found in the user store.");
    }
    // error path
    // Assuming the response is null
    Mockito.when(scimServiceStub.searchGroups(roleReturningNullResponseSearchQuery)).thenReturn(null);
    try {
        idpImpl.getRoleId(roleReturningNullResponse);
    } catch (Exception ex) {
        Assert.assertTrue(ex instanceof IdentityProviderException);
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving Id of role " + roleReturningNullResponse + ". Error : Response is null.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)128 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)97 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)94 Event (org.wso2.siddhi.core.event.Event)87 InputHandler (org.wso2.siddhi.core.stream.input.InputHandler)78 QueryCallback (org.wso2.siddhi.core.query.output.callback.QueryCallback)51 Query (org.wso2.siddhi.query.api.execution.query.Query)17 ArrayList (java.util.ArrayList)16 CharonException (org.wso2.charon3.core.exceptions.CharonException)15 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)13 StreamCallback (org.wso2.siddhi.core.stream.output.StreamCallback)12 HashMap (java.util.HashMap)8 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)8 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)8 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)7 UserManager (org.wso2.charon3.core.extensions.UserManager)7 Group (org.wso2.charon3.core.objects.Group)7 ApiOperation (io.swagger.annotations.ApiOperation)6 ApiResponses (io.swagger.annotations.ApiResponses)6 Produces (javax.ws.rs.Produces)6