Search in sources :

Example 36 with ApplicationPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApplicationPolicy in project carbon-apimgt by wso2.

the class ThrottlingApiServiceImpl method throttlingPoliciesApplicationGet.

/**
 * Retrieves all Application Throttle Policies
 *
 * @param accept          Accept header value
 * @return Retrieves all Application Throttle Policies
 */
@Override
public Response throttlingPoliciesApplicationGet(String accept, MessageContext messageContext) {
    try {
        APIAdmin apiAdmin = new APIAdminImpl();
        String userName = RestApiCommonUtil.getLoggedInUsername();
        int tenantId = APIUtil.getTenantId(userName);
        Policy[] appPolicies = apiAdmin.getPolicies(tenantId, PolicyConstants.POLICY_LEVEL_APP);
        List<ApplicationPolicy> policies = new ArrayList<>();
        for (Policy policy : appPolicies) {
            policies.add((ApplicationPolicy) policy);
        }
        ApplicationThrottlePolicyListDTO listDTO = ApplicationThrottlePolicyMappingUtil.fromApplicationPolicyArrayToListDTO(policies.toArray(new ApplicationPolicy[policies.size()]));
        return Response.ok().entity(listDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving Application level policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) 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) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIAdmin(org.wso2.carbon.apimgt.api.APIAdmin) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) ArrayList(java.util.ArrayList) APIAdminImpl(org.wso2.carbon.apimgt.impl.APIAdminImpl)

Example 37 with ApplicationPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApplicationPolicy in project carbon-apimgt by wso2.

the class ThrottlingApiServiceImpl method throttlingPoliciesApplicationPolicyIdGet.

/**
 * Get a specific Application Policy by its uuid
 *
 * @param policyId        uuid of the policy
 * @return Matched Application Throttle Policy by the given name
 */
@Override
public Response throttlingPoliciesApplicationPolicyIdGet(String policyId, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String username = RestApiCommonUtil.getLoggedInUsername();
        // This will give PolicyNotFoundException if there's no policy exists with UUID
        ApplicationPolicy appPolicy = apiProvider.getApplicationPolicyByUUID(policyId);
        if (!RestApiAdminUtils.isPolicyAccessibleToUser(username, appPolicy)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APP_POLICY, policyId, log);
        }
        ApplicationThrottlePolicyDTO policyDTO = ApplicationThrottlePolicyMappingUtil.fromApplicationThrottlePolicyToDTO(appPolicy);
        return Response.ok().entity(policyDTO).build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_POLICY, policyId, e, log);
        } else {
            String errorMessage = "Error while retrieving Application level policy: " + policyId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 38 with ApplicationPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApplicationPolicy in project carbon-apimgt by wso2.

the class ApiMgtDAO method updateApplicationPolicy.

/**
 * Updates Application level policy.
 * <p>policy name and tenant id should be specified in <code>policy</code></p>
 *
 * @param policy updated policy object
 * @throws APIManagementException
 */
public void updateApplicationPolicy(ApplicationPolicy policy) throws APIManagementException {
    Connection connection = null;
    PreparedStatement updateStatement = null;
    boolean hasCustomAttrib = false;
    String updateQuery;
    if (policy.getTenantId() == -1 || StringUtils.isEmpty(policy.getPolicyName())) {
        String errorMsg = "Policy object doesn't contain mandatory parameters. Name: " + policy.getPolicyName() + ", Tenant Id: " + policy.getTenantId();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg);
    }
    try {
        if (policy.getCustomAttributes() != null) {
            hasCustomAttrib = true;
        }
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
            updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_SQL;
            if (hasCustomAttrib) {
                updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_WITH_CUSTOM_ATTRIBUTES_SQL;
            }
        } else if (!StringUtils.isBlank(policy.getUUID())) {
            updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_BY_UUID_SQL;
            if (hasCustomAttrib) {
                updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_WITH_CUSTOM_ATTRIBUTES_BY_UUID_SQL;
            }
        } else {
            String errorMsg = "Policy object doesn't contain mandatory parameters. At least UUID or Name,Tenant Id" + " should be provided. Name: " + policy.getPolicyName() + ", Tenant Id: " + policy.getTenantId() + ", UUID: " + policy.getUUID();
            log.error(errorMsg);
            throw new APIManagementException(errorMsg);
        }
        updateStatement = connection.prepareStatement(updateQuery);
        if (!StringUtils.isEmpty(policy.getDisplayName())) {
            updateStatement.setString(1, policy.getDisplayName());
        } else {
            updateStatement.setString(1, policy.getPolicyName());
        }
        updateStatement.setString(2, policy.getDescription());
        updateStatement.setString(3, policy.getDefaultQuotaPolicy().getType());
        if (PolicyConstants.REQUEST_COUNT_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
            RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
            updateStatement.setLong(4, limit.getRequestCount());
            updateStatement.setString(5, null);
        } else if (PolicyConstants.BANDWIDTH_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
            BandwidthLimit limit = (BandwidthLimit) policy.getDefaultQuotaPolicy().getLimit();
            updateStatement.setLong(4, limit.getDataAmount());
            updateStatement.setString(5, limit.getDataUnit());
        }
        updateStatement.setLong(6, policy.getDefaultQuotaPolicy().getLimit().getUnitTime());
        updateStatement.setString(7, policy.getDefaultQuotaPolicy().getLimit().getTimeUnit());
        if (hasCustomAttrib) {
            updateStatement.setBlob(8, new ByteArrayInputStream(policy.getCustomAttributes()));
            if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
                updateStatement.setString(9, policy.getPolicyName());
                updateStatement.setInt(10, policy.getTenantId());
            } else if (!StringUtils.isBlank(policy.getUUID())) {
                updateStatement.setString(9, policy.getUUID());
            }
        } else {
            if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
                updateStatement.setString(8, policy.getPolicyName());
                updateStatement.setInt(9, policy.getTenantId());
            } else if (!StringUtils.isBlank(policy.getUUID())) {
                updateStatement.setString(8, policy.getUUID());
            }
        }
        updateStatement.executeUpdate();
        connection.commit();
    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                // Rollback failed. Exception will be thrown later for upper exception
                log.error("Failed to rollback the update Application Policy: " + policy.toString(), ex);
            }
        }
        handleException("Failed to update application policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
    } finally {
        APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
    }
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ByteArrayInputStream(java.io.ByteArrayInputStream) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) BandwidthLimit(org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit)

