use of org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy in project carbon-apimgt by wso2.
the class SubscriptionValidationDataUtil method fromGlobalPolicyToGlobalPolicyListDTO.
/**
* Converts a list of global policy objects into a global policy list DTO object.
*
* @param globalPolicies list of global policy objects
* @return global policy list DTO
*/
public static GlobalPolicyListDTO fromGlobalPolicyToGlobalPolicyListDTO(List<GlobalPolicy> globalPolicies) {
GlobalPolicyListDTO globalPolicyListDTO = new GlobalPolicyListDTO();
if (globalPolicies != null) {
for (GlobalPolicy globalPolicy : globalPolicies) {
GlobalPolicyDTO globalPolicyDTO = new GlobalPolicyDTO();
globalPolicyDTO.setId(globalPolicy.getId());
globalPolicyDTO.setName(globalPolicy.getName());
globalPolicyDTO.setTenantId(globalPolicy.getTenantId());
globalPolicyDTO.setTenantDomain(globalPolicy.getTenantDomain());
globalPolicyDTO.setSiddhiQuery(globalPolicy.getSiddhiQuery());
globalPolicyDTO.setKeyTemplate(globalPolicy.getKeyTemplate());
globalPolicyListDTO.getList().add(globalPolicyDTO);
}
globalPolicyListDTO.setCount(globalPolicies.size());
} else {
globalPolicyListDTO.setCount(0);
}
return globalPolicyListDTO;
}
use of org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy in project carbon-apimgt by wso2.
the class ApiMgtDAO method updateGlobalPolicy.
/**
* Updates global throttle policy in database
*
* @param policy updated policy obejct
* @throws APIManagementException
*/
public void updateGlobalPolicy(GlobalPolicy policy) throws APIManagementException {
Connection connection = null;
PreparedStatement updateStatement = null;
InputStream siddhiQueryInputStream;
try {
byte[] byteArray = policy.getSiddhiQuery().getBytes(Charset.defaultCharset());
int lengthOfBytes = byteArray.length;
siddhiQueryInputStream = new ByteArrayInputStream(byteArray);
connection = APIMgtDBUtil.getConnection();
connection.setAutoCommit(false);
if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
updateStatement = connection.prepareStatement(SQLConstants.UPDATE_GLOBAL_POLICY_SQL);
} else if (!StringUtils.isBlank(policy.getUUID())) {
updateStatement = connection.prepareStatement(SQLConstants.UPDATE_GLOBAL_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);
}
updateStatement.setString(1, policy.getDescription());
updateStatement.setBinaryStream(2, siddhiQueryInputStream, lengthOfBytes);
updateStatement.setString(3, policy.getKeyTemplate());
if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
updateStatement.setString(4, policy.getPolicyName());
updateStatement.setInt(5, policy.getTenantId());
} else if (!StringUtils.isBlank(policy.getUUID())) {
updateStatement.setString(4, 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 Global Policy: " + policy.toString(), ex);
}
}
handleException("Failed to update global policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
} finally {
APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
}
}
use of org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy in project carbon-apimgt by wso2.
the class AbstractAPIManagerTestCase method testGetPolicies.
@Test
public void testGetPolicies() throws APIManagementException, org.wso2.carbon.user.api.UserStoreException, RegistryException, XMLStreamException {
APIPolicy[] policies1 = { new APIPolicy("policy1") };
ApplicationPolicy[] policies2 = { new ApplicationPolicy("policy2"), new ApplicationPolicy("policy3") };
SubscriptionPolicy[] policies3 = { new SubscriptionPolicy("policy4"), new SubscriptionPolicy("policy5"), new SubscriptionPolicy("policy6") };
GlobalPolicy[] policies4 = { new GlobalPolicy("policy7"), new GlobalPolicy("policy8"), new GlobalPolicy("policy9"), new GlobalPolicy("policy0") };
PowerMockito.mockStatic(APIUtil.class);
BDDMockito.when(APIUtil.getTenantId(Mockito.anyString())).thenReturn(-1234);
PowerMockito.when(APIUtil.replaceSystemProperty(Mockito.anyString())).thenAnswer((Answer<String>) invocation -> {
Object[] args = invocation.getArguments();
return (String) args[0];
});
AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(apiMgtDAO);
Mockito.when(apiMgtDAO.getAPIPolicies(Mockito.anyInt())).thenReturn(policies1);
Mockito.when(apiMgtDAO.getApplicationPolicies(Mockito.anyInt())).thenReturn(policies2);
Mockito.when(apiMgtDAO.getSubscriptionPolicies(Mockito.anyInt())).thenReturn(policies3);
Mockito.when(apiMgtDAO.getGlobalPolicies(Mockito.anyInt())).thenReturn(policies4);
ServiceReferenceHolder sh = mockRegistryAndUserRealm(-1234);
APIManagerConfigurationService amConfigService = Mockito.mock(APIManagerConfigurationService.class);
APIManagerConfiguration amConfig = Mockito.mock(APIManagerConfiguration.class);
ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class, Mockito.RETURNS_MOCKS);
PowerMockito.when(sh.getAPIManagerConfigurationService()).thenReturn(amConfigService);
PowerMockito.when(amConfigService.getAPIManagerConfiguration()).thenReturn(amConfig);
PowerMockito.when(amConfig.getThrottleProperties()).thenReturn(throttleProperties);
Assert.assertEquals(abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_API).length, 1);
Assert.assertEquals(abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_APP).length, 2);
PowerMockito.when(throttleProperties.isEnableUnlimitedTier()).thenReturn(false);
Assert.assertEquals(3, abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_SUB).length);
Assert.assertEquals(4, abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_GLOBAL).length);
Assert.assertEquals(0, abstractAPIManager.getPolicies(API_PROVIDER, "Test").length);
}
use of org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy in project carbon-apimgt by wso2.
the class ThrottlePolicyTemplateBuilder method getThrottlePolicyForGlobalLevel.
/**
* Generate policy for global level
*
* @param policy policy with level 'global'. Multiple pipelines are not allowed. Can define more than one condition
* as set of conditions. all these conditions should be passed as a single pipeline
* @return the generated execution plan for the policy
* @throws APITemplateException if failed to generate policy
*/
public String getThrottlePolicyForGlobalLevel(GlobalPolicy policy) throws APITemplateException {
StringWriter writer = new StringWriter();
if (log.isDebugEnabled()) {
log.debug("Generating policy for global level :" + policy.toString());
}
try {
VelocityEngine velocityengine = new VelocityEngine();
APIUtil.initializeVelocityContext(velocityengine);
velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
velocityengine.init();
Template template = velocityengine.getTemplate(getTemplatePathForGlobal());
VelocityContext context = new VelocityContext();
setConstantContext(context);
context.put("policy", policy);
if (log.isDebugEnabled()) {
log.debug("Policy : " + writer.toString());
}
template.merge(context, writer);
} catch (VelocityException e) {
log.error("Velocity Error", e);
throw new APITemplateException("Velocity Error", e);
}
return writer.toString();
}
use of org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy in project carbon-apimgt by wso2.
the class PolicyUtil method deployPolicy.
/**
* Deploy the given throttle policy in the Traffic Manager.
*
* @param policy policy object
* @param policyEvent policy event object which was triggered
*/
public static void deployPolicy(Policy policy, PolicyEvent policyEvent) {
EventProcessorService eventProcessorService = ServiceReferenceHolder.getInstance().getEventProcessorService();
ThrottlePolicyTemplateBuilder policyTemplateBuilder = new ThrottlePolicyTemplateBuilder();
Map<String, String> policiesToDeploy = new HashMap<>();
List<String> policiesToUndeploy = new ArrayList<>();
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(APIConstants.SUPER_TENANT_DOMAIN, true);
String policyFile;
String policyString;
if (Policy.PolicyType.SUBSCRIPTION.equals(policy.getType()) && policy instanceof SubscriptionPolicy) {
// Add Subscription policy
policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_SUB, policy.getName());
policyString = policyTemplateBuilder.getThrottlePolicyForSubscriptionLevel((SubscriptionPolicy) policy);
policiesToDeploy.put(policyFile, policyString);
} else if (Policy.PolicyType.APPLICATION.equals(policy.getType()) && policy instanceof ApplicationPolicy) {
// Add Application policy
policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_APP, policy.getName());
policyString = policyTemplateBuilder.getThrottlePolicyForAppLevel((ApplicationPolicy) policy);
policiesToDeploy.put(policyFile, policyString);
} else if (Policy.PolicyType.API.equals(policy.getType()) && policy instanceof ApiPolicy) {
// Add API policy
policiesToDeploy = policyTemplateBuilder.getThrottlePolicyForAPILevel((ApiPolicy) policy);
String defaultPolicy = policyTemplateBuilder.getThrottlePolicyForAPILevelDefault((ApiPolicy) policy);
policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_RESOURCE, policy.getName());
String defaultPolicyName = policyFile + APIConstants.THROTTLE_POLICY_DEFAULT;
policiesToDeploy.put(defaultPolicyName, defaultPolicy);
if (policyEvent instanceof APIPolicyEvent) {
List<Integer> deletedConditionGroupIds = ((APIPolicyEvent) policyEvent).getDeletedConditionGroupIds();
// Undeploy removed condition groups
if (deletedConditionGroupIds != null) {
for (int conditionGroupId : deletedConditionGroupIds) {
policiesToUndeploy.add(policyFile + APIConstants.THROTTLE_POLICY_CONDITION + conditionGroupId);
}
}
}
} else if (Policy.PolicyType.GLOBAL.equals(policy.getType()) && policy instanceof GlobalPolicy) {
// Add Global policy
GlobalPolicy globalPolicy = (GlobalPolicy) policy;
policyFile = String.join(APIConstants.DELEM_UNDERSCORE, PolicyConstants.POLICY_LEVEL_GLOBAL, policy.getName());
policyString = policyTemplateBuilder.getThrottlePolicyForGlobalLevel(globalPolicy);
policiesToDeploy.put(policyFile, policyString);
}
// Undeploy removed policies
undeployPolicies(policiesToUndeploy);
for (Map.Entry<String, String> pair : policiesToDeploy.entrySet()) {
String policyPlanName = pair.getKey();
String flowString = pair.getValue();
String executionPlan = null;
try {
executionPlan = eventProcessorService.getActiveExecutionPlan(policyPlanName);
} catch (ExecutionPlanConfigurationException e) {
// Deploy new policies
eventProcessorService.deployExecutionPlan(flowString);
}
if (executionPlan != null) {
// Update existing policies
eventProcessorService.editActiveExecutionPlan(flowString, policyPlanName);
}
}
} catch (APITemplateException e) {
log.error("Error in creating execution plan", e);
} catch (ExecutionPlanConfigurationException | ExecutionPlanDependencyValidationException e) {
log.error("Error in deploying execution plan", e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
Aggregations