use of org.wso2.carbon.identity.configuration.mgt.core.search.Condition in project carbon-apimgt by wso2.
the class ThrottlePolicyTemplateBuilder method getThrottlePolicyForAPILevel.
/**
* Generate policy for API level throttling
*
* @param policy Policy with level 'api'. Policy can have multiple pipelines and a default condition which will be
* used as else condition
* @return a Map containing a set of policies for each condition group
* @throws APITemplateException if failed to generate policy
*/
public Map<String, String> getThrottlePolicyForAPILevel(ApiPolicy policy) throws APITemplateException {
if (log.isDebugEnabled()) {
log.debug("Generating policy for API Level :" + policy.toString());
}
Map<String, String> policyArray = new HashMap<>();
try {
VelocityEngine velocityengine = new VelocityEngine();
APIUtil.initializeVelocityContext(velocityengine);
velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
velocityengine.init();
Template template = velocityengine.getTemplate(getTemplatePathForAPI());
StringWriter writer;
VelocityContext context;
if (policy.getConditionGroups() != null) {
for (APIPolicyConditionGroup conditionGroup : policy.getConditionGroups()) {
if (conditionGroup.getDefaultLimit() == null) {
continue;
}
context = new VelocityContext();
setConstantContext(context);
context.put("policy", policy);
context.put("quotaPolicy", conditionGroup.getDefaultLimit());
context.put("pipeline", "condition_" + conditionGroup.getConditionGroupId());
String conditionString = getPolicyCondition(conditionGroup.getCondition());
JSONArray conditions = new JSONArray();
conditions.add(getPolicyConditionJson(conditionGroup.getCondition()));
context.put("condition", " AND " + conditionString);
context.put("evaluatedConditions", new String(Base64.encodeBase64(conditions.toJSONString().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
writer = new StringWriter();
template.merge(context, writer);
if (log.isDebugEnabled()) {
log.debug("Policy : " + writer.toString());
}
String policyName = policy.getTenantDomain() + APIConstants.DELEM_UNDERSCORE + PolicyConstants.POLICY_LEVEL_RESOURCE + APIConstants.DELEM_UNDERSCORE + policy.getName() + APIConstants.THROTTLE_POLICY_CONDITION + conditionGroup.getConditionGroupId();
policyArray.put(policyName, writer.toString());
}
}
} catch (VelocityException e) {
log.error("Velocity Error", e);
throw new APITemplateException("Velocity Error", e);
}
return policyArray;
}
use of org.wso2.carbon.identity.configuration.mgt.core.search.Condition in project carbon-apimgt by wso2.
the class APIMappingUtil method handleAWSCredentials.
/**
* Set AWS Secret Key based on preserveCredentials state
*
* @param awsEndpointConfig Endpoint configuration of the API
* @param preserveCredentials Condition to preserve credentials
* @return Updated endpoint config
*/
private static JSONObject handleAWSCredentials(JSONObject awsEndpointConfig, boolean preserveCredentials) {
if (StringUtils.isNotEmpty((String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY))) {
if (!preserveCredentials) {
awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, APIConstants.AWS_SECRET_KEY);
return awsEndpointConfig;
} else {
String secretKey = (String) awsEndpointConfig.get(APIConstants.AMZN_SECRET_KEY);
// Decrypting the key since CTL project goes between environments which have different encryption keys.
try {
CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();
String decryptedSecret = new String(cryptoUtil.base64DecodeAndDecrypt(secretKey), APIConstants.DigestAuthConstants.CHARSET);
awsEndpointConfig.put(APIConstants.AMZN_SECRET_KEY, decryptedSecret);
return awsEndpointConfig;
} catch (CryptoException | UnsupportedEncodingException e) {
log.error("Error while decrypting the Amazon key", e);
}
}
}
return awsEndpointConfig;
}
use of org.wso2.carbon.identity.configuration.mgt.core.search.Condition in project carbon-apimgt by wso2.
the class SearchResultMappingUtil method setPaginationParams.
/**
* Sets pagination urls for a SearchResultListDTO object given pagination parameters and url parameters.
*
* @param resultListDTO a SearchResultListDTO object
* @param query search condition
* @param limit max number of objects returned
* @param offset starting index
* @param size max offset
*/
public static void setPaginationParams(SearchResultListDTO resultListDTO, String query, int offset, int limit, int size) {
// acquiring pagination parameters and setting pagination urls
Map<String, Integer> paginatedParams = RestApiCommonUtil.getPaginationParams(offset, limit, size);
String paginatedPrevious = "";
String paginatedNext = "";
if (paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET) != null) {
paginatedPrevious = RestApiCommonUtil.getAPIPaginatedURL(paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_LIMIT), query);
}
if (paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET) != null) {
paginatedNext = RestApiCommonUtil.getAPIPaginatedURL(paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_NEXT_LIMIT), query);
}
PaginationDTO paginationDTO = new PaginationDTO();
paginationDTO.setNext(paginatedNext);
paginationDTO.setPrevious(paginatedPrevious);
paginationDTO.setOffset(offset);
paginationDTO.setLimit(limit);
paginationDTO.setTotal(size);
resultListDTO.setPagination(paginationDTO);
}
use of org.wso2.carbon.identity.configuration.mgt.core.search.Condition in project carbon-apimgt by wso2.
the class PolicyMappingUtil method mapCondition.
/**
* Map a org.wso2.carbon.apimgt.throttle.policy.deployer.dto.Condition to a
* org.wso2.carbon.apimgt.api.model.policy.Condition
*
* @param conditionDTO org.wso2.carbon.apimgt.throttle.policy.deployer.dto.Condition
* @return org.wso2.carbon.apimgt.api.model.policy.Condition object
*/
public static Condition mapCondition(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.Condition conditionDTO) {
switch(conditionDTO.getConditionType()) {
case PolicyConstants.IP_RANGE_TYPE:
IPCondition ipRangeCondition = new IPCondition(PolicyConstants.IP_RANGE_TYPE);
ipRangeCondition.setInvertCondition(conditionDTO.isInverted());
ipRangeCondition.setStartingIP(conditionDTO.getName());
ipRangeCondition.setEndingIP(conditionDTO.getValue());
return ipRangeCondition;
case PolicyConstants.IP_SPECIFIC_TYPE:
IPCondition ipSpecificCondition = new IPCondition(PolicyConstants.IP_SPECIFIC_TYPE);
ipSpecificCondition.setInvertCondition(conditionDTO.isInverted());
ipSpecificCondition.setSpecificIP(conditionDTO.getValue());
return ipSpecificCondition;
case PolicyConstants.HEADER_TYPE:
HeaderCondition headerCondition = new HeaderCondition();
headerCondition.setInvertCondition(conditionDTO.isInverted());
headerCondition.setHeader(conditionDTO.getName());
headerCondition.setValue(conditionDTO.getValue());
return headerCondition;
case PolicyConstants.JWT_CLAIMS_TYPE:
JWTClaimsCondition jwtClaimsCondition = new JWTClaimsCondition();
jwtClaimsCondition.setInvertCondition(conditionDTO.isInverted());
jwtClaimsCondition.setClaimUrl(conditionDTO.getName());
jwtClaimsCondition.setAttribute(conditionDTO.getValue());
return jwtClaimsCondition;
case PolicyConstants.QUERY_PARAMETER_TYPE:
QueryParameterCondition queryParameterCondition = new QueryParameterCondition();
queryParameterCondition.setInvertCondition(conditionDTO.isInverted());
queryParameterCondition.setParameter(conditionDTO.getName());
queryParameterCondition.setValue(conditionDTO.getValue());
return queryParameterCondition;
default:
return null;
}
}
use of org.wso2.carbon.identity.configuration.mgt.core.search.Condition 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