use of org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy in project carbon-apimgt by wso2.
the class APIUtilTierTest method testGetTiersFromApiPoliciesBandwidth.
@Test
public void testGetTiersFromApiPoliciesBandwidth() throws Exception {
String policyLevel = PolicyConstants.POLICY_LEVEL_API;
int tenantId = 1;
System.setProperty("carbon.home", APIUtilTierTest.class.getResource("/").getFile());
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("abc.com");
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(1);
ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(tenantId);
ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();
PowerMockito.mockStatic(ServiceReferenceHolder.class);
ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
APIMConfigService apimConfigService = Mockito.mock(APIMConfigService.class);
Mockito.when(serviceReferenceHolder.getApimConfigService()).thenReturn(apimConfigService);
Mockito.when(apimConfigService.getTenantConfig("abc.com")).thenReturn(IOUtils.toString(tenantConf));
APIPolicy[] policies = generateApiPoliciesBandwidth(tiersReturned);
Mockito.when(apiMgtDAO.getAPIPolicies(tenantId)).thenReturn(policies);
APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
RealmService realmService = Mockito.mock(RealmService.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
Mockito.when(tenantManager.getDomain(1)).thenReturn("abc.com");
Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
ThrottleProperties throttleProperties = new ThrottleProperties();
throttleProperties.setEnableUnlimitedTier(true);
Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
Map<String, Tier> tiersFromPolicies = APIUtil.getTiersFromPolicies(policyLevel, tenantId);
Mockito.verify(apiMgtDAO, Mockito.only()).getAPIPolicies(tenantId);
for (APIPolicy policy : policies) {
Tier tier = tiersFromPolicies.get(policy.getPolicyName());
Assert.assertNotNull(tier);
Assert.assertEquals(policy.getPolicyName(), tier.getName());
Assert.assertEquals(policy.getDescription(), tier.getDescription());
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
use of org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy in project carbon-apimgt by wso2.
the class APIUtilTierTest method generateApiPoliciesBandwidth.
private APIPolicy[] generateApiPoliciesBandwidth(String[] policyNames) {
List<APIPolicy> policyList = new ArrayList<APIPolicy>();
for (String policyName : policyNames) {
APIPolicy policy = new APIPolicy(policyName);
QuotaPolicy quotaPolicy = new QuotaPolicy();
BandwidthLimit bandwidthLimit = new BandwidthLimit();
bandwidthLimit.setDataAmount(1000);
bandwidthLimit.setDataUnit("seconds");
quotaPolicy.setLimit(bandwidthLimit);
policy.setDefaultQuotaPolicy(quotaPolicy);
policy.setDescription(policyName);
policyList.add(policy);
}
APIPolicy[] array = {};
return policyList.toArray(array);
}
use of org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy in project carbon-apimgt by wso2.
the class ApiMgtDAO method updateAPIPolicy.
/**
* Update a API level throttling policy to database.
* <p>
* If condition group already exists for the policy, that condition Group will be deleted and condition Group will
* be inserted to the database with old POLICY_ID.
* </p>
*
* @param policy policy object defining the throttle policy
* @throws APIManagementException
*/
public APIPolicy updateAPIPolicy(APIPolicy policy) throws APIManagementException {
String updateQuery;
int policyId = 0;
String selectQuery;
if (policy != null) {
if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
selectQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICY_ID_SQL;
updateQuery = SQLConstants.ThrottleSQLConstants.UPDATE_API_POLICY_SQL;
} else if (!StringUtils.isBlank(policy.getUUID())) {
selectQuery = SQLConstants.ThrottleSQLConstants.GET_API_POLICY_ID_BY_UUID_SQL;
updateQuery = ThrottleSQLConstants.UPDATE_API_POLICY_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);
}
} else {
String errorMsg = "Provided Policy to update is null";
log.error(errorMsg);
throw new APIManagementException(errorMsg);
}
try (Connection connection = APIMgtDBUtil.getConnection()) {
connection.setAutoCommit(false);
try (PreparedStatement selectStatement = connection.prepareStatement(selectQuery);
PreparedStatement deleteStatement = connection.prepareStatement(SQLConstants.ThrottleSQLConstants.DELETE_CONDITION_GROUP_SQL);
PreparedStatement updateStatement = connection.prepareStatement(updateQuery)) {
if (selectQuery.equals(SQLConstants.ThrottleSQLConstants.GET_API_POLICY_ID_SQL)) {
selectStatement.setString(1, policy.getPolicyName());
selectStatement.setInt(2, policy.getTenantId());
} else {
selectStatement.setString(1, policy.getUUID());
}
try (ResultSet resultSet = selectStatement.executeQuery()) {
if (resultSet.next()) {
policyId = resultSet.getInt(ThrottlePolicyConstants.COLUMN_POLICY_ID);
}
}
deleteStatement.setInt(1, policyId);
deleteStatement.executeUpdate();
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());
} else if (PolicyConstants.EVENT_COUNT_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
EventCountLimit limit = (EventCountLimit) policy.getDefaultQuotaPolicy().getLimit();
updateStatement.setLong(4, limit.getEventCount());
updateStatement.setString(5, null);
}
updateStatement.setLong(6, policy.getDefaultQuotaPolicy().getLimit().getUnitTime());
updateStatement.setString(7, policy.getDefaultQuotaPolicy().getLimit().getTimeUnit());
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());
}
int updatedRawCount = updateStatement.executeUpdate();
if (updatedRawCount > 0) {
List<Pipeline> pipelines = policy.getPipelines();
if (pipelines != null) {
for (Pipeline pipeline : pipelines) {
// add each pipeline data to AM_CONDITION_GROUP table
addPipeline(pipeline, policyId, connection);
}
}
}
connection.commit();
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException ex) {
// rollback failed. exception will be thrown later for upper exception
log.error("Failed to rollback the add Global Policy: " + policy.toString(), ex);
}
handleException("Failed to update API policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
}
} catch (SQLException e) {
handleException("Failed to update API policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
}
return policy;
}
use of org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy in project carbon-apimgt by wso2.
the class SubscriptionValidationDAO method getApiPolicyByNameForTenant.
/*
* @param policyName : name of an application level throttling policy
* @return {@link ApplicationPolicy}
* */
public APIPolicy getApiPolicyByNameForTenant(String policyName, String tenantDomain) {
APIPolicy policy = null;
try (Connection conn = APIMgtDBUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(SubscriptionValidationSQLConstants.GET_TENANT_API_POLICY_SQL)) {
int tenantId = 0;
try {
tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
log.error("Error in loading ApplicationPolicy for tenantDomain : " + tenantDomain, e);
}
ps.setInt(1, tenantId);
ps.setString(2, policyName);
try (ResultSet resultSet = ps.executeQuery()) {
List<APIPolicy> apiPolicies = populateApiPolicyList(resultSet);
if (!apiPolicies.isEmpty()) {
policy = apiPolicies.get(0);
}
}
} catch (SQLException e) {
log.error("Error in loading application policies by policyId : " + policyName + " of " + policyName, e);
}
return policy;
}
use of org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy in project carbon-apimgt by wso2.
the class ApiMgtDAO method setCommonPolicyDetails.
/**
* Populated common attributes of policy type objects to <code>policy</code>
* from <code>resultSet</code>
*
* @param policy initiallized {@link Policy} object to populate
* @param resultSet {@link ResultSet} with data to populate <code>policy</code>
* @throws SQLException
*/
private void setCommonPolicyDetails(Policy policy, ResultSet resultSet) throws SQLException {
QuotaPolicy quotaPolicy = new QuotaPolicy();
String prefix = "";
if (policy instanceof APIPolicy) {
prefix = "DEFAULT_";
}
quotaPolicy.setType(resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_QUOTA_POLICY_TYPE));
if (resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_QUOTA_POLICY_TYPE).equalsIgnoreCase(PolicyConstants.REQUEST_COUNT_TYPE)) {
RequestCountLimit reqLimit = new RequestCountLimit();
reqLimit.setUnitTime(resultSet.getInt(prefix + ThrottlePolicyConstants.COLUMN_UNIT_TIME));
reqLimit.setTimeUnit(resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_TIME_UNIT));
reqLimit.setRequestCount(resultSet.getInt(prefix + ThrottlePolicyConstants.COLUMN_QUOTA));
quotaPolicy.setLimit(reqLimit);
} else if (resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_QUOTA_POLICY_TYPE).equalsIgnoreCase(PolicyConstants.BANDWIDTH_TYPE)) {
BandwidthLimit bandLimit = new BandwidthLimit();
bandLimit.setUnitTime(resultSet.getInt(prefix + ThrottlePolicyConstants.COLUMN_UNIT_TIME));
bandLimit.setTimeUnit(resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_TIME_UNIT));
bandLimit.setDataAmount(resultSet.getInt(prefix + ThrottlePolicyConstants.COLUMN_QUOTA));
bandLimit.setDataUnit(resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_QUOTA_UNIT));
quotaPolicy.setLimit(bandLimit);
} else if (resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_QUOTA_POLICY_TYPE).equalsIgnoreCase(PolicyConstants.EVENT_COUNT_TYPE)) {
EventCountLimit eventCountLimit = new EventCountLimit();
eventCountLimit.setUnitTime(resultSet.getInt(prefix + ThrottlePolicyConstants.COLUMN_UNIT_TIME));
eventCountLimit.setTimeUnit(resultSet.getString(prefix + ThrottlePolicyConstants.COLUMN_TIME_UNIT));
eventCountLimit.setEventCount(resultSet.getInt(prefix + ThrottlePolicyConstants.COLUMN_QUOTA));
quotaPolicy.setLimit(eventCountLimit);
}
policy.setUUID(resultSet.getString(ThrottlePolicyConstants.COLUMN_UUID));
policy.setDescription(resultSet.getString(ThrottlePolicyConstants.COLUMN_DESCRIPTION));
policy.setDisplayName(resultSet.getString(ThrottlePolicyConstants.COLUMN_DISPLAY_NAME));
policy.setPolicyId(resultSet.getInt(ThrottlePolicyConstants.COLUMN_POLICY_ID));
policy.setTenantId(resultSet.getInt(ThrottlePolicyConstants.COLUMN_TENANT_ID));
policy.setTenantDomain(IdentityTenantUtil.getTenantDomain(policy.getTenantId()));
policy.setDefaultQuotaPolicy(quotaPolicy);
policy.setDeployed(resultSet.getBoolean(ThrottlePolicyConstants.COLUMN_DEPLOYED));
}
Aggregations