<commit_before>/*
 * Copyright (c) 2010-2013 Evolveum
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.evolveum.midpoint.common.policy;

/**
 * 
 *  @author mamut
 *  
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;

import javax.xml.namespace.QName;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;

import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.util.RandomString;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CharacterClassType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringLimitType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType;

public class ValuePolicyGenerator {

	private static final transient Trace LOGGER = TraceManager.getTrace(ValuePolicyGenerator.class);

	private static final Random rand = new Random(System.currentTimeMillis());

	public static String generate(StringPolicyType policy, int defaultLength, OperationResult inputResult) {
		return generate(policy, defaultLength, false, inputResult);
	}

	public static String generate(StringPolicyType policy, int defaultLength, boolean generateMinimalSize,
			OperationResult inputResult) {

		if (null == policy) {
			throw new IllegalArgumentException("Provided password policy can not be null.");
		}

		if (null == inputResult) {
			throw new IllegalArgumentException("Provided operation result cannot be null");
		}
		// Define result from generator
		OperationResult generatorResult = new OperationResult("Password generator running policy :"
				+ policy.getDescription());
		inputResult.addSubresult(generatorResult);

		// 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
		HashMap<StringLimitType, ArrayList<String>> lims = new HashMap<StringLimitType, ArrayList<String>>();
		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
		int minLen = policy.getLimitations().getMinLength() == null ? 0 : policy.getLimitations().getMinLength()
				.intValue();
		if (minLen != 0 && minLen > defaultLength) {
			defaultLength = minLen;
		}
		int maxLen = (policy.getLimitations().getMaxLength() == null ? 0 : policy.getLimitations()
				.getMaxLength().intValue());
		int 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;
		}

		// Initialize generator
		StringBuilder password = new StringBuilder();

		/* **********************************
		 * Try to find best characters to be first in password
		 */
		HashMap<StringLimitType, ArrayList<String>> mustBeFirst = new HashMap<StringLimitType, ArrayList<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()) {
			HashMap<Integer, ArrayList<String>> posibleFirstChars = cardinalityCounter(mustBeFirst, null, false, false,
					generatorResult);<commit_msg>fixing password generation according to password policy (MID-1889)<commit_after>/*
 * Copyright (c) 2010-2013 Evolveum
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.evolveum.midpoint.common.policy;

/**
 * 
 *  @author mamut
 *  
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;

import javax.xml.namespace.QName;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrBuilder;

import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.util.RandomString;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CharacterClassType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringLimitType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType;

public class ValuePolicyGenerator {

	private static final transient Trace LOGGER = TraceManager.getTrace(ValuePolicyGenerator.class);

	private static final Random rand = new Random(System.currentTimeMillis());

	public static String generate(StringPolicyType policy, int defaultLength, OperationResult inputResult) {
		return generate(policy, defaultLength, false, inputResult);
	}

	public static String generate(StringPolicyType policy, int defaultLength, boolean generateMinimalSize,
			OperationResult inputResult) {

		if (null == policy) {
			throw new IllegalArgumentException("Provided password policy can not be null.");
		}

		if (null == inputResult) {
			throw new IllegalArgumentException("Provided operation result cannot be null");
		}
		// Define result from generator
		OperationResult generatorResult = new OperationResult("Password generator running policy :"
				+ policy.getDescription());
		inputResult.addSubresult(generatorResult);

		// 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
		HashMap<StringLimitType, ArrayList<String>> lims = new HashMap<StringLimitType, ArrayList<String>>();
		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
		int minLen = policy.getLimitations().getMinLength() == null ? 0 : policy.getLimitations().getMinLength()
				.intValue();
		if (minLen != 0 && minLen > defaultLength) {
			defaultLength = minLen;
		}
		int maxLen = (policy.getLimitations().getMaxLength() == null ? 0 : policy.getLimitations()
				.getMaxLength().intValue());
		int 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){
			maxLen = defaultLength;
		}

		// Initialize generator
		StringBuilder password = new StringBuilder();

		/* **********************************
		 * Try to find best characters to be first in password
		 */
		HashMap<StringLimitType, ArrayList<String>> mustBeFirst = new HashMap<StringLimitType, ArrayList<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()) {
			HashMap<Integer, ArrayList<String>> posibleFirstChars = cardinalityCounter(mustBeFirst, null, false, false,
					generatorResult);
{'fraction_non_alphanumeric': 0.11569001909739672, 'fraction_numerical': 0.0047240928736556435, 'mean_word_length': 4.470038482682793, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1923315', 'n_tokens_mistral': 3085, 'n_tokens_neox': 2759, 'n_words': 765}