Search in sources :

Example 86 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class APIPublisherImplTestCase method testAddResourceLevelEndpointWhileResourceEndpointAlreadyExistsWhileDatabaseFailure.

@Test(description = "Test add api with Api Specific Endpoint", expectedExceptions = { APIManagementException.class })
public void testAddResourceLevelEndpointWhileResourceEndpointAlreadyExistsWhileDatabaseFailure() throws APIManagementException, LifecycleException {
    /**
     * this test method verify the API Add with correct API object get invoked correctly
     */
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    Endpoint globalEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("testEndpoint").applicableLevel(APIMgtConstants.GLOBAL_ENDPOINT).build();
    Endpoint apiEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("apiEndpoint").applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Endpoint resourceEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("resourceEndpoint").applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Map<String, Endpoint> endpointMap = new HashMap();
    endpointMap.put(APIMgtConstants.PRODUCTION_ENDPOINT, globalEndpoint);
    endpointMap.put(APIMgtConstants.SANDBOX_ENDPOINT, apiEndpoint);
    Map<String, Endpoint> resourceEndpoints = new HashMap();
    resourceEndpoints.put(APIMgtConstants.SANDBOX_ENDPOINT, resourceEndpoint);
    Map<String, UriTemplate> uriTemplateMap = SampleTestObjectCreator.getMockUriTemplates();
    uriTemplateMap.forEach((k, v) -> {
        UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder(v);
        uriTemplateBuilder.endpoint(resourceEndpoints);
        uriTemplateMap.replace(k, uriTemplateBuilder.build());
    });
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().endpoint(endpointMap).uriTemplates(uriTemplateMap);
    Mockito.when(apiLifecycleManager.addLifecycle(APIMgtConstants.API_LIFECYCLE, USER)).thenReturn(new LifecycleState());
    APIGateway gateway = Mockito.mock(APIGateway.class);
    LabelDAO labelDao = Mockito.mock(LabelDAO.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(null, apiDAO, null, null, null, apiLifecycleManager, labelDao, null, null, null, gatewaySourceGenerator, gateway);
    Mockito.when(apiDAO.getEndpoint(globalEndpoint.getId())).thenReturn(globalEndpoint);
    Mockito.when(apiDAO.getEndpointByName(apiEndpoint.getName())).thenReturn(null);
    Mockito.when(apiDAO.getEndpointByName(resourceEndpoint.getName())).thenThrow(APIMgtDAOException.class);
    Mockito.when(apiDAO.isAPINameExists(apiBuilder.getName(), USER)).thenReturn(false);
    apiPublisher.addAPI(apiBuilder);
    Mockito.verify(apiDAO, Mockito.times(1)).addAPI(apiBuilder.build());
    Mockito.verify(apiDAO, Mockito.times(1)).getEndpointByName(apiEndpoint.getName());
    Mockito.verify(apiDAO, Mockito.times(1)).getEndpointByName(resourceEndpoint.getName());
}
Also used : HashMap(java.util.HashMap) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) WorkflowExtensionsConfigBuilder(org.wso2.carbon.apimgt.core.workflow.WorkflowExtensionsConfigBuilder) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) LabelDAO(org.wso2.carbon.apimgt.core.dao.LabelDAO) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) APILifecycleManager(org.wso2.carbon.apimgt.core.api.APILifecycleManager) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) Test(org.testng.annotations.Test)

Example 87 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class APIPublisherImplTestCase method testAddResourceLevelEndpointWhileResourceEndpointAlreadyExists.

