Search in sources :

Example 56 with APIPolicy

use of org.wso2.carbon.apimgt.core.models.policy.APIPolicy in project carbon-apimgt by wso2.

the class AdvancedThrottlePolicyMappingUtil method fromAdvancedPolicyToInfoDTO.

/**
 * Converts a single Advanced Policy model into REST API DTO
 *
 * @param apiPolicy Advanced Policy model object
 * @return Converted Advanced policy REST API DTO object
 * @throws UnsupportedThrottleLimitTypeException
 * @throws UnsupportedThrottleConditionTypeException
 */
public static AdvancedThrottlePolicyInfoDTO fromAdvancedPolicyToInfoDTO(APIPolicy apiPolicy) throws UnsupportedThrottleLimitTypeException, UnsupportedThrottleConditionTypeException {
    AdvancedThrottlePolicyInfoDTO policyDTO = new AdvancedThrottlePolicyInfoDTO();
    policyDTO = CommonThrottleMappingUtil.updateFieldsFromToPolicyToDTO(apiPolicy, policyDTO);
    if (apiPolicy.getDefaultQuotaPolicy() != null) {
        policyDTO.setDefaultLimit(CommonThrottleMappingUtil.fromQuotaPolicyToDTO(apiPolicy.getDefaultQuotaPolicy()));
    }
    policyDTO.setType(ADVACNCED_THROTTLING_POLICY_INFO_TYPE);
    return policyDTO;
}
Also used : AdvancedThrottlePolicyInfoDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.AdvancedThrottlePolicyInfoDTO)

Example 57 with APIPolicy

use of org.wso2.carbon.apimgt.core.models.policy.APIPolicy in project carbon-apimgt by wso2.

the class ApiMgtDAO method getAPIPolicyByUUID.

/**
 * Retrieves {@link APIPolicy} with name <code>uuid</code>
 * <p>This will retrieve complete details about the APIPolicy with all pipelines and conditions.</p>
 *
 * @param uuid uuid of the policy to retrieve from the database
 * @return {@link APIPolicy}
 * @throws APIManagementException
 */
public APIPolicy getAPIPolicyByUUID(String uuid) throws APIManagementException {
    APIPolicy policy = null;
    Connection connection = null;
    PreparedStatement selectStatement = null;
    ResultSet resultSet = null;
    String sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICY_BY_UUID_SQL;
    if (forceCaseInsensitiveComparisons) {
        sqlQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICY_BY_UUID_SQL;
    }
    try {
        connection = APIMgtDBUtil.getConnection();
        selectStatement = connection.prepareStatement(sqlQuery);
        selectStatement.setString(1, uuid);
        // Should return only single result
        resultSet = selectStatement.executeQuery();
        if (resultSet.next()) {
            policy = new APIPolicy(resultSet.getString(ThrottlePolicyConstants.COLUMN_NAME));
            setCommonPolicyDetails(policy, resultSet);
            policy.setUserLevel(resultSet.getString(ThrottlePolicyConstants.COLUMN_APPLICABLE_LEVEL));
            policy.setPipelines(getPipelines(policy.getPolicyId()));
        }
    } catch (SQLException e) {
        handleException("Failed to get api policy: " + uuid, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
    }
    return policy;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy)

Example 58 with APIPolicy

use of org.wso2.carbon.apimgt.core.models.policy.APIPolicy in project carbon-apimgt by wso2.

the class ApiMgtDAO method addAPIPolicy.

/**
 * Add a API level throttling policy to database.
 * <p>
 * If valid policy Id (not -1) is present in the <code>policy</code> object,
 * policy will be inserted with that policy Id.
 * Otherwise policy Id will be auto incremented.
 * </p>
 *
 * @param policy policy object defining the throttle policy
 * @throws SQLException
 */
private void addAPIPolicy(APIPolicy policy, Connection conn) throws SQLException {
    ResultSet resultSet = null;
    PreparedStatement policyStatement = null;
    String addQuery = SQLConstants.ThrottleSQLConstants.INSERT_API_POLICY_SQL;
    int policyId;
    try {
        String dbProductName = conn.getMetaData().getDatabaseProductName();
        policyStatement = conn.prepareStatement(addQuery, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "POLICY_ID") });
        setCommonParametersForPolicy(policyStatement, policy);
        policyStatement.setString(12, policy.getUserLevel());
        policyStatement.executeUpdate();
        // Get the inserted POLICY_ID (auto incremented value)
        resultSet = policyStatement.getGeneratedKeys();
        // Returns only single row
        if (resultSet.next()) {
            /*
                 *  H2 doesn't return generated keys when key is provided (not generated).
                   Therefore policyId should be policy parameter's policyId when it is provided.
                 */
            policyId = resultSet.getInt(1);
            List<Pipeline> pipelines = policy.getPipelines();
            if (pipelines != null) {
                for (Pipeline pipeline : pipelines) {
                    // add each pipeline data to AM_CONDITION_GROUP table
                    addPipeline(pipeline, policyId, conn);
                }
            }
        }
    } finally {
        APIMgtDBUtil.closeAllConnections(policyStatement, null, resultSet);
    }
}
Also used : ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Pipeline(org.wso2.carbon.apimgt.api.model.policy.Pipeline)