Example 39 with ApplicationPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApplicationPolicy in project carbon-apimgt by wso2.

the class ApiMgtDAO method getApplicationPolicy.

/**
 * Retrieves {@link ApplicationPolicy} with name <code>policyName</code> and tenant Id <code>tenantNId</code>
 *
 * @param policyName name of the policy to retrieve from the database
 * @param tenantId   tenantId of the policy
 * @return {@link ApplicationPolicy}
 * @throws APIManagementException
 */
public ApplicationPolicy getApplicationPolicy(String policyName, int tenantId) throws APIManagementException {
    ApplicationPolicy policy = null;
    Connection connection = null;
    PreparedStatement selectStatement = null;
    ResultSet resultSet = null;
    String sqlQuery = SQLConstants.GET_APPLICATION_POLICY_SQL;
    if (forceCaseInsensitiveComparisons) {
        sqlQuery = SQLConstants.GET_APPLICATION_POLICY_SQL;
    }
    try {
        connection = APIMgtDBUtil.getConnection();
        selectStatement = connection.prepareStatement(sqlQuery);
        selectStatement.setString(1, policyName);
        selectStatement.setInt(2, tenantId);
        // Should return only single row
        resultSet = selectStatement.executeQuery();
        if (resultSet.next()) {
            policy = new ApplicationPolicy(resultSet.getString(ThrottlePolicyConstants.COLUMN_NAME));
            setCommonPolicyDetails(policy, resultSet);
        }
    } catch (SQLException e) {
        handleException("Failed to get application policy: " + policyName + '-' + tenantId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(selectStatement, connection, resultSet);
    }
    return policy;
}
Also used : SQLException(java.sql.SQLException) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 40 with ApplicationPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApplicationPolicy in project carbon-apimgt by wso2.

the class APIProviderImplTest method testGetApplicationPolicyByUUID.

@Test
public void testGetApplicationPolicyByUUID() throws APIManagementException {
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    ApplicationPolicy applicationPolicy = Mockito.mock(ApplicationPolicy.class);
    Mockito.when(apimgtDAO.getApplicationPolicyByUUID("1111")).thenReturn(applicationPolicy, null);
    apiProvider.getApplicationPolicyByUUID("1111");
    try {
        assertNotNull(apiProvider.getApplicationPolicyByUUID("1111"));
    } catch (APIManagementException e) {
        assertEquals("Application Policy: 1111 was not found.", e.getMessage());
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)56 Test (org.testng.annotations.Test)30 ApplicationPolicy (org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy)29 PolicyDAO (org.wso2.carbon.apimgt.core.dao.PolicyDAO)24 ArrayList (java.util.ArrayList)23 Test (org.junit.Test)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)18 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)18 Application (org.wso2.carbon.apimgt.core.models.Application)17 Connection (java.sql.Connection)16 PreparedStatement (java.sql.PreparedStatement)16 SQLException (java.sql.SQLException)16 ResultSet (java.sql.ResultSet)13 BeforeTest (org.testng.annotations.BeforeTest)13 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)13 ApplicationDAO (org.wso2.carbon.apimgt.core.dao.ApplicationDAO)13 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)13 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)13 APIPolicy (org.wso2.carbon.apimgt.api.model.policy.APIPolicy)12 SubscriptionPolicy (org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy)12