@Test(description = "Test add api with Api Specific Endpoint", expectedExceptions = { APIManagementException.class })
public void testAddResourceLevelEndpointWhileResourceEndpointAlreadyExists() throws APIManagementException, LifecycleException {
    /**
     * this test method verify the API Add with correct API object get invoked correctly
     */
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    Endpoint globalEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("testEndpoint").applicableLevel(APIMgtConstants.GLOBAL_ENDPOINT).build();
    Endpoint apiEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("apiEndpoint").applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Endpoint resourceEndpoint = new Endpoint.Builder().id(UUID.randomUUID().toString()).name("resourceEndpoint").applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).build();
    Map<String, Endpoint> endpointMap = new HashMap();
    endpointMap.put(APIMgtConstants.PRODUCTION_ENDPOINT, globalEndpoint);
    endpointMap.put(APIMgtConstants.SANDBOX_ENDPOINT, apiEndpoint);
    Map<String, Endpoint> resourceEndpoints = new HashMap();
    resourceEndpoints.put(APIMgtConstants.SANDBOX_ENDPOINT, resourceEndpoint);
    Map<String, UriTemplate> uriTemplateMap = SampleTestObjectCreator.getMockUriTemplates();
    uriTemplateMap.forEach((k, v) -> {
        UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder(v);
        uriTemplateBuilder.endpoint(resourceEndpoints);
        uriTemplateMap.replace(k, uriTemplateBuilder.build());
    });
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().endpoint(endpointMap).uriTemplates(uriTemplateMap);
    Mockito.when(apiLifecycleManager.addLifecycle(APIMgtConstants.API_LIFECYCLE, USER)).thenReturn(new LifecycleState());
    APIGateway gateway = Mockito.mock(APIGateway.class);
    LabelDAO labelDao = Mockito.mock(LabelDAO.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(null, apiDAO, null, null, null, apiLifecycleManager, labelDao, null, null, null, gatewaySourceGenerator, gateway);
    Mockito.when(apiDAO.getEndpoint(globalEndpoint.getId())).thenReturn(globalEndpoint);
    Mockito.when(apiDAO.getEndpointByName(apiEndpoint.getName())).thenReturn(null);
    Mockito.when(apiDAO.getEndpointByName(resourceEndpoint.getName())).thenReturn(resourceEndpoint);
    Mockito.when(apiDAO.isAPINameExists(apiBuilder.getName(), USER)).thenReturn(false);
    apiPublisher.addAPI(apiBuilder);
    Mockito.verify(apiDAO, Mockito.times(1)).addAPI(apiBuilder.build());
    Mockito.verify(apiDAO, Mockito.times(1)).getEndpointByName(apiEndpoint.getName());
    Mockito.verify(apiDAO, Mockito.times(1)).getEndpointByName(resourceEndpoint.getName());
}
Also used : HashMap(java.util.HashMap) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) WorkflowExtensionsConfigBuilder(org.wso2.carbon.apimgt.core.workflow.WorkflowExtensionsConfigBuilder) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) LabelDAO(org.wso2.carbon.apimgt.core.dao.LabelDAO) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) APILifecycleManager(org.wso2.carbon.apimgt.core.api.APILifecycleManager) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) Test(org.testng.annotations.Test)

Example 88 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetRoleIdsOfUser.

@Test
public void testGetRoleIdsOfUser() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validUserId = "a42b4760-120d-432e-8042-4a7f12e3346c";
    String roleName1 = "subscriber";
    String roleId1 = "fb5aaf9c-1fdf-4b2d-86bc-6e3203b99618";
    String roleName2 = "manager";
    String roleId2 = "097435bc-c460-402b-9137-8ab65fd28c3e";
    String roleName3 = "engineer";
    String roleId3 = "ac093278-9343-466c-8a71-af47921a575b";
    List<String> roleIds = new ArrayList<>();
    roleIds.add(roleId1);
    roleIds.add(roleId2);
    roleIds.add(roleId3);
    String successResponseBody = "{\"emails\":[{\"type\":\"home\",\"value\":\"john_home.com\"},{\"type\":\"work\"" + ",\"value\":\"john_work.com\"}],\"meta\":{\"created\":\"2017-06-02T10:12:26\",\"location\":" + "\"https://localhost:9443/wso2/scim/Users/" + validUserId + "\",\"lastModified\":" + "\"2017-06-02T10:12:26\"},\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"name\":{\"familyName\":" + "\"Smith\",\"givenName\":\"John\"},\"groups\":[{\"display\":\"" + roleName1 + "\",\"value\":\"" + roleId1 + "\"},{\"display\":\"" + roleName2 + "\",\"value\":\"" + roleId2 + "\"},{\"display\":\"" + roleName3 + "\",\"value\":\"" + roleId3 + "\"}],\"id\":\"" + validUserId + "\",\"userName\":" + "\"John\"}";
    Response successfulResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(successResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(validUserId)).thenReturn(successfulResponse);
    List<String> roles = idpImpl.getRoleIdsOfUser(validUserId);
    Assert.assertEquals(roleIds.size(), roles.size());
    roles.forEach(roleId -> Assert.assertTrue(roleIds.contains(roleId)));
    // Error case - When response is null
    String invalidUserIdResponseNull = "invalidUserId_Response_Null";
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseNull)).thenReturn(null);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdResponseNull);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with Id " + invalidUserIdResponseNull + ". Error : Response is null.");
    }
    // Error case - When the request did not return a 200 OK response
    String invalidUserIdNot200OK = "invalidUserId_Not_200_OK";
    String errorResponseBody = "{\"Errors\":[{\"code\":\"404\",\"description\":\"User not found in the user " + "store.\"}]}";
    Response errorResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdNot200OK)).thenReturn(errorResponse);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdNot200OK);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving role Ids of user with Id " + invalidUserIdNot200OK + ". Error : User not found in the user store.");
    }
    // Error case - When response body is empty
    String invalidUserIdResponseEmpty = "invalidUserId_Response_Empty";
    Response emptyResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body("".getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseEmpty)).thenReturn(emptyResponse);
    try {
        idpImpl.getRoleIdsOfUser(invalidUserIdResponseEmpty);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with user Id " + invalidUserIdResponseEmpty + " from SCIM endpoint. Response body is null or empty.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) ArrayList(java.util.ArrayList) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 89 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class APIConfigContextTestCase method testEndpointContext.

