Search in sources :

Example 51 with SubscribedAPI

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

the class InternalAPIKeyAuthenticatorTest method testAuthenticateNoCacheTokenTenant.

@Test
public void testAuthenticateNoCacheTokenTenant() throws Exception {
    PowerMockito.when(GatewayUtils.isInternalKey(Mockito.any(JWTClaimsSet.class))).thenReturn(true);
    InternalAPIKeyAuthenticator internalAPIKeyAuthenticator = new InternalAPIKeyAuthenticator(APIMgtGatewayConstants.INTERNAL_KEY);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1/1.0.0");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0.0");
    API api = new API();
    PowerMockito.when(GatewayUtils.getAPI(messageContext)).thenReturn(api);
    TreeMap transportHeaders = new TreeMap();
    transportHeaders.put(APIMgtGatewayConstants.INTERNAL_KEY, internalKey);
    org.apache.axis2.context.MessageContext axis2MsgCntxt = Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/resource");
    OpenAPI openAPI = Mockito.mock(OpenAPI.class);
    Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT)).thenReturn(openAPI);
    PowerMockito.when(OpenAPIUtils.getResourceThrottlingTier(openAPI, messageContext)).thenReturn("GOLD");
    PowerMockito.when(GatewayUtils.getTenantDomain()).thenReturn("abc.com");
    Cache internalKeyCache = Mockito.mock(Cache.class);
    Cache superTenantInternalKeyCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyCache()).thenReturn(internalKeyCache).thenReturn(internalKeyCache).thenReturn(superTenantInternalKeyCache);
    Mockito.when(internalKeyCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn(null);
    Cache internalKeyDataCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getGatewayInternalKeyDataCache()).thenReturn(internalKeyDataCache);
    Cache invalidCache = Mockito.mock(Cache.class);
    PowerMockito.when(CacheProvider.getInvalidGatewayInternalKeyCache()).thenReturn(invalidCache);
    Mockito.when(invalidCache.get("28f8d7b0-9e62-4341-bf17-094453d5ffa4")).thenReturn(null);
    JSONObject subscribedAPI = Mockito.mock(JSONObject.class);
    PowerMockito.when(GatewayUtils.verifyTokenSignature(Mockito.any(SignedJWT.class), Mockito.anyString())).thenReturn(true);
    PowerMockito.when(GatewayUtils.isJwtTokenExpired(signedJWT.getJWTClaimsSet())).thenReturn(false);
    PowerMockito.when(GatewayUtils.validateAPISubscription("/api1/1.0.0", "1.0.0", signedJWT.getJWTClaimsSet(), internalKey.split("\\."), false)).thenReturn(subscribedAPI);
    AuthenticationContext authenticationContext = Mockito.mock(AuthenticationContext.class);
    PowerMockito.when(GatewayUtils.generateAuthenticationContext("28f8d7b0-9e62-4341-bf17-094453d5ffa4", signedJWT.getJWTClaimsSet(), subscribedAPI, api.getApiTier())).thenReturn(authenticationContext);
    PowerMockito.doNothing().when(APISecurityUtils.class, "setAuthenticationContext", messageContext, authenticationContext);
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    PowerMockito.doNothing().when(PrivilegedCarbonContext.class, "startTenantFlow");
    PowerMockito.doNothing().when(privilegedCarbonContext).setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
    AuthenticationResponse authenticate = internalAPIKeyAuthenticator.authenticate(messageContext);
    Assert.assertNotNull(authenticate);
    Assert.assertTrue(authenticate.isMandatoryAuthentication());
    Assert.assertTrue(authenticate.isAuthenticated());
    Assert.assertFalse(authenticate.isContinueToNextAuthenticator());
    Assert.assertEquals(authenticate.getErrorCode(), 0);
    Assert.assertNull(authenticate.getErrorMessage());
    Mockito.verify(internalKeyCache, Mockito.times(1)).get("28f8d7b0-9e62-4341-bf17-094453d5ffa4");
    Mockito.verify(invalidCache, Mockito.times(1)).get("28f8d7b0-9e62-4341-bf17-094453d5ffa4");
    Mockito.verify(internalKeyCache, Mockito.times(1)).put("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "abc.com");
    Mockito.verify(superTenantInternalKeyCache, Mockito.times(1)).put("28f8d7b0-9e62-4341-bf17-094453d5ffa4", "abc.com");
    Mockito.verify(internalKeyDataCache, Mockito.times(1)).put(Mockito.anyString(), Mockito.any());
}
Also used : AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) SignedJWT(com.nimbusds.jwt.SignedJWT) TreeMap(java.util.TreeMap) AuthenticationResponse(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse) JSONObject(net.minidev.json.JSONObject) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OpenAPI(io.swagger.v3.oas.models.OpenAPI) API(org.wso2.carbon.apimgt.keymgt.model.entity.API) MessageContext(org.apache.synapse.MessageContext) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext) Cache(javax.cache.Cache) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 52 with SubscribedAPI

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

