CreatePasswordSensor extends AddSensorInitializer<String> { @Override public void apply(EntityLocal entity) { AttributeSensor<String> sensor = addSensor(entity); List<String> characterGroups = initParam(CHARACTER_GROUPS); String acceptableChars = initParam(ACCEPTABLE_CHARS); Integer passwordLength = initParam(PASSWORD_LENGTH); boolean isCharacterGroupsPresent = characterGroups != null && characterGroups.size() > 0; boolean isCharacterGroupsValid = isCharacterGroupsPresent && !Iterables.contains(characterGroups, Predicates.isNull()) && !Iterables.contains(characterGroups, Predicates.equalTo("")); boolean isAcceptableCharsPresentAndValid = acceptableChars != null && !acceptableChars.isEmpty(); Preconditions.checkArgument(!isCharacterGroupsPresent || isCharacterGroupsValid, "password.character.groups config key was given but does not contain any valid groups"); Preconditions.checkArgument(!(isCharacterGroupsPresent && isAcceptableCharsPresentAndValid), "password.chars and password.character.groups both provided - please provide only ONE of them"); Preconditions.checkArgument(!isCharacterGroupsValid || characterGroups.size() <= passwordLength, "password.length must be longer than the number of entries in password.character.groups"); String password; if (isCharacterGroupsValid) { password = Identifiers.makeRandomPassword(passwordLength, characterGroups.toArray(new String[0])); } else if (isAcceptableCharsPresentAndValid) { password = Identifiers.makeRandomPassword(passwordLength, acceptableChars); } else { password = Identifiers.makeRandomPassword(passwordLength); } entity.sensors().set(sensor, password); } private  CreatePasswordSensor();  CreatePasswordSensor(Map<String, String> params);  CreatePasswordSensor(ConfigBag params); @Override void apply(EntityLocal entity); static final ConfigKey<Integer> PASSWORD_LENGTH; static final ConfigKey<String> ACCEPTABLE_CHARS; static final ConfigKey<List<String>> CHARACTER_GROUPS; }
@Test public void testCreatePasswordCreatesAPasswordOfDefaultLength() { final CreatePasswordSensor sensor = new CreatePasswordSensor(ConfigBag.newInstance() .configure(CreatePasswordSensor.SENSOR_NAME, SENSOR_STRING.getName())); sensor.apply(entity); String password = entity.getAttribute(SENSOR_STRING); Asserts.assertEquals(password.length(), 12); }
@Test public void testCreatePasswordCharacterGroups() { final CreatePasswordSensor sensor = new CreatePasswordSensor(ConfigBag.newInstance() .configure(CreatePasswordSensor.SENSOR_NAME, SENSOR_STRING.getName()) .configure(CreatePasswordSensor.PASSWORD_LENGTH, 6) .configure(CreatePasswordSensor.CHARACTER_GROUPS, ImmutableList.of("abc", "def", "ghi")) ); sensor.apply(entity); String password = entity.getAttribute(SENSOR_STRING); Asserts.assertEquals(password.length(), 6); Asserts.assertStringMatchesRegex(password, "[a-i]{6}", ".*[a-c].*", ".*[d-f].*", ".*[g-i].*" ); }