Example 59 with APIPolicy

use of org.wso2.carbon.apimgt.core.models.policy.APIPolicy in project carbon-apimgt by wso2.

the class APIMgtDAOTest method testGetApiPolicy.

@Test
public void testGetApiPolicy() throws APIManagementException {
    String policyName = "TestGetAPIPolicy";
    apiMgtDAO.addAPIPolicy((APIPolicy) getPolicyAPILevelPerUser(policyName));
    APIPolicy apiPolicy = apiMgtDAO.getAPIPolicy(policyName, -1234);
    assertNotNull(apiPolicy);
    assertEquals(apiPolicy.getPolicyName(), policyName);
    APIPolicy apiPolicyFromUUId = apiMgtDAO.getAPIPolicyByUUID(apiPolicy.getUUID());
    assertNotNull(apiPolicyFromUUId);
    assertEquals(apiPolicyFromUUId.getPolicyName(), policyName);
    apiMgtDAO.setPolicyDeploymentStatus(PolicyConstants.POLICY_LEVEL_API, apiPolicy.getPolicyName(), -1234, true);
    assertTrue(apiMgtDAO.isPolicyDeployed(PolicyConstants.POLICY_LEVEL_API, -1234, apiPolicy.getPolicyName()));
    assertTrue(apiMgtDAO.getPolicyNames(PolicyConstants.POLICY_LEVEL_API, "admin").length > 0);
    assertTrue(apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_API, -1234, apiPolicy.getPolicyName()));
}
Also used : APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 60 with APIPolicy

use of org.wso2.carbon.apimgt.core.models.policy.APIPolicy in project carbon-apimgt by wso2.

the class APIMgtDAOTest method testDeleteSubscriptionsForapiId.

