DictionaryRule with TernaryDictionary example

In this post under Passay, I will show with example, how to use “TernaryDictionary” with “DictionaryRule”.

For recap, DictionaryRule will check whether the user inputed password matches a word amoung a dictionary of words. If it matches, the validation fails or else passes.

The dictionary of words can be implemented in many ways but for this example I will be using “TernaryDictionary” provided by Passay itself.

Below is the complete main class for your reference.

Main class

Plain text
package defaultPackage;
import java.util.Arrays;
import org.passay.DictionaryRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.dictionary.TernaryTree;
import org.passay.dictionary.TernaryTreeDictionary;
public class Example28 {
public static void main(String[] args) {
String[] words = new String[] {"Lantern", "Meadow", "Glacier", "Whisper", "Compass", "Orchard", "Velvet", "Horizon"};
Arrays.sort(words);
TernaryTree ternaryTree = new TernaryTree();
ternaryTree.insert(words);
TernaryTreeDictionary ternaryTreeDictionary = new TernaryTreeDictionary(ternaryTree);
DictionaryRule dictionaryRule = new DictionaryRule(ternaryTreeDictionary);
PasswordValidator passwordValidator = new PasswordValidator(dictionaryRule);
PasswordData passwordData = new PasswordData("Lantern");
RuleResult result = passwordValidator.validate(passwordData);
System.out.println("Validation result for 'Lantern': " + result.isValid());
passwordData = new PasswordData("abc1998dfjasdfjaoe");
result = passwordValidator.validate(passwordData);
System.out.println("Validation result for 'abc1998dfjasdfjaoe': " + result.isValid());
}
}

In the above, at line 14, I create an array of words and at line 15, I sort them.

At line 17, I create an instance of “TernaryTree” named “ternaryTree” and line 18, I populate the instance with the words.

At line 20, I create a dictionary of type “TernaryTreeDictionary” named “ternaryTreeDictionary” and use “ternaryTree” instance as constructor argument.

At line 22, I create a rule of type “DictionaryRule” named “dictionaryRule” and pass “ternaryTreeDictionary” instance as constructor argument.

At line 24, I create a password validator of type “PasswordValidator” and pass the rule “dictionaryRule” as constructor argument.

From line 26 to 32, I validate user provided input and print the result to the console.

Below is the output

Output

Validation result for 'Lantern': false
Validation result for 'abc1998dfjasdfjaoe': true

Leave a comment