the class ApiMgtDAO method getSubscriptionById.

/**
 * returns the SubscribedAPI object which is related to the subscriptionId
 *
 * @param subscriptionId subscription id
 * @return {@link SubscribedAPI} Object which contains the subscribed API information.
 * @throws APIManagementException
 */
public SubscribedAPI getSubscriptionById(int subscriptionId) throws APIManagementException {
    Connection conn = null;
    ResultSet resultSet = null;
    PreparedStatement ps = null;
    try {
        conn = APIMgtDBUtil.getConnection();
        String getSubscriptionQuery = SQLConstants.GET_SUBSCRIPTION_BY_ID_SQL;
        ps = conn.prepareStatement(getSubscriptionQuery);
        ps.setInt(1, subscriptionId);
        resultSet = ps.executeQuery();
        SubscribedAPI subscribedAPI = null;
        if (resultSet.next()) {
            int applicationId = resultSet.getInt("APPLICATION_ID");
            Application application = getLightweightApplicationById(conn, applicationId);
            if (APIConstants.API_PRODUCT.equals(resultSet.getString("API_TYPE"))) {
                APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(APIUtil.replaceEmailDomain(resultSet.getString("API_PROVIDER")), resultSet.getString("API_NAME"), resultSet.getString("API_VERSION"));
                apiProductIdentifier.setProductId(resultSet.getInt("API_ID"));
                apiProductIdentifier.setUUID(resultSet.getString("API_UUID"));
                subscribedAPI = new SubscribedAPI(application.getSubscriber(), apiProductIdentifier);
            } else {
                APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(resultSet.getString("API_PROVIDER")), resultSet.getString("API_NAME"), resultSet.getString("API_VERSION"));
                apiIdentifier.setId(resultSet.getInt("API_ID"));
                apiIdentifier.setUuid(resultSet.getString("API_UUID"));
                subscribedAPI = new SubscribedAPI(application.getSubscriber(), apiIdentifier);
            }
            subscribedAPI.setSubscriptionId(resultSet.getInt("SUBSCRIPTION_ID"));
            subscribedAPI.setSubStatus(resultSet.getString("SUB_STATUS"));
            subscribedAPI.setSubCreatedStatus(resultSet.getString("SUBS_CREATE_STATE"));
            subscribedAPI.setTier(new Tier(resultSet.getString("TIER_ID")));
            subscribedAPI.setRequestedTier(new Tier(resultSet.getString("TIER_ID_PENDING")));
            subscribedAPI.setUUID(resultSet.getString("UUID"));
            subscribedAPI.setApplication(application);
        }
        return subscribedAPI;
    } catch (SQLException e) {
        handleException("Failed to retrieve subscription from subscription id", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
    }
    return null;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Tier(org.wso2.carbon.apimgt.api.model.Tier) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PreparedStatement(java.sql.PreparedStatement) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 53 with SubscribedAPI

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

the class ApiMgtDAO method getSubscriptionByUUID.

/**
 * returns the SubscribedAPI object which is related to the UUID
 *
 * @param uuid UUID of Application
 * @return {@link SubscribedAPI} Object which contains the subscribed API information.
 * @throws APIManagementException
 */
public SubscribedAPI getSubscriptionByUUID(String uuid) throws APIManagementException {
    Connection conn = null;
    ResultSet resultSet = null;
    PreparedStatement ps = null;
    try {
        conn = APIMgtDBUtil.getConnection();
        String getSubscriptionQuery = SQLConstants.GET_SUBSCRIPTION_BY_UUID_SQL;
        ps = conn.prepareStatement(getSubscriptionQuery);
        ps.setString(1, uuid);
        resultSet = ps.executeQuery();
        SubscribedAPI subscribedAPI = null;
        if (resultSet.next()) {
            Identifier identifier;
            if (APIConstants.API_PRODUCT.equals(resultSet.getString("API_TYPE"))) {
                identifier = new APIProductIdentifier(APIUtil.replaceEmailDomain(resultSet.getString("API_PROVIDER")), resultSet.getString("API_NAME"), resultSet.getString("API_VERSION"));
            } else {
                identifier = new APIIdentifier(APIUtil.replaceEmailDomain(resultSet.getString("API_PROVIDER")), resultSet.getString("API_NAME"), resultSet.getString("API_VERSION"));
            }
            identifier.setId(resultSet.getInt("API_ID"));
            identifier.setUuid(resultSet.getString("API_UUID"));
            identifier.setOrganization(resultSet.getString("ORGANIZATION"));
            int applicationId = resultSet.getInt("APPLICATION_ID");
            Application application = getLightweightApplicationById(conn, applicationId);
            application.setSubscriptionCount(getSubscriptionCountByApplicationId(conn, application, identifier.getOrganization()));
            subscribedAPI = new SubscribedAPI(application.getSubscriber(), identifier);
            subscribedAPI.setUUID(resultSet.getString("UUID"));
            subscribedAPI.setSubscriptionId(resultSet.getInt("SUBSCRIPTION_ID"));
            subscribedAPI.setSubStatus(resultSet.getString("SUB_STATUS"));
            subscribedAPI.setSubCreatedStatus(resultSet.getString("SUBS_CREATE_STATE"));
            subscribedAPI.setTier(new Tier(resultSet.getString("TIER_ID")));
            subscribedAPI.setRequestedTier(new Tier(resultSet.getString("TIER_ID_PENDING")));
            Timestamp createdTime = resultSet.getTimestamp("CREATED_TIME");
            subscribedAPI.setCreatedTime(createdTime == null ? null : String.valueOf(createdTime.getTime()));
            try {
                Timestamp updatedTime = resultSet.getTimestamp("UPDATED_TIME");
                subscribedAPI.setUpdatedTime(updatedTime == null ? null : String.valueOf(updatedTime.getTime()));
            } catch (SQLException e) {
                // fixing Timestamp issue with default value '0000-00-00 00:00:00'for existing applications created
                subscribedAPI.setUpdatedTime(subscribedAPI.getCreatedTime());
            }
            subscribedAPI.setApplication(application);
        }
        return subscribedAPI;
    } catch (SQLException e) {
        handleException("Failed to retrieve subscription from subscription id", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
    }
    return null;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) ResultSet(java.sql.ResultSet) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 54 with SubscribedAPI

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

the class AbstractAPIManagerTestCase method testGetSubscriptionByUUID.

@Test
public void testGetSubscriptionByUUID() throws APIManagementException {
    Subscriber subscriber = new Subscriber("sub1");
    SubscribedAPI subscribedAPI = new SubscribedAPI(subscriber, getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION));
    Mockito.when(apiMgtDAO.getSubscriptionByUUID(Mockito.anyString())).thenReturn(subscribedAPI);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(apiMgtDAO);
    Assert.assertEquals(abstractAPIManager.getSubscriptionByUUID(SAMPLE_RESOURCE_ID).getApiId().getApiName(), SAMPLE_API_NAME);
}
Also used : Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 55 with SubscribedAPI

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

the class APIProviderImplTest method testGetAPIUsageByAPIId.

@Test
public void testGetAPIUsageByAPIId() throws APIManagementException, RegistryException, UserStoreException {
    String uuid = UUID.randomUUID().toString();
    SubscribedAPI subscribedAPI1 = new SubscribedAPI(new Subscriber("user1"), new APIIdentifier("admin", "API1", "1.0.0"));
    SubscribedAPI subscribedAPI2 = new SubscribedAPI(new Subscriber("user1"), new APIIdentifier("admin", "API2", "1.0.0"));
    UserApplicationAPIUsage apiResult1 = new UserApplicationAPIUsage();
    apiResult1.addApiSubscriptions(subscribedAPI1);
    apiResult1.addApiSubscriptions(subscribedAPI2);
    SubscribedAPI subscribedAPI3 = new SubscribedAPI(new Subscriber("user2"), new APIIdentifier("admin", "API1", "1.0.0"));
    SubscribedAPI subscribedAPI4 = new SubscribedAPI(new Subscriber("user2"), new APIIdentifier("admin", "API2", "1.0.0"));
    UserApplicationAPIUsage apiResult2 = new UserApplicationAPIUsage();
    apiResult2.addApiSubscriptions(subscribedAPI3);
    apiResult2.addApiSubscriptions(subscribedAPI4);
    UserApplicationAPIUsage[] apiResults = { apiResult1, apiResult2 };
    Mockito.when(apimgtDAO.getAllAPIUsageByProviderAndApiId(uuid, "org1")).thenReturn(apiResults);
    Mockito.when(apimgtDAO.getAPIIdentifierFromUUID(uuid)).thenReturn(new APIIdentifier("admin", "API1", "1.0.0"));
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    List<SubscribedAPI> subscribedAPIs = apiProvider.getAPIUsageByAPIId(uuid, "org1");
    Assert.assertEquals(2, subscribedAPIs.size());
    Assert.assertEquals("user1", subscribedAPIs.get(0).getSubscriber().getName());
    Assert.assertEquals("user2", subscribedAPIs.get(1).getSubscriber().getName());
}
Also used : UserApplicationAPIUsage(org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)54 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)28 Application (org.wso2.carbon.apimgt.api.model.Application)28 Tier (org.wso2.carbon.apimgt.api.model.Tier)23 Test (org.junit.Test)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)18 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)16 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)14 ArrayList (java.util.ArrayList)12 ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)12 HashSet (java.util.HashSet)11 TreeMap (java.util.TreeMap)11 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)11 Connection (java.sql.Connection)10 PreparedStatement (java.sql.PreparedStatement)10 SQLException (java.sql.SQLException)10 ResultSet (java.sql.ResultSet)9 JSONObject (net.minidev.json.JSONObject)9 API (org.wso2.carbon.apimgt.api.model.API)9