use of com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType in project midpoint by Evolveum.
the class GenerateExpressionEvaluator method evaluate.
/*
* (non-Javadoc)
*
* @see
* com.evolveum.midpoint.common.expression.ExpressionEvaluator#evaluate(java
* .util.Collection, java.util.Map, boolean, java.lang.String,
* com.evolveum.midpoint.schema.result.OperationResult)
*/
@Override
public PrismValueDeltaSetTriple<V> evaluate(ExpressionEvaluationContext context) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
StringPolicyType stringPolicyType = null;
ObjectReferenceType generateEvaluatorValuePolicyRef = generateEvaluatorType.getValuePolicyRef();
if (generateEvaluatorValuePolicyRef != null) {
if (generateEvaluatorType.getValuePolicyRef() != null) {
ValuePolicyType valuePolicyType = objectResolver.resolve(generateEvaluatorValuePolicyRef, ValuePolicyType.class, null, "resolving value policy reference in generateExpressionEvaluator", context.getTask(), context.getResult());
stringPolicyType = valuePolicyType.getStringPolicy();
}
}
// would be generated
if (stringPolicyType == null) {
StringPolicyResolver stringPolicyResolver = context.getStringPolicyResolver();
if (stringPolicyResolver != null) {
stringPolicyType = stringPolicyResolver.resolve();
}
}
elementStringPolicy = stringPolicyType;
// } else {
// stringPolicyType = elementStringPolicy;
// }
//
String stringValue = null;
GenerateExpressionEvaluatorModeType mode = generateEvaluatorType.getMode();
Item<V, D> output = outputDefinition.instantiate();
if (mode == null || mode == GenerateExpressionEvaluatorModeType.POLICY) {
PrismObject<? extends ObjectType> object = getObject(context);
// TODO: generate value based on stringPolicyType (if not null)
if (stringPolicyType != null) {
if (isNotEmptyMinLength(stringPolicyType)) {
stringValue = valuePolicyGenerator.generate(output.getPath(), stringPolicyType, DEFAULT_LENGTH, true, object, context.getContextDescription(), context.getTask(), context.getResult());
} else {
stringValue = valuePolicyGenerator.generate(output.getPath(), stringPolicyType, DEFAULT_LENGTH, false, object, context.getContextDescription(), context.getTask(), context.getResult());
}
context.getResult().computeStatus();
if (context.getResult().isError()) {
throw new ExpressionEvaluationException("Failed to generate value according to policy: " + stringPolicyType.getDescription() + ". " + context.getResult().getMessage());
}
}
if (stringValue == null) {
int length = DEFAULT_LENGTH;
RandomString randomString = new RandomString(length);
stringValue = randomString.nextString();
}
} else if (mode == GenerateExpressionEvaluatorModeType.UUID) {
UUID randomUUID = UUID.randomUUID();
stringValue = randomUUID.toString();
} else {
throw new ExpressionEvaluationException("Unknown mode for generate expression: " + mode);
}
Object value = ExpressionUtil.convertToOutputValue(stringValue, outputDefinition, protector);
if (output instanceof PrismProperty) {
PrismPropertyValue<Object> pValue = new PrismPropertyValue<Object>(value);
((PrismProperty<Object>) output).add(pValue);
} else {
throw new UnsupportedOperationException("Can only generate values of property, not " + output.getClass());
}
return ItemDelta.toDeltaSetTriple(output, null);
}
use of com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType in project midpoint by Evolveum.
the class StringPolicyUtils method normalize.
public static StringPolicyType normalize(StringPolicyType sp) {
if (null == sp) {
throw new IllegalArgumentException("Providide string policy cannot be null");
}
if (null == sp.getLimitations()) {
LimitationsType sl = new LimitationsType();
sl.setCheckAgainstDictionary(false);
sl.setCheckPattern("");
sl.setMaxLength(-1);
sl.setMinLength(0);
sl.setMinUniqueChars(0);
sp.setLimitations(sl);
}
// Add default char class
if (null == sp.getCharacterClass()) {
CharacterClassType cct = new CharacterClassType();
cct.setValue(ASCII7_CHARS);
sp.setCharacterClass(cct);
}
return sp;
}
use of com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType in project midpoint by Evolveum.
the class ValuePolicyProcessor method generateAttempt.
private String generateAttempt(StringPolicyType policy, int defaultLength, boolean generateMinimalSize, OperationResult result) {
// if (policy.getLimitations() != null &&
// policy.getLimitations().getMinLength() != null){
// generateMinimalSize = true;
// }
// setup default values where missing
// PasswordPolicyUtils.normalize(pp);
// Optimize usage of limits ass hashmap of limitas and key is set of
// valid chars for each limitation
Map<StringLimitType, List<String>> lims = new HashMap<StringLimitType, List<String>>();
int minLen = defaultLength;
int maxLen = defaultLength;
int unique = defaultLength / 2;
if (policy != null) {
for (StringLimitType l : policy.getLimitations().getLimit()) {
if (null != l.getCharacterClass().getValue()) {
lims.put(l, StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue()));
} else {
lims.put(l, StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass(policy.getCharacterClass(), l.getCharacterClass().getRef())));
}
}
// Get global limitations
minLen = policy.getLimitations().getMinLength() == null ? 0 : policy.getLimitations().getMinLength().intValue();
if (minLen != 0 && minLen > defaultLength) {
defaultLength = minLen;
}
maxLen = (policy.getLimitations().getMaxLength() == null ? 0 : policy.getLimitations().getMaxLength().intValue());
unique = policy.getLimitations().getMinUniqueChars() == null ? minLen : policy.getLimitations().getMinUniqueChars().intValue();
}
// test correctness of definition
if (unique > minLen) {
minLen = unique;
OperationResult reportBug = new OperationResult("Global limitation check");
reportBug.recordWarning("There is more required uniq characters then definied minimum. Raise minimum to number of required uniq chars.");
}
if (minLen == 0 && maxLen == 0) {
minLen = defaultLength;
maxLen = defaultLength;
generateMinimalSize = true;
}
if (maxLen == 0) {
if (minLen > defaultLength) {
maxLen = minLen;
} else {
maxLen = defaultLength;
}
}
// Initialize generator
StringBuilder password = new StringBuilder();
/*
* ********************************** Try to find best characters to be
* first in password
*/
Map<StringLimitType, List<String>> mustBeFirst = new HashMap<StringLimitType, List<String>>();
for (StringLimitType l : lims.keySet()) {
if (l.isMustBeFirst() != null && l.isMustBeFirst()) {
mustBeFirst.put(l, lims.get(l));
}
}
// If any limitation was found to be first
if (!mustBeFirst.isEmpty()) {
Map<Integer, List<String>> posibleFirstChars = cardinalityCounter(mustBeFirst, null, false, false, result);
int intersectionCardinality = mustBeFirst.keySet().size();
List<String> intersectionCharacters = posibleFirstChars.get(intersectionCardinality);
// If no intersection was found then raise error
if (null == intersectionCharacters || intersectionCharacters.size() == 0) {
result.recordFatalError("No intersection for required first character sets in value policy:" + policy.getDescription());
// Log error
if (LOGGER.isErrorEnabled()) {
LOGGER.error("Unable to generate value for " + getPath() + ": No intersection for required first character sets in value policy: [" + policy.getDescription() + "] following character limitation and sets are used:");
for (StringLimitType l : mustBeFirst.keySet()) {
StrBuilder tmp = new StrBuilder();
tmp.appendSeparator(", ");
tmp.appendAll(mustBeFirst.get(l));
LOGGER.error("L:" + l.getDescription() + " -> [" + tmp + "]");
}
}
// EXIT
return null;
} else {
if (LOGGER.isDebugEnabled()) {
StrBuilder tmp = new StrBuilder();
tmp.appendSeparator(", ");
tmp.appendAll(intersectionCharacters);
LOGGER.trace("Generate first character intersection items [" + tmp + "] into " + getPath() + ".");
}
// Generate random char into password from intersection
password.append(intersectionCharacters.get(RAND.nextInt(intersectionCharacters.size())));
}
}
/*
* ************************************** Generate rest to fulfill
* minimal criteria
*/
boolean uniquenessReached = false;
// Count cardinality of elements
Map<Integer, List<String>> chars;
for (int i = 0; i < minLen; i++) {
// Check if still unique chars are needed
if (password.length() >= unique) {
uniquenessReached = true;
}
// Find all usable characters
chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), false, uniquenessReached, result);
// If something goes badly then go out
if (null == chars) {
return null;
}
if (chars.isEmpty()) {
LOGGER.trace("Minimal criterias was met. No more characters");
break;
}
// Find lowest possible cardinality and then generate char
for (int card = 1; card < lims.keySet().size(); card++) {
if (chars.containsKey(card)) {
List<String> validChars = chars.get(card);
password.append(validChars.get(RAND.nextInt(validChars.size())));
break;
}
}
}
// test if maximum is not exceeded
if (password.length() > maxLen) {
result.recordFatalError("Unable to meet minimal criteria and not exceed maximxal size of " + getPath() + ".");
return null;
}
for (int i = 0; i < minLen; i++) {
// test if max is reached
if (password.length() == maxLen) {
// no more characters maximal size is reached
break;
}
if (password.length() >= minLen && generateMinimalSize) {
// no more characters are needed
break;
}
// Check if still unique chars are needed
if (password.length() >= unique) {
uniquenessReached = true;
}
// find all usable characters
chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), true, uniquenessReached, result);
// If something goes badly then go out
if (null == chars) {
// we hope this never happend.
result.recordFatalError("No valid characters to generate, but no all limitation are reached");
return null;
}
// our work
if (chars.isEmpty()) {
if (i == 0) {
password.append(RandomStringUtils.randomAlphanumeric(minLen));
}
break;
// if (!StringUtils.isBlank(password.toString()) &&
// password.length() >= minLen) {
// break;
// }
// check uf this is a firs cycle and if we need to user some
// default (alphanum) character class.
}
// Find lowest possible cardinality and then generate char
for (int card = 1; card <= lims.keySet().size(); card++) {
if (chars.containsKey(card)) {
List<String> validChars = chars.get(card);
password.append(validChars.get(RAND.nextInt(validChars.size())));
break;
}
}
}
if (password.length() < minLen) {
result.recordFatalError("Unable to generate value for " + getPath() + " and meet minimal size of " + getPath() + ". Actual lenght: " + password.length() + ", required: " + minLen);
LOGGER.trace("Unable to generate value for " + getPath() + " and meet minimal size of " + getPath() + ". Actual lenght: {}, required: {}", password.length(), minLen);
return null;
}
result.recordSuccess();
// Shuffle output to solve pattern like output
StrBuilder sb = new StrBuilder(password.substring(0, 1));
List<String> shuffleBuffer = StringPolicyUtils.stringTokenizer(password.substring(1));
Collections.shuffle(shuffleBuffer);
sb.appendAll(shuffleBuffer);
return sb.toString();
}
use of com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType in project midpoint by Evolveum.
the class OutboundProcessor method evaluateMapping.
private <F extends FocusType, V extends PrismValue, D extends ItemDefinition> Mapping<V, D> evaluateMapping(final Mapping.Builder<V, D> mappingBuilder, QName mappingQName, D targetDefinition, ObjectDeltaObject<F> focusOdo, ObjectDeltaObject<ShadowType> projectionOdo, String operation, RefinedObjectClassDefinition rOcDef, RefinedObjectClassDefinition assocTargetObjectClassDefinition, LensContext<F> context, LensProjectionContext projCtx, final Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
if (!mappingBuilder.isApplicableToChannel(context.getChannel())) {
LOGGER.trace("Skipping outbound mapping for {} because the channel does not match", mappingQName);
return null;
}
// TODO: check access
// This is just supposed to be an optimization. The consolidation should deal with the weak mapping
// even if it is there. But in that case we do not need to evaluate it at all.
// Edit 2017-02-16 pmed: It's not quite true. If the attribute is non-tolerant, it will get removed if we would
// skip evaluation of this mapping. So we really need to do this.
// if (mappingBuilder.getStrength() == MappingStrengthType.WEAK && projCtx.hasValueForAttribute(mappingQName)) {
// LOGGER.trace("Skipping outbound mapping for {} because it is weak", mappingQName);
// return null;
// }
mappingBuilder.setDefaultTargetDefinition(targetDefinition);
mappingBuilder.setSourceContext(focusOdo);
mappingBuilder.setMappingQName(mappingQName);
mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_USER, focusOdo);
mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_FOCUS, focusOdo);
mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ACCOUNT, projectionOdo);
mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_SHADOW, projectionOdo);
mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_PROJECTION, projectionOdo);
mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_CONFIGURATION, context.getSystemConfiguration());
mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ITERATION, LensUtil.getIterationVariableValue(projCtx));
mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ITERATION_TOKEN, LensUtil.getIterationTokenVariableValue(projCtx));
mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_RESOURCE, projCtx.getResource());
mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_OPERATION, operation);
if (assocTargetObjectClassDefinition != null) {
mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ASSOCIATION_TARGET_OBJECT_CLASS_DEFINITION, assocTargetObjectClassDefinition);
}
mappingBuilder.setRootNode(focusOdo);
mappingBuilder.setOriginType(OriginType.OUTBOUND);
mappingBuilder.setRefinedObjectClassDefinition(rOcDef);
StringPolicyResolver stringPolicyResolver = new StringPolicyResolver() {
private ItemPath outputPath;
private ItemDefinition outputDefinition;
@Override
public void setOutputPath(ItemPath outputPath) {
this.outputPath = outputPath;
}
@Override
public void setOutputDefinition(ItemDefinition outputDefinition) {
this.outputDefinition = outputDefinition;
}
@Override
public StringPolicyType resolve() {
if (mappingBuilder.getMappingType().getExpression() != null) {
List<JAXBElement<?>> evaluators = mappingBuilder.getMappingType().getExpression().getExpressionEvaluator();
for (JAXBElement jaxbEvaluator : evaluators) {
Object object = jaxbEvaluator.getValue();
if (object instanceof GenerateExpressionEvaluatorType && ((GenerateExpressionEvaluatorType) object).getValuePolicyRef() != null) {
ObjectReferenceType ref = ((GenerateExpressionEvaluatorType) object).getValuePolicyRef();
try {
ValuePolicyType valuePolicyType = mappingBuilder.getObjectResolver().resolve(ref, ValuePolicyType.class, null, "resolving value policy for generate attribute " + outputDefinition.getName() + "value", task, new OperationResult("Resolving value policy"));
if (valuePolicyType != null) {
return valuePolicyType.getStringPolicy();
}
} catch (CommonException ex) {
throw new SystemException(ex.getMessage(), ex);
}
}
}
}
return null;
}
};
mappingBuilder.setStringPolicyResolver(stringPolicyResolver);
// (e.g. in old values in ADD situations and new values in DELETE situations).
if (focusOdo.getOldObject() == null) {
mappingBuilder.setConditionMaskOld(false);
}
if (focusOdo.getNewObject() == null) {
mappingBuilder.setConditionMaskNew(false);
}
Mapping<V, D> mapping = mappingBuilder.build();
mappingEvaluator.evaluateMapping(mapping, context, projCtx, task, result);
return mapping;
}
use of com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType in project midpoint by Evolveum.
the class TestPasswordPolicy method stringPolicyUtilsMinimalTest.
@Test
public void stringPolicyUtilsMinimalTest() throws JAXBException, SchemaException, IOException {
File file = new File(TEST_DIR, "password-policy-minimal.xml");
ValuePolicyType pp = (ValuePolicyType) PrismTestUtil.parseObject(file).asObjectable();
StringPolicyType sp = pp.getStringPolicy();
StringPolicyUtils.normalize(sp);
AssertJUnit.assertNotNull(sp.getCharacterClass());
AssertJUnit.assertNotNull(sp.getLimitations().getLimit());
AssertJUnit.assertTrue(-1 == sp.getLimitations().getMaxLength());
AssertJUnit.assertTrue(0 == sp.getLimitations().getMinLength());
AssertJUnit.assertTrue(0 == " !\"#$%&'()*+,-.01234567890:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~".compareTo(sp.getCharacterClass().getValue()));
}
Aggregations