@Test
public void testEndpointContext() {
    Endpoint ep = Endpoint.newEndpoint().name("Ep1").build();
    EndpointContext endpointContext = new EndpointContext(ep, "org.test");
    Endpoint epFromContext = (Endpoint) endpointContext.getContext().get("endpoint");
    Assert.assertEquals(epFromContext.getName(), "Ep1");
}
Also used : Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) Test(org.testng.annotations.Test)

Example 90 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testRevokeToken.

// TODO:Enable after revoke endpoint implementation done in key manager.
@Test(enabled = false)
public void testRevokeToken() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    OAuth2ServiceStubs.RevokeServiceStub revokeStub = Mockito.mock(OAuth2ServiceStubs.RevokeServiceStub.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    // happy path - 200
    Response revokeTokenResponse = Response.builder().status(200).headers(new HashMap<>()).build();
    Mockito.when(oAuth2ServiceStub.getRevokeServiceStub()).thenReturn(revokeStub);
    final String revokeToken = "xxx-revoke-token-xxx";
    Mockito.when(revokeStub.revokeAccessToken(revokeToken, consumerKey, consumerSecret)).thenReturn(revokeTokenResponse);
    try {
        kmImpl.revokeAccessToken(revokeToken, consumerKey, consumerSecret);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
    // error case - response is null
    Mockito.when(oAuth2ServiceStub.getRevokeServiceStub()).thenReturn(revokeStub);
    Mockito.when(revokeStub.revokeAccessToken(revokeToken, consumerKey, consumerSecret)).thenReturn(null);
    try {
        kmImpl.revokeAccessToken(revokeToken, consumerKey, consumerSecret);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Error occurred while revoking current access token. " + "Response is null"));
    }
    // error case - token response non-200
    final int errorCode = 500;
    Response errorResponse = Response.builder().status(errorCode).headers(new HashMap<>()).body("backend error occurred", Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getRevokeServiceStub()).thenReturn(revokeStub);
    Mockito.when(revokeStub.revokeAccessToken(revokeToken, consumerKey, consumerSecret)).thenReturn(errorResponse);
    try {
        kmImpl.revokeAccessToken(revokeToken, consumerKey, consumerSecret);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Token revocation failed. HTTP error code: " + errorCode));
    }
}
Also used : Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) HashMap(java.util.HashMap) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) OAuth2ServiceStubs(org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) Test(org.testng.annotations.Test)

Aggregations

Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)118 Test (org.testng.annotations.Test)114 HashMap (java.util.HashMap)90 IOException (java.io.IOException)84 ArrayList (java.util.ArrayList)77 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)70 Test (org.junit.Test)62 API (org.wso2.carbon.apimgt.core.models.API)58 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)50 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)50 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)46 Map (java.util.Map)44 HashSet (java.util.HashSet)36 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)33 URL (java.net.URL)31 CharonException (org.wso2.charon3.core.exceptions.CharonException)31 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)30 OMElement (org.apache.axiom.om.OMElement)28 Response (javax.ws.rs.core.Response)27 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)27