@Test
public void testDeleteSubscriptionsForapiId() throws Exception {
    Subscriber subscriber = new Subscriber("testCreateApplicationRegistrationEntry");
    String organization = "testOrg";
    subscriber.setTenantId(-1234);
    subscriber.setEmail("abc@wso2.com");
    subscriber.setSubscribedDate(new Date(System.currentTimeMillis()));
    apiMgtDAO.addSubscriber(subscriber, null);
    Policy applicationPolicy = getApplicationPolicy("testCreateApplicationRegistrationEntry");
    SubscriptionPolicy subscriptionPolicy = (SubscriptionPolicy) getSubscriptionPolicy("testCreateApplicationRegistrationEntry");
    subscriptionPolicy.setMonetizationPlan(APIConstants.Monetization.FIXED_RATE);
    apiMgtDAO.addSubscriptionPolicy((SubscriptionPolicy) subscriptionPolicy);
    applicationPolicy.setTenantId(-1234);
    apiMgtDAO.addApplicationPolicy((ApplicationPolicy) applicationPolicy);
    Application application = new Application("testCreateApplicationRegistrationEntry", subscriber);
    application.setTier("testCreateApplicationRegistrationEntry");
    application.setId(apiMgtDAO.addApplication(application, "testCreateApplicationRegistrationEntry", organization));
    application.setDescription("updated description");
    apiMgtDAO.updateApplication(application);
    assertEquals(apiMgtDAO.getApplicationById(application.getId()).getDescription(), "updated description");
    APIIdentifier apiId = new APIIdentifier("testCreateApplicationRegistrationEntry", "testCreateApplicationRegistrationEntry", "1.0.0");
    API api = new API(apiId);
    api.setContext("/testCreateApplicationRegistrationEntry");
    api.setContextTemplate("/testCreateApplicationRegistrationEntry/{version}");
    api.setVersionTimestamp(String.valueOf(System.currentTimeMillis()));
    APIPolicy apiPolicy = (APIPolicy) getPolicyAPILevelPerUser("testCreateApplicationRegistrationEntry");
    api.setApiLevelPolicy(apiPolicy.getPolicyName());
    api.setUUID(UUID.randomUUID().toString());
    api.getId().setId(apiMgtDAO.addAPI(api, -1234, organization));
    apiId.setTier(subscriptionPolicy.getPolicyName());
    ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(api);
    int subsId = apiMgtDAO.addSubscription(apiTypeWrapper, application, APIConstants.SubscriptionStatus.ON_HOLD, subscriber.getName());
    assertTrue(apiMgtDAO.getApplicationsByTier(subscriptionPolicy.getPolicyName()).length > 0);
    String subStatus = apiMgtDAO.getSubscriptionStatusById(subsId);
    assertEquals(subStatus, APIConstants.SubscriptionStatus.ON_HOLD);
    SubscribedAPI subscribedAPI = apiMgtDAO.getSubscriptionById(subsId);
    String clientIdProduction = UUID.randomUUID().toString();
    String clientIdSandbox = UUID.randomUUID().toString();
    apiMgtDAO.createApplicationKeyTypeMappingForManualClients(APIConstants.API_KEY_TYPE_PRODUCTION, application.getId(), clientIdProduction, "Default", UUID.randomUUID().toString());
    apiMgtDAO.createApplicationKeyTypeMappingForManualClients(APIConstants.API_KEY_TYPE_SANDBOX, application.getId(), clientIdSandbox, "Default", UUID.randomUUID().toString());
    assertTrue(apiMgtDAO.getSubscriptionCount(subscriber, application.getName(), null) > 0);
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    Mockito.when(keyManager.retrieveApplication(clientIdProduction)).thenReturn(oAuthApplicationInfo);
    Mockito.when(keyManager.retrieveApplication(clientIdSandbox)).thenReturn(oAuthApplicationInfo);
    assertTrue(apiMgtDAO.getSubscribedAPIs(organization, subscriber, null).size() > 0);
    assertEquals(subscribedAPI.getSubCreatedStatus(), APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
    assertEquals(subscribedAPI.getApiId(), apiId);
    assertEquals(subscribedAPI.getApplication().getId(), application.getId());
    SubscribedAPI subscribedAPIFromUuid = apiMgtDAO.getSubscriptionByUUID(subscribedAPI.getUUID());
    assertEquals(subscribedAPIFromUuid.getSubCreatedStatus(), APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
    assertEquals(subscribedAPIFromUuid.getApiId(), apiId);
    assertEquals(subscribedAPIFromUuid.getApplication().getId(), application.getId());
    apiMgtDAO.updateApplicationStatus(application.getId(), APIConstants.ApplicationStatus.APPLICATION_APPROVED);
    String status = apiMgtDAO.getApplicationStatus("testCreateApplicationRegistrationEntry", "testCreateApplicationRegistrationEntry");
    assertEquals(status, APIConstants.ApplicationStatus.APPLICATION_APPROVED);
    boolean applicationExist = apiMgtDAO.isApplicationExist(application.getName(), subscriber.getName(), null, organization);
    assertTrue(applicationExist);
    Set<SubscribedAPI> subscribedAPIS = apiMgtDAO.getSubscribedAPIs(subscriber, application.getName(), null);
    assertEquals(subscribedAPIS.size(), 1);
    apiMgtDAO.updateSubscription(apiId, APIConstants.SubscriptionStatus.BLOCKED, application.getId(), organization);
    subscribedAPI.setSubStatus(APIConstants.SubscriptionStatus.REJECTED);
    apiMgtDAO.updateSubscription(subscribedAPI);
    assertTrue(apiMgtDAO.hasSubscription(subscriptionPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_SUB));
    assertTrue(apiMgtDAO.hasSubscription(applicationPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_APP));
    assertTrue(apiMgtDAO.hasSubscription(apiPolicy.getPolicyName(), subscriber.getName(), PolicyConstants.POLICY_LEVEL_API));
    assertTrue(apiPolicy.getPolicyName().equals(apiMgtDAO.getAPILevelTier(apiMgtDAO.getAPIID(api.getUuid()))));
    apiMgtDAO.recordAPILifeCycleEvent(api.getUuid(), "CREATED", "PUBLISHED", "testCreateApplicationRegistrationEntry", -1234);
    apiMgtDAO.updateDefaultAPIPublishedVersion(apiId);
    apiMgtDAO.removeAllSubscriptions(api.getUuid());
    assertTrue(apiMgtDAO.getAPINamesMatchingContext(api.getContext()).size() > 0);
    apiMgtDAO.deleteAPI(api.getUuid());
    apiMgtDAO.deleteApplication(application);
    apiMgtDAO.removeThrottlePolicy(PolicyConstants.POLICY_LEVEL_APP, "testCreateApplicationRegistrationEntry", -1234);
    apiMgtDAO.deleteApplicationKeyMappingByConsumerKey(clientIdProduction);
    apiMgtDAO.deleteApplicationMappingByConsumerKey(clientIdSandbox);
    deleteSubscriber(subscriber.getId());
}
Also used : QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.api.model.policy.Policy) GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) Date(java.util.Date) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) OAuthApplicationInfo(org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) API(org.wso2.carbon.apimgt.api.model.API) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Application(org.wso2.carbon.apimgt.api.model.Application) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)87 Test (org.testng.annotations.Test)44 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)40 PolicyDAO (org.wso2.carbon.apimgt.core.dao.PolicyDAO)39 ArrayList (java.util.ArrayList)38 API (org.wso2.carbon.apimgt.core.models.API)33 APIPolicy (org.wso2.carbon.apimgt.api.model.policy.APIPolicy)30 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)27 HashMap (java.util.HashMap)25 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)22 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)22 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)22 APIBuilder (org.wso2.carbon.apimgt.core.models.API.APIBuilder)21 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)20 HashSet (java.util.HashSet)19 Test (org.junit.Test)19 QuotaPolicy (org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy)19 ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)17 PreparedStatement (java.sql.PreparedStatement)15