target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test void generatedBeansNumberShouldBeEqualToSpecifiedNumber() { Stream<Person> persons = easyRandom.objects(Person.class, 2); assertThat(persons).hasSize(2).hasOnlyElementsOfType(Person.class); }
public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); }
EasyRandom extends Random { public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); } }
EasyRandom extends Random { public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); }
EasyRandom extends Random { public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
EasyRandom extends Random { public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
@Test void whenSpecifiedNumberOfBeansToGenerateIsNegative_thenShouldThrowAnIllegalArgumentException() { assertThatThrownBy(() -> easyRandom.objects(Person.class, -2)).isInstanceOf(IllegalArgumentException.class); }
public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); }
EasyRandom extends Random { public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); } }
EasyRandom extends Random { public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); }
EasyRandom extends Random { public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
EasyRandom extends Random { public <T> Stream<T> objects(final Class<T> type, final int streamSize) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type)).limit(streamSize); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
@Test void testGetInheritedFields() { assertThat(ReflectionUtils.getInheritedFields(SocialPerson.class)).hasSize(11); }
public static List<Field> getInheritedFields(Class<?> type) { List<Field> inheritedFields = new ArrayList<>(); while (type.getSuperclass() != null) { Class<?> superclass = type.getSuperclass(); inheritedFields.addAll(asList(superclass.getDeclaredFields())); type = superclass; } return inheritedFields; }
ReflectionUtils { public static List<Field> getInheritedFields(Class<?> type) { List<Field> inheritedFields = new ArrayList<>(); while (type.getSuperclass() != null) { Class<?> superclass = type.getSuperclass(); inheritedFields.addAll(asList(superclass.getDeclaredFields())); type = superclass; } return inheritedFields; } }
ReflectionUtils { public static List<Field> getInheritedFields(Class<?> type) { List<Field> inheritedFields = new ArrayList<>(); while (type.getSuperclass() != null) { Class<?> superclass = type.getSuperclass(); inheritedFields.addAll(asList(superclass.getDeclaredFields())); type = superclass; } return inheritedFields; } private ReflectionUtils(); }
ReflectionUtils { public static List<Field> getInheritedFields(Class<?> type) { List<Field> inheritedFields = new ArrayList<>(); while (type.getSuperclass() != null) { Class<?> superclass = type.getSuperclass(); inheritedFields.addAll(asList(superclass.getDeclaredFields())); type = superclass; } return inheritedFields; } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
ReflectionUtils { public static List<Field> getInheritedFields(Class<?> type) { List<Field> inheritedFields = new ArrayList<>(); while (type.getSuperclass() != null) { Class<?> superclass = type.getSuperclass(); inheritedFields.addAll(asList(superclass.getDeclaredFields())); type = superclass; } return inheritedFields; } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
@Test void whenUnableToInstantiateField_thenShouldThrowObjectGenerationException() { assertThatThrownBy(() -> easyRandom.nextObject(AbstractBean.class)).isInstanceOf(ObjectCreationException.class); }
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
@Test void beansWithRecursiveStructureMustNotCauseStackOverflowException() { Node node = easyRandom.nextObject(Node.class); assertThat(node).hasNoNullFieldsOrProperties(); }
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
@Test void objectTypeMustBeCorrectlyPopulated() { Object object = easyRandom.nextObject(Object.class); assertThat(object).isNotNull(); }
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
@Test void annotatedRandomizerArgumentsShouldBeCorrectlyParsed() { TestData data = easyRandom.nextObject(TestData.class); then(data.getDate()).isBetween(valueOf(of(2016, 1, 10, 0, 0, 0)), valueOf(of(2016, 1, 30, 23, 59, 59))); then(data.getPrice()).isBetween(200, 500); }
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
@Test void nextEnumShouldNotAlwaysReturnTheSameValue() { HashSet<TestEnum> distinctEnumBeans = new HashSet<>(); for (int i = 0; i < 10; i++) { distinctEnumBeans.add(easyRandom.nextObject(TestEnum.class)); } assertThat(distinctEnumBeans.size()).isGreaterThan(1); }
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
@Test void fieldsOfTypeClassShouldBeSkipped() { try { TestBean testBean = easyRandom.nextObject(TestBean.class); assertThat(testBean.getException()).isNotNull(); assertThat(testBean.getClazz()).isNull(); } catch (Exception e) { fail("Should skip fields of type Class"); } }
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
@Test void differentCollectionsShouldBeRandomizedWithDifferentSizes() { class Foo { List<String> names; List<String> addresses; } Foo foo = new EasyRandom().nextObject(Foo.class); assertThat(foo.names.size()).isNotEqualTo(foo.addresses.size()); }
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
@Test void differentArraysShouldBeRandomizedWithDifferentSizes() { class Foo { String[] names; String[] addresses; } Foo foo = new EasyRandom().nextObject(Foo.class); assertThat(foo.names.length).isNotEqualTo(foo.addresses.length); }
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
@Disabled("Dummy test to see possible reasons of randomization failures") @Test void tryToRandomizeAllPublicConcreteTypesInTheClasspath(){ int success = 0; int failure = 0; List<Class<?>> publicConcreteTypes = ReflectionUtils.getPublicConcreteSubTypesOf(Object.class); System.out.println("Found " + publicConcreteTypes.size() + " public concrete types in the classpath"); for (Class<?> aClass : publicConcreteTypes) { try { easyRandom.nextObject(aClass); System.out.println(aClass.getName() + " has been successfully randomized"); success++; } catch (Throwable e) { System.err.println("Unable to populate a random instance of type: " + aClass.getName()); e.printStackTrace(); System.err.println("----------------------------------------------"); failure++; } } System.out.println("Success: " + success); System.out.println("Failure: " + failure); }
public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
EasyRandom extends Random { public <T> T nextObject(final Class<T> type) { return doPopulateBean(type, new RandomizationContext(type, parameters)); } EasyRandom(); EasyRandom(final EasyRandomParameters easyRandomParameters); T nextObject(final Class<T> type); Stream<T> objects(final Class<T> type, final int streamSize); }
@Test void whenSkipRandomizerIsRegisteredForTheField_thenTheFieldShouldBeSkipped() throws Exception { Field name = Human.class.getDeclaredField("name"); Human human = new Human(); randomizer = new SkipRandomizer(); RandomizationContext context = new RandomizationContext(Human.class, new EasyRandomParameters()); when(randomizerProvider.getRandomizerByField(name, context)).thenReturn(randomizer); fieldPopulator.populateField(human, name, context); assertThat(human.getName()).isNull(); }
void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
@Test void testIsStatic() throws Exception { assertThat(ReflectionUtils.isStatic(Human.class.getField("SERIAL_VERSION_UID"))).isTrue(); }
public static boolean isStatic(final Field field) { return Modifier.isStatic(field.getModifiers()); }
ReflectionUtils { public static boolean isStatic(final Field field) { return Modifier.isStatic(field.getModifiers()); } }
ReflectionUtils { public static boolean isStatic(final Field field) { return Modifier.isStatic(field.getModifiers()); } private ReflectionUtils(); }
ReflectionUtils { public static boolean isStatic(final Field field) { return Modifier.isStatic(field.getModifiers()); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
ReflectionUtils { public static boolean isStatic(final Field field) { return Modifier.isStatic(field.getModifiers()); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
@Test void whenCustomRandomizerIsRegisteredForTheField_thenTheFieldShouldBePopulatedWithTheRandomValue() throws Exception { Field name = Human.class.getDeclaredField("name"); Human human = new Human(); RandomizationContext context = new RandomizationContext(Human.class, new EasyRandomParameters()); when(randomizerProvider.getRandomizerByField(name, context)).thenReturn(randomizer); when(randomizer.getRandomValue()).thenReturn(NAME); fieldPopulator.populateField(human, name, context); assertThat(human.getName()).isEqualTo(NAME); }
void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
@Test void whenTheFieldIsOfTypeArray_thenShouldDelegatePopulationToArrayPopulator() throws Exception { Field strings = ArrayBean.class.getDeclaredField("strings"); ArrayBean arrayBean = new ArrayBean(); String[] object = new String[0]; RandomizationContext context = new RandomizationContext(ArrayBean.class, new EasyRandomParameters()); when(arrayPopulator.getRandomArray(strings.getType(), context)).thenReturn(object); fieldPopulator.populateField(arrayBean, strings, context); assertThat(arrayBean.getStrings()).isEqualTo(object); }
void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
@Test void whenTheFieldIsOfTypeCollection_thenShouldDelegatePopulationToCollectionPopulator() throws Exception { Field strings = CollectionBean.class.getDeclaredField("typedCollection"); CollectionBean collectionBean = new CollectionBean(); Collection<Person> persons = Collections.emptyList(); RandomizationContext context = new RandomizationContext(CollectionBean.class, new EasyRandomParameters()); fieldPopulator.populateField(collectionBean, strings, context); assertThat(collectionBean.getTypedCollection()).isEqualTo(persons); }
void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
@Test void whenTheFieldIsOfTypeMap_thenShouldDelegatePopulationToMapPopulator() throws Exception { Field strings = MapBean.class.getDeclaredField("typedMap"); MapBean mapBean = new MapBean(); Map<Integer, Person> idToPerson = new HashMap<>(); RandomizationContext context = new RandomizationContext(MapBean.class, new EasyRandomParameters()); fieldPopulator.populateField(mapBean, strings, context); assertThat(mapBean.getTypedMap()).isEqualTo(idToPerson); }
void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
@Test void whenRandomizationDepthIsExceeded_thenFieldsAreNotInitialized() throws Exception { Field name = Human.class.getDeclaredField("name"); Human human = new Human(); RandomizationContext context = Mockito.mock(RandomizationContext.class); when(context.hasExceededRandomizationDepth()).thenReturn(true); fieldPopulator.populateField(human, name, context); assertThat(human.getName()).isNull(); }
void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
@Test @Disabled("Objenesis is able to create an instance of JAXBElement type. Hence no error is thrown as expected in this test") void shouldFailWithNiceErrorMessageWhenUnableToCreateFieldValue() throws Exception { FieldPopulator fieldPopulator = new FieldPopulator(new EasyRandom(), randomizerProvider, arrayPopulator, collectionPopulator, mapPopulator); Field jaxbElementField = JaxbElementFieldBean.class.getDeclaredField("jaxbElementField"); JaxbElementFieldBean jaxbElementFieldBean = new JaxbElementFieldBean(); RandomizationContext context = Mockito.mock(RandomizationContext.class); thenThrownBy(() -> { fieldPopulator.populateField(jaxbElementFieldBean, jaxbElementField, context); }) .hasMessage("Unable to create type: javax.xml.bind.JAXBElement for field: jaxbElementField of class: org.jeasy.random.FieldPopulatorTest$JaxbElementFieldBean"); }
void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
FieldPopulator { void populateField(final Object target, final Field field, final RandomizationContext context) throws IllegalAccessException { Randomizer<?> randomizer = getRandomizer(field, context); if (randomizer instanceof SkipRandomizer) { return; } if (randomizer instanceof ContextAwareRandomizer) { ((ContextAwareRandomizer<?>) randomizer).setRandomizerContext(context); } context.pushStackItem(new RandomizationContextStackItem(target, field)); if(!context.hasExceededRandomizationDepth()) { Object value; if (randomizer != null) { value = randomizer.getRandomValue(); } else { try { value = generateRandomValue(field, context); } catch (ObjectCreationException e) { String exceptionMessage = String.format("Unable to create type: %s for field: %s of class: %s", field.getType().getName(), field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e); } } if (context.getParameters().isBypassSetters()) { setFieldValue(target, field, value); } else { try { setProperty(target, field, value); } catch (InvocationTargetException e) { String exceptionMessage = String.format("Unable to invoke setter for field %s of class %s", field.getName(), target.getClass().getName()); throw new ObjectCreationException(exceptionMessage, e.getCause()); } } } context.popStackItem(); } FieldPopulator(final EasyRandom easyRandom, final RandomizerProvider randomizerProvider, final ArrayPopulator arrayPopulator, final CollectionPopulator collectionPopulator, final MapPopulator mapPopulator); }
@Test void testCompare() { assertThat(priorityComparator.compare(foo, bar)).isGreaterThan(0); List<Object> objects = Arrays.asList(foo,bar); objects.sort(priorityComparator); assertThat(objects).containsExactly(bar, foo); }
@Override public int compare(final Object o1, final Object o2) { int o1Priority = getPriority(o1); int o2Priority = getPriority(o2); return o2Priority - o1Priority; }
PriorityComparator implements Comparator<Object> { @Override public int compare(final Object o1, final Object o2) { int o1Priority = getPriority(o1); int o2Priority = getPriority(o2); return o2Priority - o1Priority; } }
PriorityComparator implements Comparator<Object> { @Override public int compare(final Object o1, final Object o2) { int o1Priority = getPriority(o1); int o2Priority = getPriority(o2); return o2Priority - o1Priority; } }
PriorityComparator implements Comparator<Object> { @Override public int compare(final Object o1, final Object o2) { int o1Priority = getPriority(o1); int o2Priority = getPriority(o2); return o2Priority - o1Priority; } @Override int compare(final Object o1, final Object o2); }
PriorityComparator implements Comparator<Object> { @Override public int compare(final Object o1, final Object o2) { int o1Priority = getPriority(o1); int o2Priority = getPriority(o2); return o2Priority - o1Priority; } @Override int compare(final Object o1, final Object o2); }
@Test void rawInterfaceCollectionTypesMustBeReturnedEmpty() throws Exception { when(context.getParameters()).thenReturn(parameters); Field field = Foo.class.getDeclaredField("rawInterfaceList"); Collection<?> collection = collectionPopulator.getRandomCollection(field, context); assertThat(collection).isEmpty(); }
@SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
@Test void rawConcreteCollectionTypesMustBeReturnedEmpty() throws Exception { when(context.getParameters()).thenReturn(parameters); Field field = Foo.class.getDeclaredField("rawConcreteList"); Collection<?> collection = collectionPopulator.getRandomCollection(field, context); assertThat(collection).isEmpty(); }
@SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
@Test void typedInterfaceCollectionTypesMightBePopulated() throws Exception { when(context.getParameters()).thenReturn(parameters); when(easyRandom.doPopulateBean(String.class, context)).thenReturn(STRING); Field field = Foo.class.getDeclaredField("typedInterfaceList"); @SuppressWarnings("unchecked") Collection<String> collection = (Collection<String>) collectionPopulator.getRandomCollection(field, context); assertThat(collection).containsExactly(STRING, STRING); }
@SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
@Test void testIsInterface() { assertThat(ReflectionUtils.isInterface(List.class)).isTrue(); assertThat(ReflectionUtils.isInterface(Mammal.class)).isTrue(); assertThat(ReflectionUtils.isInterface(MammalImpl.class)).isFalse(); assertThat(ReflectionUtils.isInterface(ArrayList.class)).isFalse(); }
public static boolean isInterface(final Class<?> type) { return type.isInterface(); }
ReflectionUtils { public static boolean isInterface(final Class<?> type) { return type.isInterface(); } }
ReflectionUtils { public static boolean isInterface(final Class<?> type) { return type.isInterface(); } private ReflectionUtils(); }
ReflectionUtils { public static boolean isInterface(final Class<?> type) { return type.isInterface(); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
ReflectionUtils { public static boolean isInterface(final Class<?> type) { return type.isInterface(); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
@Test void typedConcreteCollectionTypesMightBePopulated() throws Exception { when(context.getParameters()).thenReturn(parameters); when(easyRandom.doPopulateBean(String.class, context)).thenReturn(STRING); Field field = Foo.class.getDeclaredField("typedConcreteList"); @SuppressWarnings("unchecked") Collection<String> collection = (Collection<String>) collectionPopulator.getRandomCollection(field, context); assertThat(collection).containsExactly(STRING, STRING); }
@SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
CollectionPopulator { @SuppressWarnings({"unchecked", "rawtypes"}) Collection<?> getRandomCollection(final Field field, final RandomizationContext context) { int randomSize = getRandomCollectionSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Collection collection; if (isInterface(fieldType)) { collection = getEmptyImplementationForCollectionInterface(fieldType); } else { collection = createEmptyCollectionForType(fieldType, randomSize); } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type type = parameterizedType.getActualTypeArguments()[0]; if (isPopulatable(type)) { for (int i = 0; i < randomSize; i++) { Object item = easyRandom.doPopulateBean((Class<?>) type, context); collection.add(item); } } } return collection; } CollectionPopulator(final EasyRandom easyRandom); }
@Test void staticFieldsShouldBeExcluded() throws NoSuchFieldException { Field field = Human.class.getDeclaredField("SERIAL_VERSION_UID"); boolean actual = exclusionPolicy.shouldBeExcluded(field, randomizerContext); assertThat(actual).isTrue(); }
public boolean shouldBeExcluded(final Field field, final RandomizerContext context) { if (isStatic(field)) { return true; } Set<Predicate<Field>> fieldExclusionPredicates = context.getParameters().getFieldExclusionPredicates(); for (Predicate<Field> fieldExclusionPredicate : fieldExclusionPredicates) { if (fieldExclusionPredicate.test(field)) { return true; } } return false; }
DefaultExclusionPolicy implements ExclusionPolicy { public boolean shouldBeExcluded(final Field field, final RandomizerContext context) { if (isStatic(field)) { return true; } Set<Predicate<Field>> fieldExclusionPredicates = context.getParameters().getFieldExclusionPredicates(); for (Predicate<Field> fieldExclusionPredicate : fieldExclusionPredicates) { if (fieldExclusionPredicate.test(field)) { return true; } } return false; } }
DefaultExclusionPolicy implements ExclusionPolicy { public boolean shouldBeExcluded(final Field field, final RandomizerContext context) { if (isStatic(field)) { return true; } Set<Predicate<Field>> fieldExclusionPredicates = context.getParameters().getFieldExclusionPredicates(); for (Predicate<Field> fieldExclusionPredicate : fieldExclusionPredicates) { if (fieldExclusionPredicate.test(field)) { return true; } } return false; } }
DefaultExclusionPolicy implements ExclusionPolicy { public boolean shouldBeExcluded(final Field field, final RandomizerContext context) { if (isStatic(field)) { return true; } Set<Predicate<Field>> fieldExclusionPredicates = context.getParameters().getFieldExclusionPredicates(); for (Predicate<Field> fieldExclusionPredicate : fieldExclusionPredicates) { if (fieldExclusionPredicate.test(field)) { return true; } } return false; } boolean shouldBeExcluded(final Field field, final RandomizerContext context); boolean shouldBeExcluded(final Class<?> type, final RandomizerContext context); }
DefaultExclusionPolicy implements ExclusionPolicy { public boolean shouldBeExcluded(final Field field, final RandomizerContext context) { if (isStatic(field)) { return true; } Set<Predicate<Field>> fieldExclusionPredicates = context.getParameters().getFieldExclusionPredicates(); for (Predicate<Field> fieldExclusionPredicate : fieldExclusionPredicates) { if (fieldExclusionPredicate.test(field)) { return true; } } return false; } boolean shouldBeExcluded(final Field field, final RandomizerContext context); boolean shouldBeExcluded(final Class<?> type, final RandomizerContext context); }
@Test void rawInterfaceMapTypesMustBeGeneratedEmpty() throws Exception { when(context.getParameters()).thenReturn(parameters); Field field = Foo.class.getDeclaredField("rawMap"); Map<?, ?> randomMap = mapPopulator.getRandomMap(field, context); assertThat(randomMap).isEmpty(); }
@SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
@Test void rawConcreteMapTypesMustBeGeneratedEmpty() throws Exception { when(context.getParameters()).thenReturn(parameters); Field field = Foo.class.getDeclaredField("concreteMap"); Map<?, ?> randomMap = mapPopulator.getRandomMap(field, context); assertThat(randomMap).isEmpty(); }
@SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
@Test void typedInterfaceMapTypesMightBePopulated() throws Exception { when(context.getParameters()).thenReturn(parameters); when(easyRandom.doPopulateBean(String.class, context)).thenReturn(FOO, BAR); Field field = Foo.class.getDeclaredField("typedMap"); Map<String, String> randomMap = (Map<String, String>) mapPopulator.getRandomMap(field, context); assertThat(randomMap).containsExactly(entry(FOO, BAR)); }
@SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
@Test void typedConcreteMapTypesMightBePopulated() throws Exception { when(context.getParameters()).thenReturn(parameters); when(easyRandom.doPopulateBean(String.class, context)).thenReturn(FOO, BAR); Field field = Foo.class.getDeclaredField("typedConcreteMap"); Map<String, String> randomMap = (Map<String, String>) mapPopulator.getRandomMap(field, context); assertThat(randomMap).containsExactly(entry(FOO, BAR)); }
@SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
@Test void notAddNullKeysToMap() throws NoSuchFieldException { when(context.getParameters()).thenReturn(parameters); when(easyRandom.doPopulateBean(String.class, context)).thenReturn(null); Field field = Foo.class.getDeclaredField("typedConcreteMap"); Map<String, String> randomMap = (Map<String, String>) mapPopulator.getRandomMap(field, context); assertThat(randomMap).isEmpty(); }
@SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
MapPopulator { @SuppressWarnings("unchecked") Map<?, ?> getRandomMap(final Field field, final RandomizationContext context) { int randomSize = getRandomMapSize(context.getParameters()); Class<?> fieldType = field.getType(); Type fieldGenericType = field.getGenericType(); Map<Object, Object> map; if (isInterface(fieldType)) { map = (Map<Object, Object>) getEmptyImplementationForMapInterface(fieldType); } else { try { map = (Map<Object, Object>) fieldType.newInstance(); } catch (InstantiationException | IllegalAccessException e) { if (fieldType.isAssignableFrom(EnumMap.class)) { if (isParameterizedType(fieldGenericType)) { Type type = ((ParameterizedType) fieldGenericType).getActualTypeArguments()[0]; map = new EnumMap((Class<?>)type); } else { return null; } } else { map = (Map<Object, Object>) objectFactory.createInstance(fieldType, context); } } } if (isParameterizedType(fieldGenericType)) { ParameterizedType parameterizedType = (ParameterizedType) fieldGenericType; Type keyType = parameterizedType.getActualTypeArguments()[0]; Type valueType = parameterizedType.getActualTypeArguments()[1]; if (isPopulatable(keyType) && isPopulatable(valueType)) { for (int index = 0; index < randomSize; index++) { Object randomKey = easyRandom.doPopulateBean((Class<?>) keyType, context); Object randomValue = easyRandom.doPopulateBean((Class<?>) valueType, context); if(randomKey != null) { map.put(randomKey, randomValue); } } } } return map; } MapPopulator(final EasyRandom easyRandom, final ObjectFactory objectFactory); }
@Test void concreteClassesShouldBeCreatedAsExpected() { String string = objenesisObjectFactory.createInstance(String.class, context); assertThat(string).isNotNull(); }
@Override public <T> T createInstance(Class<T> type, RandomizerContext context) { if (context.getParameters().isScanClasspathForConcreteTypes() && isAbstract(type)) { Class<?> randomConcreteSubType = randomElementOf(getPublicConcreteSubTypesOf((type))); if (randomConcreteSubType == null) { throw new InstantiationError("Unable to find a matching concrete subtype of type: " + type + " in the classpath"); } else { return (T) createNewInstance(randomConcreteSubType); } } else { try { return createNewInstance(type); } catch (Error e) { throw new ObjectCreationException("Unable to create an instance of type: " + type, e); } } }
ObjenesisObjectFactory implements ObjectFactory { @Override public <T> T createInstance(Class<T> type, RandomizerContext context) { if (context.getParameters().isScanClasspathForConcreteTypes() && isAbstract(type)) { Class<?> randomConcreteSubType = randomElementOf(getPublicConcreteSubTypesOf((type))); if (randomConcreteSubType == null) { throw new InstantiationError("Unable to find a matching concrete subtype of type: " + type + " in the classpath"); } else { return (T) createNewInstance(randomConcreteSubType); } } else { try { return createNewInstance(type); } catch (Error e) { throw new ObjectCreationException("Unable to create an instance of type: " + type, e); } } } }
ObjenesisObjectFactory implements ObjectFactory { @Override public <T> T createInstance(Class<T> type, RandomizerContext context) { if (context.getParameters().isScanClasspathForConcreteTypes() && isAbstract(type)) { Class<?> randomConcreteSubType = randomElementOf(getPublicConcreteSubTypesOf((type))); if (randomConcreteSubType == null) { throw new InstantiationError("Unable to find a matching concrete subtype of type: " + type + " in the classpath"); } else { return (T) createNewInstance(randomConcreteSubType); } } else { try { return createNewInstance(type); } catch (Error e) { throw new ObjectCreationException("Unable to create an instance of type: " + type, e); } } } }
ObjenesisObjectFactory implements ObjectFactory { @Override public <T> T createInstance(Class<T> type, RandomizerContext context) { if (context.getParameters().isScanClasspathForConcreteTypes() && isAbstract(type)) { Class<?> randomConcreteSubType = randomElementOf(getPublicConcreteSubTypesOf((type))); if (randomConcreteSubType == null) { throw new InstantiationError("Unable to find a matching concrete subtype of type: " + type + " in the classpath"); } else { return (T) createNewInstance(randomConcreteSubType); } } else { try { return createNewInstance(type); } catch (Error e) { throw new ObjectCreationException("Unable to create an instance of type: " + type, e); } } } @Override T createInstance(Class<T> type, RandomizerContext context); }
ObjenesisObjectFactory implements ObjectFactory { @Override public <T> T createInstance(Class<T> type, RandomizerContext context) { if (context.getParameters().isScanClasspathForConcreteTypes() && isAbstract(type)) { Class<?> randomConcreteSubType = randomElementOf(getPublicConcreteSubTypesOf((type))); if (randomConcreteSubType == null) { throw new InstantiationError("Unable to find a matching concrete subtype of type: " + type + " in the classpath"); } else { return (T) createNewInstance(randomConcreteSubType); } } else { try { return createNewInstance(type); } catch (Error e) { throw new ObjectCreationException("Unable to create an instance of type: " + type, e); } } } @Override T createInstance(Class<T> type, RandomizerContext context); }
@Test void whenNoConcreteTypeIsFound_thenShouldThrowAnInstantiationError() { Mockito.when(context.getParameters().isScanClasspathForConcreteTypes()).thenReturn(true); assertThatThrownBy(() -> objenesisObjectFactory.createInstance(AbstractFoo.class, context)).isInstanceOf(InstantiationError.class); }
@Override public <T> T createInstance(Class<T> type, RandomizerContext context) { if (context.getParameters().isScanClasspathForConcreteTypes() && isAbstract(type)) { Class<?> randomConcreteSubType = randomElementOf(getPublicConcreteSubTypesOf((type))); if (randomConcreteSubType == null) { throw new InstantiationError("Unable to find a matching concrete subtype of type: " + type + " in the classpath"); } else { return (T) createNewInstance(randomConcreteSubType); } } else { try { return createNewInstance(type); } catch (Error e) { throw new ObjectCreationException("Unable to create an instance of type: " + type, e); } } }
ObjenesisObjectFactory implements ObjectFactory { @Override public <T> T createInstance(Class<T> type, RandomizerContext context) { if (context.getParameters().isScanClasspathForConcreteTypes() && isAbstract(type)) { Class<?> randomConcreteSubType = randomElementOf(getPublicConcreteSubTypesOf((type))); if (randomConcreteSubType == null) { throw new InstantiationError("Unable to find a matching concrete subtype of type: " + type + " in the classpath"); } else { return (T) createNewInstance(randomConcreteSubType); } } else { try { return createNewInstance(type); } catch (Error e) { throw new ObjectCreationException("Unable to create an instance of type: " + type, e); } } } }
ObjenesisObjectFactory implements ObjectFactory { @Override public <T> T createInstance(Class<T> type, RandomizerContext context) { if (context.getParameters().isScanClasspathForConcreteTypes() && isAbstract(type)) { Class<?> randomConcreteSubType = randomElementOf(getPublicConcreteSubTypesOf((type))); if (randomConcreteSubType == null) { throw new InstantiationError("Unable to find a matching concrete subtype of type: " + type + " in the classpath"); } else { return (T) createNewInstance(randomConcreteSubType); } } else { try { return createNewInstance(type); } catch (Error e) { throw new ObjectCreationException("Unable to create an instance of type: " + type, e); } } } }
ObjenesisObjectFactory implements ObjectFactory { @Override public <T> T createInstance(Class<T> type, RandomizerContext context) { if (context.getParameters().isScanClasspathForConcreteTypes() && isAbstract(type)) { Class<?> randomConcreteSubType = randomElementOf(getPublicConcreteSubTypesOf((type))); if (randomConcreteSubType == null) { throw new InstantiationError("Unable to find a matching concrete subtype of type: " + type + " in the classpath"); } else { return (T) createNewInstance(randomConcreteSubType); } } else { try { return createNewInstance(type); } catch (Error e) { throw new ObjectCreationException("Unable to create an instance of type: " + type, e); } } } @Override T createInstance(Class<T> type, RandomizerContext context); }
ObjenesisObjectFactory implements ObjectFactory { @Override public <T> T createInstance(Class<T> type, RandomizerContext context) { if (context.getParameters().isScanClasspathForConcreteTypes() && isAbstract(type)) { Class<?> randomConcreteSubType = randomElementOf(getPublicConcreteSubTypesOf((type))); if (randomConcreteSubType == null) { throw new InstantiationError("Unable to find a matching concrete subtype of type: " + type + " in the classpath"); } else { return (T) createNewInstance(randomConcreteSubType); } } else { try { return createNewInstance(type); } catch (Error e) { throw new ObjectCreationException("Unable to create an instance of type: " + type, e); } } } @Override T createInstance(Class<T> type, RandomizerContext context); }
@Test void should_throw_an_exception_when_all_values_are_excluded() { assertThatThrownBy(() -> aNewEnumRandomizer(Gender.class, Gender.values())).isInstanceOf(IllegalArgumentException.class); }
public static <E extends Enum<E>> EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration) { return new EnumRandomizer<>(enumeration); }
EnumRandomizer extends AbstractRandomizer<E> { public static <E extends Enum<E>> EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration) { return new EnumRandomizer<>(enumeration); } }
EnumRandomizer extends AbstractRandomizer<E> { public static <E extends Enum<E>> EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration) { return new EnumRandomizer<>(enumeration); } EnumRandomizer(final Class<E> enumeration); EnumRandomizer(final Class<E> enumeration, final long seed); EnumRandomizer(final Class<E> enumeration, final E... excludedValues); }
EnumRandomizer extends AbstractRandomizer<E> { public static <E extends Enum<E>> EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration) { return new EnumRandomizer<>(enumeration); } EnumRandomizer(final Class<E> enumeration); EnumRandomizer(final Class<E> enumeration, final long seed); EnumRandomizer(final Class<E> enumeration, final E... excludedValues); static EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration); static EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration, final long seed); static EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration, final E... excludedValues); @Override E getRandomValue(); }
EnumRandomizer extends AbstractRandomizer<E> { public static <E extends Enum<E>> EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration) { return new EnumRandomizer<>(enumeration); } EnumRandomizer(final Class<E> enumeration); EnumRandomizer(final Class<E> enumeration, final long seed); EnumRandomizer(final Class<E> enumeration, final E... excludedValues); static EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration); static EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration, final long seed); static EnumRandomizer<E> aNewEnumRandomizer(final Class<E> enumeration, final E... excludedValues); @Override E getRandomValue(); }
@Test void testIsAbstract() { assertThat(ReflectionUtils.isAbstract(Foo.class)).isFalse(); assertThat(ReflectionUtils.isAbstract(Bar.class)).isTrue(); }
public static <T> boolean isAbstract(final Class<T> type) { return Modifier.isAbstract(type.getModifiers()); }
ReflectionUtils { public static <T> boolean isAbstract(final Class<T> type) { return Modifier.isAbstract(type.getModifiers()); } }
ReflectionUtils { public static <T> boolean isAbstract(final Class<T> type) { return Modifier.isAbstract(type.getModifiers()); } private ReflectionUtils(); }
ReflectionUtils { public static <T> boolean isAbstract(final Class<T> type) { return Modifier.isAbstract(type.getModifiers()); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
ReflectionUtils { public static <T> boolean isAbstract(final Class<T> type) { return Modifier.isAbstract(type.getModifiers()); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
@Test void whenOptionalPercentIsOneHundredThenShouldGenerateValue() { assertThat(optionalRandomizer.getRandomValue()) .isEqualTo(NAME); }
@Override public T getRandomValue() { int randomPercent = random.nextInt(MAX_PERCENT); if (randomPercent <= optionalPercent) { return delegate.getRandomValue(); } return null; }
OptionalRandomizer extends AbstractRandomizer<T> { @Override public T getRandomValue() { int randomPercent = random.nextInt(MAX_PERCENT); if (randomPercent <= optionalPercent) { return delegate.getRandomValue(); } return null; } }
OptionalRandomizer extends AbstractRandomizer<T> { @Override public T getRandomValue() { int randomPercent = random.nextInt(MAX_PERCENT); if (randomPercent <= optionalPercent) { return delegate.getRandomValue(); } return null; } OptionalRandomizer(final Randomizer<T> delegate, final int optionalPercent); }
OptionalRandomizer extends AbstractRandomizer<T> { @Override public T getRandomValue() { int randomPercent = random.nextInt(MAX_PERCENT); if (randomPercent <= optionalPercent) { return delegate.getRandomValue(); } return null; } OptionalRandomizer(final Randomizer<T> delegate, final int optionalPercent); static Randomizer<T> aNewOptionalRandomizer(final Randomizer<T> delegate, final int optionalPercent); @Override T getRandomValue(); }
OptionalRandomizer extends AbstractRandomizer<T> { @Override public T getRandomValue() { int randomPercent = random.nextInt(MAX_PERCENT); if (randomPercent <= optionalPercent) { return delegate.getRandomValue(); } return null; } OptionalRandomizer(final Randomizer<T> delegate, final int optionalPercent); static Randomizer<T> aNewOptionalRandomizer(final Randomizer<T> delegate, final int optionalPercent); @Override T getRandomValue(); }
@Test void generatedValueShouldBeWithinSpecifiedRange() { Double randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
@Override public Double getRandomValue() { return nextDouble(min, max); }
DoubleRangeRandomizer extends AbstractRangeRandomizer<Double> { @Override public Double getRandomValue() { return nextDouble(min, max); } }
DoubleRangeRandomizer extends AbstractRangeRandomizer<Double> { @Override public Double getRandomValue() { return nextDouble(min, max); } DoubleRangeRandomizer(final Double min, final Double max); DoubleRangeRandomizer(final Double min, final Double max, final long seed); }
DoubleRangeRandomizer extends AbstractRangeRandomizer<Double> { @Override public Double getRandomValue() { return nextDouble(min, max); } DoubleRangeRandomizer(final Double min, final Double max); DoubleRangeRandomizer(final Double min, final Double max, final long seed); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max, final long seed); @Override Double getRandomValue(); }
DoubleRangeRandomizer extends AbstractRangeRandomizer<Double> { @Override public Double getRandomValue() { return nextDouble(min, max); } DoubleRangeRandomizer(final Double min, final Double max); DoubleRangeRandomizer(final Double min, final Double max, final long seed); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max, final long seed); @Override Double getRandomValue(); }
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewDoubleRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
public static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max) { return new DoubleRangeRandomizer(min, max); }
DoubleRangeRandomizer extends AbstractRangeRandomizer<Double> { public static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max) { return new DoubleRangeRandomizer(min, max); } }
DoubleRangeRandomizer extends AbstractRangeRandomizer<Double> { public static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max) { return new DoubleRangeRandomizer(min, max); } DoubleRangeRandomizer(final Double min, final Double max); DoubleRangeRandomizer(final Double min, final Double max, final long seed); }
DoubleRangeRandomizer extends AbstractRangeRandomizer<Double> { public static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max) { return new DoubleRangeRandomizer(min, max); } DoubleRangeRandomizer(final Double min, final Double max); DoubleRangeRandomizer(final Double min, final Double max, final long seed); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max, final long seed); @Override Double getRandomValue(); }
DoubleRangeRandomizer extends AbstractRangeRandomizer<Double> { public static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max) { return new DoubleRangeRandomizer(min, max); } DoubleRangeRandomizer(final Double min, final Double max); DoubleRangeRandomizer(final Double min, final Double max, final long seed); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max); static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max, final long seed); @Override Double getRandomValue(); }
@Test void generatedDateShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
@Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble(minDateTime, maxDateTime); return new Date(randomDateTime); }
SqlDateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble(minDateTime, maxDateTime); return new Date(randomDateTime); } }
SqlDateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble(minDateTime, maxDateTime); return new Date(randomDateTime); } SqlDateRangeRandomizer(final Date min, final Date max); SqlDateRangeRandomizer(final Date min, final Date max, final long seed); }
SqlDateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble(minDateTime, maxDateTime); return new Date(randomDateTime); } SqlDateRangeRandomizer(final Date min, final Date max); SqlDateRangeRandomizer(final Date min, final Date max, final long seed); static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max); static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }
SqlDateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble(minDateTime, maxDateTime); return new Date(randomDateTime); } SqlDateRangeRandomizer(final Date min, final Date max); SqlDateRangeRandomizer(final Date min, final Date max, final long seed); static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max); static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }
@Test void generatedDateShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDate, maxDate); }
@Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble(minDateTime, maxDateTime); return new Date(randomDateTime); }
SqlDateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble(minDateTime, maxDateTime); return new Date(randomDateTime); } }
SqlDateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble(minDateTime, maxDateTime); return new Date(randomDateTime); } SqlDateRangeRandomizer(final Date min, final Date max); SqlDateRangeRandomizer(final Date min, final Date max, final long seed); }
SqlDateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble(minDateTime, maxDateTime); return new Date(randomDateTime); } SqlDateRangeRandomizer(final Date min, final Date max); SqlDateRangeRandomizer(final Date min, final Date max, final long seed); static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max); static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }
SqlDateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble(minDateTime, maxDateTime); return new Date(randomDateTime); } SqlDateRangeRandomizer(final Date min, final Date max); SqlDateRangeRandomizer(final Date min, final Date max, final long seed); static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max); static SqlDateRangeRandomizer aNewSqlDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }
@Test void generatedValueShouldBeWithinSpecifiedRange() { Byte randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
@Override public Byte getRandomValue() { return (byte) nextDouble(min, max); }
ByteRangeRandomizer extends AbstractRangeRandomizer<Byte> { @Override public Byte getRandomValue() { return (byte) nextDouble(min, max); } }
ByteRangeRandomizer extends AbstractRangeRandomizer<Byte> { @Override public Byte getRandomValue() { return (byte) nextDouble(min, max); } ByteRangeRandomizer(final Byte min, final Byte max); ByteRangeRandomizer(final Byte min, final Byte max, final long seed); }
ByteRangeRandomizer extends AbstractRangeRandomizer<Byte> { @Override public Byte getRandomValue() { return (byte) nextDouble(min, max); } ByteRangeRandomizer(final Byte min, final Byte max); ByteRangeRandomizer(final Byte min, final Byte max, final long seed); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max, final long seed); @Override Byte getRandomValue(); }
ByteRangeRandomizer extends AbstractRangeRandomizer<Byte> { @Override public Byte getRandomValue() { return (byte) nextDouble(min, max); } ByteRangeRandomizer(final Byte min, final Byte max); ByteRangeRandomizer(final Byte min, final Byte max, final long seed); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max, final long seed); @Override Byte getRandomValue(); }
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewByteRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
public static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max) { return new ByteRangeRandomizer(min, max); }
ByteRangeRandomizer extends AbstractRangeRandomizer<Byte> { public static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max) { return new ByteRangeRandomizer(min, max); } }
ByteRangeRandomizer extends AbstractRangeRandomizer<Byte> { public static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max) { return new ByteRangeRandomizer(min, max); } ByteRangeRandomizer(final Byte min, final Byte max); ByteRangeRandomizer(final Byte min, final Byte max, final long seed); }
ByteRangeRandomizer extends AbstractRangeRandomizer<Byte> { public static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max) { return new ByteRangeRandomizer(min, max); } ByteRangeRandomizer(final Byte min, final Byte max); ByteRangeRandomizer(final Byte min, final Byte max, final long seed); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max, final long seed); @Override Byte getRandomValue(); }
ByteRangeRandomizer extends AbstractRangeRandomizer<Byte> { public static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max) { return new ByteRangeRandomizer(min, max); } ByteRangeRandomizer(final Byte min, final Byte max); ByteRangeRandomizer(final Byte min, final Byte max, final long seed); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max); static ByteRangeRandomizer aNewByteRangeRandomizer(final Byte min, final Byte max, final long seed); @Override Byte getRandomValue(); }
@Test void generatedOffsetDateTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
@Override public OffsetDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getZone()); }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { @Override public OffsetDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getZone()); } }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { @Override public OffsetDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getZone()); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { @Override public OffsetDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getZone()); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); @Override OffsetDateTime getRandomValue(); }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { @Override public OffsetDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getZone()); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); @Override OffsetDateTime getRandomValue(); }
@Test void generatedOffsetDateTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minOffsetDateTime, maxOffsetDateTime); }
@Override public OffsetDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getZone()); }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { @Override public OffsetDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getZone()); } }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { @Override public OffsetDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getZone()); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { @Override public OffsetDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getZone()); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); @Override OffsetDateTime getRandomValue(); }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { @Override public OffsetDateTime getRandomValue() { long minSeconds = min.toEpochSecond(); long maxSeconds = max.toEpochSecond(); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); return OffsetDateTime.ofInstant(Instant.ofEpochSecond(seconds, nanoSeconds), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getZone()); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); @Override OffsetDateTime getRandomValue(); }
@Test void whenSpecifiedMinOffsetDateTimeIsAfterMaxOffsetDateTime_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewOffsetDateTimeRangeRandomizer(maxOffsetDateTime, minOffsetDateTime)).isInstanceOf(IllegalArgumentException.class); }
public static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max) { return new OffsetDateTimeRangeRandomizer(min, max); }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { public static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max) { return new OffsetDateTimeRangeRandomizer(min, max); } }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { public static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max) { return new OffsetDateTimeRangeRandomizer(min, max); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { public static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max) { return new OffsetDateTimeRangeRandomizer(min, max); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); @Override OffsetDateTime getRandomValue(); }
OffsetDateTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetDateTime> { public static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max) { return new OffsetDateTimeRangeRandomizer(min, max); } OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); OffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max); static OffsetDateTimeRangeRandomizer aNewOffsetDateTimeRangeRandomizer(final OffsetDateTime min, final OffsetDateTime max, final long seed); @Override OffsetDateTime getRandomValue(); }
@Test void testIsPublic() { assertThat(ReflectionUtils.isPublic(Foo.class)).isTrue(); assertThat(ReflectionUtils.isPublic(Dummy.class)).isFalse(); }
public static <T> boolean isPublic(final Class<T> type) { return Modifier.isPublic(type.getModifiers()); }
ReflectionUtils { public static <T> boolean isPublic(final Class<T> type) { return Modifier.isPublic(type.getModifiers()); } }
ReflectionUtils { public static <T> boolean isPublic(final Class<T> type) { return Modifier.isPublic(type.getModifiers()); } private ReflectionUtils(); }
ReflectionUtils { public static <T> boolean isPublic(final Class<T> type) { return Modifier.isPublic(type.getModifiers()); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
ReflectionUtils { public static <T> boolean isPublic(final Class<T> type) { return Modifier.isPublic(type.getModifiers()); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
@Test void generatedLocalDateShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
@Override public LocalDate getRandomValue() { long minEpochDay = min.getLong(ChronoField.EPOCH_DAY); long maxEpochDay = max.getLong(ChronoField.EPOCH_DAY); long randomEpochDay = (long) nextDouble(minEpochDay, maxEpochDay); return LocalDate.ofEpochDay(randomEpochDay); }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { @Override public LocalDate getRandomValue() { long minEpochDay = min.getLong(ChronoField.EPOCH_DAY); long maxEpochDay = max.getLong(ChronoField.EPOCH_DAY); long randomEpochDay = (long) nextDouble(minEpochDay, maxEpochDay); return LocalDate.ofEpochDay(randomEpochDay); } }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { @Override public LocalDate getRandomValue() { long minEpochDay = min.getLong(ChronoField.EPOCH_DAY); long maxEpochDay = max.getLong(ChronoField.EPOCH_DAY); long randomEpochDay = (long) nextDouble(minEpochDay, maxEpochDay); return LocalDate.ofEpochDay(randomEpochDay); } LocalDateRangeRandomizer(final LocalDate min, final LocalDate max); LocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { @Override public LocalDate getRandomValue() { long minEpochDay = min.getLong(ChronoField.EPOCH_DAY); long maxEpochDay = max.getLong(ChronoField.EPOCH_DAY); long randomEpochDay = (long) nextDouble(minEpochDay, maxEpochDay); return LocalDate.ofEpochDay(randomEpochDay); } LocalDateRangeRandomizer(final LocalDate min, final LocalDate max); LocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); @Override LocalDate getRandomValue(); }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { @Override public LocalDate getRandomValue() { long minEpochDay = min.getLong(ChronoField.EPOCH_DAY); long maxEpochDay = max.getLong(ChronoField.EPOCH_DAY); long randomEpochDay = (long) nextDouble(minEpochDay, maxEpochDay); return LocalDate.ofEpochDay(randomEpochDay); } LocalDateRangeRandomizer(final LocalDate min, final LocalDate max); LocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); @Override LocalDate getRandomValue(); }
@Test void generatedLocalDateShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDate, maxDate); }
@Override public LocalDate getRandomValue() { long minEpochDay = min.getLong(ChronoField.EPOCH_DAY); long maxEpochDay = max.getLong(ChronoField.EPOCH_DAY); long randomEpochDay = (long) nextDouble(minEpochDay, maxEpochDay); return LocalDate.ofEpochDay(randomEpochDay); }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { @Override public LocalDate getRandomValue() { long minEpochDay = min.getLong(ChronoField.EPOCH_DAY); long maxEpochDay = max.getLong(ChronoField.EPOCH_DAY); long randomEpochDay = (long) nextDouble(minEpochDay, maxEpochDay); return LocalDate.ofEpochDay(randomEpochDay); } }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { @Override public LocalDate getRandomValue() { long minEpochDay = min.getLong(ChronoField.EPOCH_DAY); long maxEpochDay = max.getLong(ChronoField.EPOCH_DAY); long randomEpochDay = (long) nextDouble(minEpochDay, maxEpochDay); return LocalDate.ofEpochDay(randomEpochDay); } LocalDateRangeRandomizer(final LocalDate min, final LocalDate max); LocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { @Override public LocalDate getRandomValue() { long minEpochDay = min.getLong(ChronoField.EPOCH_DAY); long maxEpochDay = max.getLong(ChronoField.EPOCH_DAY); long randomEpochDay = (long) nextDouble(minEpochDay, maxEpochDay); return LocalDate.ofEpochDay(randomEpochDay); } LocalDateRangeRandomizer(final LocalDate min, final LocalDate max); LocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); @Override LocalDate getRandomValue(); }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { @Override public LocalDate getRandomValue() { long minEpochDay = min.getLong(ChronoField.EPOCH_DAY); long maxEpochDay = max.getLong(ChronoField.EPOCH_DAY); long randomEpochDay = (long) nextDouble(minEpochDay, maxEpochDay); return LocalDate.ofEpochDay(randomEpochDay); } LocalDateRangeRandomizer(final LocalDate min, final LocalDate max); LocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); @Override LocalDate getRandomValue(); }
@Test void whenSpecifiedMinDateIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLocalDateRangeRandomizer(maxDate, minDate)).isInstanceOf(IllegalArgumentException.class); }
public static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max) { return new LocalDateRangeRandomizer(min, max); }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { public static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max) { return new LocalDateRangeRandomizer(min, max); } }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { public static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max) { return new LocalDateRangeRandomizer(min, max); } LocalDateRangeRandomizer(final LocalDate min, final LocalDate max); LocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { public static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max) { return new LocalDateRangeRandomizer(min, max); } LocalDateRangeRandomizer(final LocalDate min, final LocalDate max); LocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); @Override LocalDate getRandomValue(); }
LocalDateRangeRandomizer extends AbstractRangeRandomizer<LocalDate> { public static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max) { return new LocalDateRangeRandomizer(min, max); } LocalDateRangeRandomizer(final LocalDate min, final LocalDate max); LocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max); static LocalDateRangeRandomizer aNewLocalDateRangeRandomizer(final LocalDate min, final LocalDate max, final long seed); @Override LocalDate getRandomValue(); }
@Test void generatedInstantShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
@Override public Instant getRandomValue() { long minEpochMillis = min.toEpochMilli(); long maxEpochMillis = max.toEpochMilli(); long randomEpochMillis = (long) nextDouble(minEpochMillis, maxEpochMillis); return Instant.ofEpochMilli(randomEpochMillis); }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { @Override public Instant getRandomValue() { long minEpochMillis = min.toEpochMilli(); long maxEpochMillis = max.toEpochMilli(); long randomEpochMillis = (long) nextDouble(minEpochMillis, maxEpochMillis); return Instant.ofEpochMilli(randomEpochMillis); } }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { @Override public Instant getRandomValue() { long minEpochMillis = min.toEpochMilli(); long maxEpochMillis = max.toEpochMilli(); long randomEpochMillis = (long) nextDouble(minEpochMillis, maxEpochMillis); return Instant.ofEpochMilli(randomEpochMillis); } InstantRangeRandomizer(final Instant min, final Instant max); InstantRangeRandomizer(final Instant min, final Instant max, long seed); }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { @Override public Instant getRandomValue() { long minEpochMillis = min.toEpochMilli(); long maxEpochMillis = max.toEpochMilli(); long randomEpochMillis = (long) nextDouble(minEpochMillis, maxEpochMillis); return Instant.ofEpochMilli(randomEpochMillis); } InstantRangeRandomizer(final Instant min, final Instant max); InstantRangeRandomizer(final Instant min, final Instant max, long seed); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max, final long seed); @Override Instant getRandomValue(); }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { @Override public Instant getRandomValue() { long minEpochMillis = min.toEpochMilli(); long maxEpochMillis = max.toEpochMilli(); long randomEpochMillis = (long) nextDouble(minEpochMillis, maxEpochMillis); return Instant.ofEpochMilli(randomEpochMillis); } InstantRangeRandomizer(final Instant min, final Instant max); InstantRangeRandomizer(final Instant min, final Instant max, long seed); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max, final long seed); @Override Instant getRandomValue(); }
@Test void generatedInstantShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minInstant, maxInstant); }
@Override public Instant getRandomValue() { long minEpochMillis = min.toEpochMilli(); long maxEpochMillis = max.toEpochMilli(); long randomEpochMillis = (long) nextDouble(minEpochMillis, maxEpochMillis); return Instant.ofEpochMilli(randomEpochMillis); }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { @Override public Instant getRandomValue() { long minEpochMillis = min.toEpochMilli(); long maxEpochMillis = max.toEpochMilli(); long randomEpochMillis = (long) nextDouble(minEpochMillis, maxEpochMillis); return Instant.ofEpochMilli(randomEpochMillis); } }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { @Override public Instant getRandomValue() { long minEpochMillis = min.toEpochMilli(); long maxEpochMillis = max.toEpochMilli(); long randomEpochMillis = (long) nextDouble(minEpochMillis, maxEpochMillis); return Instant.ofEpochMilli(randomEpochMillis); } InstantRangeRandomizer(final Instant min, final Instant max); InstantRangeRandomizer(final Instant min, final Instant max, long seed); }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { @Override public Instant getRandomValue() { long minEpochMillis = min.toEpochMilli(); long maxEpochMillis = max.toEpochMilli(); long randomEpochMillis = (long) nextDouble(minEpochMillis, maxEpochMillis); return Instant.ofEpochMilli(randomEpochMillis); } InstantRangeRandomizer(final Instant min, final Instant max); InstantRangeRandomizer(final Instant min, final Instant max, long seed); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max, final long seed); @Override Instant getRandomValue(); }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { @Override public Instant getRandomValue() { long minEpochMillis = min.toEpochMilli(); long maxEpochMillis = max.toEpochMilli(); long randomEpochMillis = (long) nextDouble(minEpochMillis, maxEpochMillis); return Instant.ofEpochMilli(randomEpochMillis); } InstantRangeRandomizer(final Instant min, final Instant max); InstantRangeRandomizer(final Instant min, final Instant max, long seed); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max, final long seed); @Override Instant getRandomValue(); }
@Test void whenSpecifiedMinInstantIsAfterMaxInstant_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewInstantRangeRandomizer(maxInstant, minInstant)).isInstanceOf(IllegalArgumentException.class); }
public static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max) { return new InstantRangeRandomizer(min, max); }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { public static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max) { return new InstantRangeRandomizer(min, max); } }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { public static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max) { return new InstantRangeRandomizer(min, max); } InstantRangeRandomizer(final Instant min, final Instant max); InstantRangeRandomizer(final Instant min, final Instant max, long seed); }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { public static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max) { return new InstantRangeRandomizer(min, max); } InstantRangeRandomizer(final Instant min, final Instant max); InstantRangeRandomizer(final Instant min, final Instant max, long seed); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max, final long seed); @Override Instant getRandomValue(); }
InstantRangeRandomizer extends AbstractRangeRandomizer<Instant> { public static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max) { return new InstantRangeRandomizer(min, max); } InstantRangeRandomizer(final Instant min, final Instant max); InstantRangeRandomizer(final Instant min, final Instant max, long seed); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max); static InstantRangeRandomizer aNewInstantRangeRandomizer(final Instant min, final Instant max, final long seed); @Override Instant getRandomValue(); }
@Test void generatedValueShouldBeWithinSpecifiedRange() { BigInteger randomValue = randomizer.getRandomValue(); assertThat(randomValue.intValue()).isBetween(min, max); }
@Override public BigInteger getRandomValue() { return new BigInteger(String.valueOf(delegate.getRandomValue())); }
BigIntegerRangeRandomizer implements Randomizer<BigInteger> { @Override public BigInteger getRandomValue() { return new BigInteger(String.valueOf(delegate.getRandomValue())); } }
BigIntegerRangeRandomizer implements Randomizer<BigInteger> { @Override public BigInteger getRandomValue() { return new BigInteger(String.valueOf(delegate.getRandomValue())); } BigIntegerRangeRandomizer(final Integer min, final Integer max); BigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); }
BigIntegerRangeRandomizer implements Randomizer<BigInteger> { @Override public BigInteger getRandomValue() { return new BigInteger(String.valueOf(delegate.getRandomValue())); } BigIntegerRangeRandomizer(final Integer min, final Integer max); BigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override BigInteger getRandomValue(); }
BigIntegerRangeRandomizer implements Randomizer<BigInteger> { @Override public BigInteger getRandomValue() { return new BigInteger(String.valueOf(delegate.getRandomValue())); } BigIntegerRangeRandomizer(final Integer min, final Integer max); BigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override BigInteger getRandomValue(); }
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewBigIntegerRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
public static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max) { return new BigIntegerRangeRandomizer(min, max); }
BigIntegerRangeRandomizer implements Randomizer<BigInteger> { public static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max) { return new BigIntegerRangeRandomizer(min, max); } }
BigIntegerRangeRandomizer implements Randomizer<BigInteger> { public static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max) { return new BigIntegerRangeRandomizer(min, max); } BigIntegerRangeRandomizer(final Integer min, final Integer max); BigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); }
BigIntegerRangeRandomizer implements Randomizer<BigInteger> { public static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max) { return new BigIntegerRangeRandomizer(min, max); } BigIntegerRangeRandomizer(final Integer min, final Integer max); BigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override BigInteger getRandomValue(); }
BigIntegerRangeRandomizer implements Randomizer<BigInteger> { public static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max) { return new BigIntegerRangeRandomizer(min, max); } BigIntegerRangeRandomizer(final Integer min, final Integer max); BigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max); static BigIntegerRangeRandomizer aNewBigIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override BigInteger getRandomValue(); }
@Test void generatedOffsetTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
@Override public OffsetTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return OffsetTime.of(LocalTime.ofSecondOfDay(randomSecondOfDay), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getOffset()); }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { @Override public OffsetTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return OffsetTime.of(LocalTime.ofSecondOfDay(randomSecondOfDay), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getOffset()); } }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { @Override public OffsetTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return OffsetTime.of(LocalTime.ofSecondOfDay(randomSecondOfDay), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getOffset()); } OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { @Override public OffsetTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return OffsetTime.of(LocalTime.ofSecondOfDay(randomSecondOfDay), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getOffset()); } OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); @Override OffsetTime getRandomValue(); }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { @Override public OffsetTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return OffsetTime.of(LocalTime.ofSecondOfDay(randomSecondOfDay), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getOffset()); } OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); @Override OffsetTime getRandomValue(); }
@Test void generatedOffsetTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minTime, maxTime); }
@Override public OffsetTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return OffsetTime.of(LocalTime.ofSecondOfDay(randomSecondOfDay), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getOffset()); }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { @Override public OffsetTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return OffsetTime.of(LocalTime.ofSecondOfDay(randomSecondOfDay), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getOffset()); } }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { @Override public OffsetTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return OffsetTime.of(LocalTime.ofSecondOfDay(randomSecondOfDay), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getOffset()); } OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { @Override public OffsetTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return OffsetTime.of(LocalTime.ofSecondOfDay(randomSecondOfDay), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getOffset()); } OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); @Override OffsetTime getRandomValue(); }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { @Override public OffsetTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return OffsetTime.of(LocalTime.ofSecondOfDay(randomSecondOfDay), EasyRandomParameters.DEFAULT_DATES_RANGE.getMin().getOffset()); } OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); @Override OffsetTime getRandomValue(); }
@Test void testIsArrayType() { assertThat(ReflectionUtils.isArrayType(int[].class)).isTrue(); assertThat(ReflectionUtils.isArrayType(Foo.class)).isFalse(); }
public static boolean isArrayType(final Class<?> type) { return type.isArray(); }
ReflectionUtils { public static boolean isArrayType(final Class<?> type) { return type.isArray(); } }
ReflectionUtils { public static boolean isArrayType(final Class<?> type) { return type.isArray(); } private ReflectionUtils(); }
ReflectionUtils { public static boolean isArrayType(final Class<?> type) { return type.isArray(); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
ReflectionUtils { public static boolean isArrayType(final Class<?> type) { return type.isArray(); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
@Test void whenSpecifiedMinTimeIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewOffsetTimeRangeRandomizer(maxTime, minTime)).isInstanceOf(IllegalArgumentException.class); }
public static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max) { return new OffsetTimeRangeRandomizer(min, max); }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { public static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max) { return new OffsetTimeRangeRandomizer(min, max); } }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { public static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max) { return new OffsetTimeRangeRandomizer(min, max); } OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { public static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max) { return new OffsetTimeRangeRandomizer(min, max); } OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); @Override OffsetTime getRandomValue(); }
OffsetTimeRangeRandomizer extends AbstractRangeRandomizer<OffsetTime> { public static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max) { return new OffsetTimeRangeRandomizer(min, max); } OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); OffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max); static OffsetTimeRangeRandomizer aNewOffsetTimeRangeRandomizer(final OffsetTime min, final OffsetTime max, final long seed); @Override OffsetTime getRandomValue(); }
@Test void generatedLocalTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
@Override public LocalTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return LocalTime.ofSecondOfDay(randomSecondOfDay); }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { @Override public LocalTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return LocalTime.ofSecondOfDay(randomSecondOfDay); } }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { @Override public LocalTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return LocalTime.ofSecondOfDay(randomSecondOfDay); } LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { @Override public LocalTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return LocalTime.ofSecondOfDay(randomSecondOfDay); } LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); @Override LocalTime getRandomValue(); }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { @Override public LocalTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return LocalTime.ofSecondOfDay(randomSecondOfDay); } LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); @Override LocalTime getRandomValue(); }
@Test void generatedLocalTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minTime, maxTime); }
@Override public LocalTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return LocalTime.ofSecondOfDay(randomSecondOfDay); }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { @Override public LocalTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return LocalTime.ofSecondOfDay(randomSecondOfDay); } }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { @Override public LocalTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return LocalTime.ofSecondOfDay(randomSecondOfDay); } LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { @Override public LocalTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return LocalTime.ofSecondOfDay(randomSecondOfDay); } LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); @Override LocalTime getRandomValue(); }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { @Override public LocalTime getRandomValue() { long minSecondOfDay = min.getLong(ChronoField.SECOND_OF_DAY); long maxSecondOfDay = max.getLong(ChronoField.SECOND_OF_DAY); long randomSecondOfDay = (long) nextDouble(minSecondOfDay, maxSecondOfDay); return LocalTime.ofSecondOfDay(randomSecondOfDay); } LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); @Override LocalTime getRandomValue(); }
@Test void whenSpecifiedMinTimeIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLocalTimeRangeRandomizer(maxTime, minTime)).isInstanceOf(IllegalArgumentException.class); }
public static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max) { return new LocalTimeRangeRandomizer(min, max); }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { public static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max) { return new LocalTimeRangeRandomizer(min, max); } }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { public static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max) { return new LocalTimeRangeRandomizer(min, max); } LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { public static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max) { return new LocalTimeRangeRandomizer(min, max); } LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); @Override LocalTime getRandomValue(); }
LocalTimeRangeRandomizer extends AbstractRangeRandomizer<LocalTime> { public static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max) { return new LocalTimeRangeRandomizer(min, max); } LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); LocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max); static LocalTimeRangeRandomizer aNewLocalTimeRangeRandomizer(final LocalTime min, final LocalTime max, final long seed); @Override LocalTime getRandomValue(); }
@Test void generatedDateShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
@Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble((double) minDateTime, (double) maxDateTime); return new Date(randomDateTime); }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble((double) minDateTime, (double) maxDateTime); return new Date(randomDateTime); } }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble((double) minDateTime, (double) maxDateTime); return new Date(randomDateTime); } DateRangeRandomizer(final Date min, final Date max); DateRangeRandomizer(final Date min, final Date max, final long seed); }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble((double) minDateTime, (double) maxDateTime); return new Date(randomDateTime); } DateRangeRandomizer(final Date min, final Date max); DateRangeRandomizer(final Date min, final Date max, final long seed); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble((double) minDateTime, (double) maxDateTime); return new Date(randomDateTime); } DateRangeRandomizer(final Date min, final Date max); DateRangeRandomizer(final Date min, final Date max, final long seed); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }
@Test void generatedDateShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDate, maxDate); }
@Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble((double) minDateTime, (double) maxDateTime); return new Date(randomDateTime); }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble((double) minDateTime, (double) maxDateTime); return new Date(randomDateTime); } }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble((double) minDateTime, (double) maxDateTime); return new Date(randomDateTime); } DateRangeRandomizer(final Date min, final Date max); DateRangeRandomizer(final Date min, final Date max, final long seed); }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble((double) minDateTime, (double) maxDateTime); return new Date(randomDateTime); } DateRangeRandomizer(final Date min, final Date max); DateRangeRandomizer(final Date min, final Date max, final long seed); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { @Override public Date getRandomValue() { long minDateTime = min.getTime(); long maxDateTime = max.getTime(); long randomDateTime = (long) nextDouble((double) minDateTime, (double) maxDateTime); return new Date(randomDateTime); } DateRangeRandomizer(final Date min, final Date max); DateRangeRandomizer(final Date min, final Date max, final long seed); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }
@Test void whenSpecifiedMinDateIsAfterMaxDate_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewDateRangeRandomizer(maxDate, minDate)).isInstanceOf(IllegalArgumentException.class); }
public static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max) { return new DateRangeRandomizer(min, max); }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { public static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max) { return new DateRangeRandomizer(min, max); } }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { public static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max) { return new DateRangeRandomizer(min, max); } DateRangeRandomizer(final Date min, final Date max); DateRangeRandomizer(final Date min, final Date max, final long seed); }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { public static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max) { return new DateRangeRandomizer(min, max); } DateRangeRandomizer(final Date min, final Date max); DateRangeRandomizer(final Date min, final Date max, final long seed); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }
DateRangeRandomizer extends AbstractRangeRandomizer<Date> { public static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max) { return new DateRangeRandomizer(min, max); } DateRangeRandomizer(final Date min, final Date max); DateRangeRandomizer(final Date min, final Date max, final long seed); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max); static DateRangeRandomizer aNewDateRangeRandomizer(final Date min, final Date max, final long seed); @Override Date getRandomValue(); }
@Test void generatedYearMonthShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
@Override public YearMonth getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); long minMonth = min.getLong(ChronoField.MONTH_OF_YEAR); long maxMonth = max.getLong(ChronoField.MONTH_OF_YEAR); long randomMonth = (long) nextDouble(minMonth, maxMonth); return YearMonth.of(Math.toIntExact(randomYear), Math.toIntExact(randomMonth)); }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { @Override public YearMonth getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); long minMonth = min.getLong(ChronoField.MONTH_OF_YEAR); long maxMonth = max.getLong(ChronoField.MONTH_OF_YEAR); long randomMonth = (long) nextDouble(minMonth, maxMonth); return YearMonth.of(Math.toIntExact(randomYear), Math.toIntExact(randomMonth)); } }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { @Override public YearMonth getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); long minMonth = min.getLong(ChronoField.MONTH_OF_YEAR); long maxMonth = max.getLong(ChronoField.MONTH_OF_YEAR); long randomMonth = (long) nextDouble(minMonth, maxMonth); return YearMonth.of(Math.toIntExact(randomYear), Math.toIntExact(randomMonth)); } YearMonthRangeRandomizer(final YearMonth min, final YearMonth max); YearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { @Override public YearMonth getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); long minMonth = min.getLong(ChronoField.MONTH_OF_YEAR); long maxMonth = max.getLong(ChronoField.MONTH_OF_YEAR); long randomMonth = (long) nextDouble(minMonth, maxMonth); return YearMonth.of(Math.toIntExact(randomYear), Math.toIntExact(randomMonth)); } YearMonthRangeRandomizer(final YearMonth min, final YearMonth max); YearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); @Override YearMonth getRandomValue(); }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { @Override public YearMonth getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); long minMonth = min.getLong(ChronoField.MONTH_OF_YEAR); long maxMonth = max.getLong(ChronoField.MONTH_OF_YEAR); long randomMonth = (long) nextDouble(minMonth, maxMonth); return YearMonth.of(Math.toIntExact(randomYear), Math.toIntExact(randomMonth)); } YearMonthRangeRandomizer(final YearMonth min, final YearMonth max); YearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); @Override YearMonth getRandomValue(); }
@Test void generatedYearMonthShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minYearMonth, maxYearMonth); }
@Override public YearMonth getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); long minMonth = min.getLong(ChronoField.MONTH_OF_YEAR); long maxMonth = max.getLong(ChronoField.MONTH_OF_YEAR); long randomMonth = (long) nextDouble(minMonth, maxMonth); return YearMonth.of(Math.toIntExact(randomYear), Math.toIntExact(randomMonth)); }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { @Override public YearMonth getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); long minMonth = min.getLong(ChronoField.MONTH_OF_YEAR); long maxMonth = max.getLong(ChronoField.MONTH_OF_YEAR); long randomMonth = (long) nextDouble(minMonth, maxMonth); return YearMonth.of(Math.toIntExact(randomYear), Math.toIntExact(randomMonth)); } }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { @Override public YearMonth getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); long minMonth = min.getLong(ChronoField.MONTH_OF_YEAR); long maxMonth = max.getLong(ChronoField.MONTH_OF_YEAR); long randomMonth = (long) nextDouble(minMonth, maxMonth); return YearMonth.of(Math.toIntExact(randomYear), Math.toIntExact(randomMonth)); } YearMonthRangeRandomizer(final YearMonth min, final YearMonth max); YearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { @Override public YearMonth getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); long minMonth = min.getLong(ChronoField.MONTH_OF_YEAR); long maxMonth = max.getLong(ChronoField.MONTH_OF_YEAR); long randomMonth = (long) nextDouble(minMonth, maxMonth); return YearMonth.of(Math.toIntExact(randomYear), Math.toIntExact(randomMonth)); } YearMonthRangeRandomizer(final YearMonth min, final YearMonth max); YearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); @Override YearMonth getRandomValue(); }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { @Override public YearMonth getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); long minMonth = min.getLong(ChronoField.MONTH_OF_YEAR); long maxMonth = max.getLong(ChronoField.MONTH_OF_YEAR); long randomMonth = (long) nextDouble(minMonth, maxMonth); return YearMonth.of(Math.toIntExact(randomYear), Math.toIntExact(randomMonth)); } YearMonthRangeRandomizer(final YearMonth min, final YearMonth max); YearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); @Override YearMonth getRandomValue(); }
@Test void whenSpecifiedMinYearMonthIsAfterMaxYearMonth_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewYearMonthRangeRandomizer(maxYearMonth, minYearMonth)).isInstanceOf(IllegalArgumentException.class); }
public static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max) { return new YearMonthRangeRandomizer(min, max); }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { public static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max) { return new YearMonthRangeRandomizer(min, max); } }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { public static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max) { return new YearMonthRangeRandomizer(min, max); } YearMonthRangeRandomizer(final YearMonth min, final YearMonth max); YearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { public static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max) { return new YearMonthRangeRandomizer(min, max); } YearMonthRangeRandomizer(final YearMonth min, final YearMonth max); YearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); @Override YearMonth getRandomValue(); }
YearMonthRangeRandomizer extends AbstractRangeRandomizer<YearMonth> { public static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max) { return new YearMonthRangeRandomizer(min, max); } YearMonthRangeRandomizer(final YearMonth min, final YearMonth max); YearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max); static YearMonthRangeRandomizer aNewYearMonthRangeRandomizer(final YearMonth min, final YearMonth max, final long seed); @Override YearMonth getRandomValue(); }
@Test void testIsEnumType() { assertThat(ReflectionUtils.isEnumType(Gender.class)).isTrue(); assertThat(ReflectionUtils.isEnumType(Foo.class)).isFalse(); }
public static boolean isEnumType(final Class<?> type) { return type.isEnum(); }
ReflectionUtils { public static boolean isEnumType(final Class<?> type) { return type.isEnum(); } }
ReflectionUtils { public static boolean isEnumType(final Class<?> type) { return type.isEnum(); } private ReflectionUtils(); }
ReflectionUtils { public static boolean isEnumType(final Class<?> type) { return type.isEnum(); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
ReflectionUtils { public static boolean isEnumType(final Class<?> type) { return type.isEnum(); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
@Test void generatedYearShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
@Override public Year getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); return Year.of(Math.toIntExact(randomYear)); }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { @Override public Year getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); return Year.of(Math.toIntExact(randomYear)); } }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { @Override public Year getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); return Year.of(Math.toIntExact(randomYear)); } YearRangeRandomizer(final Year min, final Year max); YearRangeRandomizer(final Year min, final Year max, final long seed); }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { @Override public Year getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); return Year.of(Math.toIntExact(randomYear)); } YearRangeRandomizer(final Year min, final Year max); YearRangeRandomizer(final Year min, final Year max, final long seed); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max, final long seed); @Override Year getRandomValue(); }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { @Override public Year getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); return Year.of(Math.toIntExact(randomYear)); } YearRangeRandomizer(final Year min, final Year max); YearRangeRandomizer(final Year min, final Year max, final long seed); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max, final long seed); @Override Year getRandomValue(); }
@Test void generatedYearShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minYear, maxYear); }
@Override public Year getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); return Year.of(Math.toIntExact(randomYear)); }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { @Override public Year getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); return Year.of(Math.toIntExact(randomYear)); } }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { @Override public Year getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); return Year.of(Math.toIntExact(randomYear)); } YearRangeRandomizer(final Year min, final Year max); YearRangeRandomizer(final Year min, final Year max, final long seed); }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { @Override public Year getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); return Year.of(Math.toIntExact(randomYear)); } YearRangeRandomizer(final Year min, final Year max); YearRangeRandomizer(final Year min, final Year max, final long seed); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max, final long seed); @Override Year getRandomValue(); }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { @Override public Year getRandomValue() { long minYear = min.getLong(ChronoField.YEAR); long maxYear = max.getLong(ChronoField.YEAR); long randomYear = (long) nextDouble(minYear, maxYear); return Year.of(Math.toIntExact(randomYear)); } YearRangeRandomizer(final Year min, final Year max); YearRangeRandomizer(final Year min, final Year max, final long seed); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max, final long seed); @Override Year getRandomValue(); }
@Test void whenSpecifiedMinYearIsAfterMaxYear_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewYearRangeRandomizer(maxYear, minYear)).isInstanceOf(IllegalArgumentException.class); }
public static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max) { return new YearRangeRandomizer(min, max); }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { public static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max) { return new YearRangeRandomizer(min, max); } }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { public static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max) { return new YearRangeRandomizer(min, max); } YearRangeRandomizer(final Year min, final Year max); YearRangeRandomizer(final Year min, final Year max, final long seed); }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { public static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max) { return new YearRangeRandomizer(min, max); } YearRangeRandomizer(final Year min, final Year max); YearRangeRandomizer(final Year min, final Year max, final long seed); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max, final long seed); @Override Year getRandomValue(); }
YearRangeRandomizer extends AbstractRangeRandomizer<Year> { public static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max) { return new YearRangeRandomizer(min, max); } YearRangeRandomizer(final Year min, final Year max); YearRangeRandomizer(final Year min, final Year max, final long seed); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max); static YearRangeRandomizer aNewYearRangeRandomizer(final Year min, final Year max, final long seed); @Override Year getRandomValue(); }
@Test void generatedValueShouldBeWithinSpecifiedRange() { Long randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
@Override public Long getRandomValue() { return (long) nextDouble(min, max); }
LongRangeRandomizer extends AbstractRangeRandomizer<Long> { @Override public Long getRandomValue() { return (long) nextDouble(min, max); } }
LongRangeRandomizer extends AbstractRangeRandomizer<Long> { @Override public Long getRandomValue() { return (long) nextDouble(min, max); } LongRangeRandomizer(final Long min, final Long max); LongRangeRandomizer(final Long min, final Long max, final long seed); }
LongRangeRandomizer extends AbstractRangeRandomizer<Long> { @Override public Long getRandomValue() { return (long) nextDouble(min, max); } LongRangeRandomizer(final Long min, final Long max); LongRangeRandomizer(final Long min, final Long max, final long seed); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max, final long seed); @Override Long getRandomValue(); }
LongRangeRandomizer extends AbstractRangeRandomizer<Long> { @Override public Long getRandomValue() { return (long) nextDouble(min, max); } LongRangeRandomizer(final Long min, final Long max); LongRangeRandomizer(final Long min, final Long max, final long seed); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max, final long seed); @Override Long getRandomValue(); }
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLongRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
public static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max) { return new LongRangeRandomizer(min, max); }
LongRangeRandomizer extends AbstractRangeRandomizer<Long> { public static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max) { return new LongRangeRandomizer(min, max); } }
LongRangeRandomizer extends AbstractRangeRandomizer<Long> { public static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max) { return new LongRangeRandomizer(min, max); } LongRangeRandomizer(final Long min, final Long max); LongRangeRandomizer(final Long min, final Long max, final long seed); }
LongRangeRandomizer extends AbstractRangeRandomizer<Long> { public static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max) { return new LongRangeRandomizer(min, max); } LongRangeRandomizer(final Long min, final Long max); LongRangeRandomizer(final Long min, final Long max, final long seed); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max, final long seed); @Override Long getRandomValue(); }
LongRangeRandomizer extends AbstractRangeRandomizer<Long> { public static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max) { return new LongRangeRandomizer(min, max); } LongRangeRandomizer(final Long min, final Long max); LongRangeRandomizer(final Long min, final Long max, final long seed); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max); static LongRangeRandomizer aNewLongRangeRandomizer(final Long min, final Long max, final long seed); @Override Long getRandomValue(); }
@Test void generatedLocalDateTimeShouldNotBeNull() { assertThat(randomizer.getRandomValue()).isNotNull(); }
@Override public LocalDateTime getRandomValue() { long minSeconds = min.toEpochSecond(ZoneOffset.UTC); long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); Instant instant = Instant.ofEpochSecond(seconds, nanoSeconds); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { @Override public LocalDateTime getRandomValue() { long minSeconds = min.toEpochSecond(ZoneOffset.UTC); long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); Instant instant = Instant.ofEpochSecond(seconds, nanoSeconds); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { @Override public LocalDateTime getRandomValue() { long minSeconds = min.toEpochSecond(ZoneOffset.UTC); long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); Instant instant = Instant.ofEpochSecond(seconds, nanoSeconds); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { @Override public LocalDateTime getRandomValue() { long minSeconds = min.toEpochSecond(ZoneOffset.UTC); long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); Instant instant = Instant.ofEpochSecond(seconds, nanoSeconds); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); @Override LocalDateTime getRandomValue(); }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { @Override public LocalDateTime getRandomValue() { long minSeconds = min.toEpochSecond(ZoneOffset.UTC); long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); Instant instant = Instant.ofEpochSecond(seconds, nanoSeconds); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); @Override LocalDateTime getRandomValue(); }
@Test void generatedLocalDateTimeShouldBeWithinSpecifiedRange() { assertThat(randomizer.getRandomValue()).isBetween(minDateTime, maxDateTime); }
@Override public LocalDateTime getRandomValue() { long minSeconds = min.toEpochSecond(ZoneOffset.UTC); long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); Instant instant = Instant.ofEpochSecond(seconds, nanoSeconds); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { @Override public LocalDateTime getRandomValue() { long minSeconds = min.toEpochSecond(ZoneOffset.UTC); long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); Instant instant = Instant.ofEpochSecond(seconds, nanoSeconds); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { @Override public LocalDateTime getRandomValue() { long minSeconds = min.toEpochSecond(ZoneOffset.UTC); long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); Instant instant = Instant.ofEpochSecond(seconds, nanoSeconds); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { @Override public LocalDateTime getRandomValue() { long minSeconds = min.toEpochSecond(ZoneOffset.UTC); long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); Instant instant = Instant.ofEpochSecond(seconds, nanoSeconds); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); @Override LocalDateTime getRandomValue(); }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { @Override public LocalDateTime getRandomValue() { long minSeconds = min.toEpochSecond(ZoneOffset.UTC); long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); long seconds = (long) nextDouble(minSeconds, maxSeconds); int minNanoSeconds = min.getNano(); int maxNanoSeconds = max.getNano(); long nanoSeconds = (long) nextDouble(minNanoSeconds, maxNanoSeconds); Instant instant = Instant.ofEpochSecond(seconds, nanoSeconds); return LocalDateTime.ofInstant(instant, ZoneOffset.UTC); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); @Override LocalDateTime getRandomValue(); }
@Test void whenSpecifiedMinDateTimeIsAfterMaxDateTime_thenShouldThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewLocalDateTimeRangeRandomizer(maxDateTime, minDateTime)).isInstanceOf(IllegalArgumentException.class); }
public static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max) { return new LocalDateTimeRangeRandomizer(min, max); }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { public static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max) { return new LocalDateTimeRangeRandomizer(min, max); } }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { public static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max) { return new LocalDateTimeRangeRandomizer(min, max); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { public static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max) { return new LocalDateTimeRangeRandomizer(min, max); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); @Override LocalDateTime getRandomValue(); }
LocalDateTimeRangeRandomizer extends AbstractRangeRandomizer<LocalDateTime> { public static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max) { return new LocalDateTimeRangeRandomizer(min, max); } LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); LocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max); static LocalDateTimeRangeRandomizer aNewLocalDateTimeRangeRandomizer(final LocalDateTime min, final LocalDateTime max, final long seed); @Override LocalDateTime getRandomValue(); }
@Test void generatedValueShouldBeWithinSpecifiedRange() { Integer randomValue = randomizer.getRandomValue(); assertThat(randomValue).isBetween(min, max); }
@Override public Integer getRandomValue() { return (int) nextDouble(min, max); }
IntegerRangeRandomizer extends AbstractRangeRandomizer<Integer> { @Override public Integer getRandomValue() { return (int) nextDouble(min, max); } }
IntegerRangeRandomizer extends AbstractRangeRandomizer<Integer> { @Override public Integer getRandomValue() { return (int) nextDouble(min, max); } IntegerRangeRandomizer(final Integer min, final Integer max); IntegerRangeRandomizer(final Integer min, final Integer max, final long seed); }
IntegerRangeRandomizer extends AbstractRangeRandomizer<Integer> { @Override public Integer getRandomValue() { return (int) nextDouble(min, max); } IntegerRangeRandomizer(final Integer min, final Integer max); IntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override Integer getRandomValue(); }
IntegerRangeRandomizer extends AbstractRangeRandomizer<Integer> { @Override public Integer getRandomValue() { return (int) nextDouble(min, max); } IntegerRangeRandomizer(final Integer min, final Integer max); IntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override Integer getRandomValue(); }
@Test void whenSpecifiedMinValueIsAfterMaxValueThenThrowIllegalArgumentException() { assertThatThrownBy(() -> aNewIntegerRangeRandomizer(max, min)).isInstanceOf(IllegalArgumentException.class); }
public static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max) { return new IntegerRangeRandomizer(min, max); }
IntegerRangeRandomizer extends AbstractRangeRandomizer<Integer> { public static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max) { return new IntegerRangeRandomizer(min, max); } }
IntegerRangeRandomizer extends AbstractRangeRandomizer<Integer> { public static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max) { return new IntegerRangeRandomizer(min, max); } IntegerRangeRandomizer(final Integer min, final Integer max); IntegerRangeRandomizer(final Integer min, final Integer max, final long seed); }
IntegerRangeRandomizer extends AbstractRangeRandomizer<Integer> { public static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max) { return new IntegerRangeRandomizer(min, max); } IntegerRangeRandomizer(final Integer min, final Integer max); IntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override Integer getRandomValue(); }
IntegerRangeRandomizer extends AbstractRangeRandomizer<Integer> { public static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max) { return new IntegerRangeRandomizer(min, max); } IntegerRangeRandomizer(final Integer min, final Integer max); IntegerRangeRandomizer(final Integer min, final Integer max, final long seed); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max); static IntegerRangeRandomizer aNewIntegerRangeRandomizer(final Integer min, final Integer max, final long seed); @Override Integer getRandomValue(); }
@Test void testIsCollectionType() { assertThat(ReflectionUtils.isCollectionType(CustomList.class)).isTrue(); assertThat(ReflectionUtils.isCollectionType(Foo.class)).isFalse(); }
public static boolean isCollectionType(final Class<?> type) { return Collection.class.isAssignableFrom(type); }
ReflectionUtils { public static boolean isCollectionType(final Class<?> type) { return Collection.class.isAssignableFrom(type); } }
ReflectionUtils { public static boolean isCollectionType(final Class<?> type) { return Collection.class.isAssignableFrom(type); } private ReflectionUtils(); }
ReflectionUtils { public static boolean isCollectionType(final Class<?> type) { return Collection.class.isAssignableFrom(type); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
ReflectionUtils { public static boolean isCollectionType(final Class<?> type) { return Collection.class.isAssignableFrom(type); } private ReflectionUtils(); @SuppressWarnings("unchecked") static Randomizer<T> asRandomizer(final Supplier<T> supplier); static List<Field> getDeclaredFields(T type); static List<Field> getInheritedFields(Class<?> type); static void setProperty(final Object object, final Field field, final Object value); static void setFieldValue(final Object object, final Field field, final Object value); static Object getFieldValue(final Object object, final Field field); static Class<?> getWrapperType(Class<?> primitiveType); static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field); static boolean isStatic(final Field field); static boolean isInterface(final Class<?> type); static boolean isAbstract(final Class<T> type); static boolean isPublic(final Class<T> type); static boolean isArrayType(final Class<?> type); static boolean isEnumType(final Class<?> type); static boolean isCollectionType(final Class<?> type); static boolean isCollectionType(final Type type); static boolean isPopulatable(final Type type); static boolean isIntrospectable(final Class<?> type); static boolean isMapType(final Class<?> type); static boolean isJdkBuiltIn(final Class<?> type); static boolean isParameterizedType(final Type type); static boolean isWildcardType(final Type type); static boolean isTypeVariable(final Type type); static List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type); static List<Class<?>> filterSameParameterizedTypes(final List<Class<?>> types, final Type type); static T getAnnotation(Field field, Class<T> annotationType); static boolean isAnnotationPresent(Field field, Class<? extends Annotation> annotationType); static Collection<?> getEmptyImplementationForCollectionInterface(final Class<?> collectionInterface); static Collection<?> createEmptyCollectionForType(Class<?> fieldType, int initialSize); static Map<?, ?> getEmptyImplementationForMapInterface(final Class<?> mapInterface); static Optional<Method> getReadMethod(Field field); @SuppressWarnings("unchecked") static Randomizer<T> newInstance(final Class<T> type, final RandomizerArgument[] randomizerArguments); }
@Test public void testGetNumberPhoneticRhymePart() { assertEquals(wordParser.phoneticRhymePart("-1"), "uno"); assertEquals(wordParser.phoneticRhymePart("0"), "ero"); assertEquals(wordParser.phoneticRhymePart("dos"), "os"); assertEquals(wordParser.phoneticRhymePart("3521637"), "ete"); assertEquals(wordParser.phoneticRhymePart("350000"), "il"); assertEquals(wordParser.phoneticRhymePart("5000000"), "ones"); }
@Override public String phoneticRhymePart(final String word) { String withoutPunctuation = removeTwitterChars(removeTrailingPunctuation(word)); if (WordUtils.isNumber(withoutPunctuation)) { withoutPunctuation = SpanishNumber.getBaseSound(withoutPunctuation); } String rhymePart = rhymePart(withoutPunctuation); StringBuilder result = new StringBuilder(); char[] letters = rhymePart.toCharArray(); for (int i = 0; i < letters.length; i++) { switch (letters[i]) { case 225: result.append('a'); break; case 233: result.append('e'); break; case 237: result.append('i'); break; case 243: result.append('o'); break; case 250: result.append('u'); break; case 252: result.append('u'); break; case 'b': result.append('v'); break; case 'y': result.append("ll"); break; case 'h': if (i > 0 && letters[i - 1] == 'c') { result.append('h'); } break; case 'g': if (i + 1 < letters.length && (letters[i + 1] == 'e' || letters[i + 1] == 'i')) { result.append('j'); } else { result.append('g'); } break; default: result.append(letters[i]); break; } } return result.toString(); }
SpanishWordParser implements WordParser { @Override public String phoneticRhymePart(final String word) { String withoutPunctuation = removeTwitterChars(removeTrailingPunctuation(word)); if (WordUtils.isNumber(withoutPunctuation)) { withoutPunctuation = SpanishNumber.getBaseSound(withoutPunctuation); } String rhymePart = rhymePart(withoutPunctuation); StringBuilder result = new StringBuilder(); char[] letters = rhymePart.toCharArray(); for (int i = 0; i < letters.length; i++) { switch (letters[i]) { case 225: result.append('a'); break; case 233: result.append('e'); break; case 237: result.append('i'); break; case 243: result.append('o'); break; case 250: result.append('u'); break; case 252: result.append('u'); break; case 'b': result.append('v'); break; case 'y': result.append("ll"); break; case 'h': if (i > 0 && letters[i - 1] == 'c') { result.append('h'); } break; case 'g': if (i + 1 < letters.length && (letters[i + 1] == 'e' || letters[i + 1] == 'i')) { result.append('j'); } else { result.append('g'); } break; default: result.append(letters[i]); break; } } return result.toString(); } }
SpanishWordParser implements WordParser { @Override public String phoneticRhymePart(final String word) { String withoutPunctuation = removeTwitterChars(removeTrailingPunctuation(word)); if (WordUtils.isNumber(withoutPunctuation)) { withoutPunctuation = SpanishNumber.getBaseSound(withoutPunctuation); } String rhymePart = rhymePart(withoutPunctuation); StringBuilder result = new StringBuilder(); char[] letters = rhymePart.toCharArray(); for (int i = 0; i < letters.length; i++) { switch (letters[i]) { case 225: result.append('a'); break; case 233: result.append('e'); break; case 237: result.append('i'); break; case 243: result.append('o'); break; case 250: result.append('u'); break; case 252: result.append('u'); break; case 'b': result.append('v'); break; case 'y': result.append("ll"); break; case 'h': if (i > 0 && letters[i - 1] == 'c') { result.append('h'); } break; case 'g': if (i + 1 < letters.length && (letters[i + 1] == 'e' || letters[i + 1] == 'i')) { result.append('j'); } else { result.append('g'); } break; default: result.append(letters[i]); break; } } return result.toString(); } @Inject SpanishWordParser(final @Named(FALLBACK_RHYMES) List<String> defaultRhymes); }
SpanishWordParser implements WordParser { @Override public String phoneticRhymePart(final String word) { String withoutPunctuation = removeTwitterChars(removeTrailingPunctuation(word)); if (WordUtils.isNumber(withoutPunctuation)) { withoutPunctuation = SpanishNumber.getBaseSound(withoutPunctuation); } String rhymePart = rhymePart(withoutPunctuation); StringBuilder result = new StringBuilder(); char[] letters = rhymePart.toCharArray(); for (int i = 0; i < letters.length; i++) { switch (letters[i]) { case 225: result.append('a'); break; case 233: result.append('e'); break; case 237: result.append('i'); break; case 243: result.append('o'); break; case 250: result.append('u'); break; case 252: result.append('u'); break; case 'b': result.append('v'); break; case 'y': result.append("ll"); break; case 'h': if (i > 0 && letters[i - 1] == 'c') { result.append('h'); } break; case 'g': if (i + 1 < letters.length && (letters[i + 1] == 'e' || letters[i + 1] == 'i')) { result.append('j'); } else { result.append('g'); } break; default: result.append(letters[i]); break; } } return result.toString(); } @Inject SpanishWordParser(final @Named(FALLBACK_RHYMES) List<String> defaultRhymes); @Override StressType stressType(final String word); @Override boolean rhyme(final String word1, final String word2); @Override String phoneticRhymePart(final String word); @Override boolean isLetter(final char letter); @Override boolean isWord(final String text); @Override String getDefaultRhyme(); }
SpanishWordParser implements WordParser { @Override public String phoneticRhymePart(final String word) { String withoutPunctuation = removeTwitterChars(removeTrailingPunctuation(word)); if (WordUtils.isNumber(withoutPunctuation)) { withoutPunctuation = SpanishNumber.getBaseSound(withoutPunctuation); } String rhymePart = rhymePart(withoutPunctuation); StringBuilder result = new StringBuilder(); char[] letters = rhymePart.toCharArray(); for (int i = 0; i < letters.length; i++) { switch (letters[i]) { case 225: result.append('a'); break; case 233: result.append('e'); break; case 237: result.append('i'); break; case 243: result.append('o'); break; case 250: result.append('u'); break; case 252: result.append('u'); break; case 'b': result.append('v'); break; case 'y': result.append("ll"); break; case 'h': if (i > 0 && letters[i - 1] == 'c') { result.append('h'); } break; case 'g': if (i + 1 < letters.length && (letters[i + 1] == 'e' || letters[i + 1] == 'i')) { result.append('j'); } else { result.append('g'); } break; default: result.append(letters[i]); break; } } return result.toString(); } @Inject SpanishWordParser(final @Named(FALLBACK_RHYMES) List<String> defaultRhymes); @Override StressType stressType(final String word); @Override boolean rhyme(final String word1, final String word2); @Override String phoneticRhymePart(final String word); @Override boolean isLetter(final char letter); @Override boolean isWord(final String text); @Override String getDefaultRhyme(); }
@Test(expectedExceptions = IOException.class) public void testDeleteUnexistingRhyme() throws IOException { store.delete("Unexisting"); }
public void delete(final String sentence) throws IOException { String word = WordUtils.getLastWord(sentence); if (word.isEmpty()) { return; } String rhyme = normalizeString(wordParser.phoneticRhymePart(word)); StressType type = wordParser.stressType(word); connect(); try { String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence)); if (redis.exists(sentenceKey) == 0) { throw new IOException("The element to remove does not exist."); } String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type)); String sentenceId = redis.get(sentenceKey); sentenceId = sentencens.build(sentenceId).toString(); if (redis.exists(indexKey) == 1) { String indexId = redis.get(indexKey); indexId = indexns.build(indexId).toString(); if (redis.exists(indexId) == 1) { redis.srem(indexId, sentenceId); } if (redis.smembers(indexId).isEmpty()) { redis.del(indexId, indexKey); } } redis.del(sentenceId, sentenceKey); LOGGER.info("Deleted rhyme: {}", sentence); } finally { disconnect(); } }
RedisStore { public void delete(final String sentence) throws IOException { String word = WordUtils.getLastWord(sentence); if (word.isEmpty()) { return; } String rhyme = normalizeString(wordParser.phoneticRhymePart(word)); StressType type = wordParser.stressType(word); connect(); try { String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence)); if (redis.exists(sentenceKey) == 0) { throw new IOException("The element to remove does not exist."); } String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type)); String sentenceId = redis.get(sentenceKey); sentenceId = sentencens.build(sentenceId).toString(); if (redis.exists(indexKey) == 1) { String indexId = redis.get(indexKey); indexId = indexns.build(indexId).toString(); if (redis.exists(indexId) == 1) { redis.srem(indexId, sentenceId); } if (redis.smembers(indexId).isEmpty()) { redis.del(indexId, indexKey); } } redis.del(sentenceId, sentenceKey); LOGGER.info("Deleted rhyme: {}", sentence); } finally { disconnect(); } } }
RedisStore { public void delete(final String sentence) throws IOException { String word = WordUtils.getLastWord(sentence); if (word.isEmpty()) { return; } String rhyme = normalizeString(wordParser.phoneticRhymePart(word)); StressType type = wordParser.stressType(word); connect(); try { String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence)); if (redis.exists(sentenceKey) == 0) { throw new IOException("The element to remove does not exist."); } String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type)); String sentenceId = redis.get(sentenceKey); sentenceId = sentencens.build(sentenceId).toString(); if (redis.exists(indexKey) == 1) { String indexId = redis.get(indexKey); indexId = indexns.build(indexId).toString(); if (redis.exists(indexId) == 1) { redis.srem(indexId, sentenceId); } if (redis.smembers(indexId).isEmpty()) { redis.del(indexId, indexKey); } } redis.del(sentenceId, sentenceKey); LOGGER.info("Deleted rhyme: {}", sentence); } finally { disconnect(); } } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); }
RedisStore { public void delete(final String sentence) throws IOException { String word = WordUtils.getLastWord(sentence); if (word.isEmpty()) { return; } String rhyme = normalizeString(wordParser.phoneticRhymePart(word)); StressType type = wordParser.stressType(word); connect(); try { String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence)); if (redis.exists(sentenceKey) == 0) { throw new IOException("The element to remove does not exist."); } String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type)); String sentenceId = redis.get(sentenceKey); sentenceId = sentencens.build(sentenceId).toString(); if (redis.exists(indexKey) == 1) { String indexId = redis.get(indexKey); indexId = indexns.build(indexId).toString(); if (redis.exists(indexId) == 1) { redis.srem(indexId, sentenceId); } if (redis.smembers(indexId).isEmpty()) { redis.del(indexId, indexKey); } } redis.del(sentenceId, sentenceKey); LOGGER.info("Deleted rhyme: {}", sentence); } finally { disconnect(); } } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }
RedisStore { public void delete(final String sentence) throws IOException { String word = WordUtils.getLastWord(sentence); if (word.isEmpty()) { return; } String rhyme = normalizeString(wordParser.phoneticRhymePart(word)); StressType type = wordParser.stressType(word); connect(); try { String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence)); if (redis.exists(sentenceKey) == 0) { throw new IOException("The element to remove does not exist."); } String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type)); String sentenceId = redis.get(sentenceKey); sentenceId = sentencens.build(sentenceId).toString(); if (redis.exists(indexKey) == 1) { String indexId = redis.get(indexKey); indexId = indexns.build(indexId).toString(); if (redis.exists(indexId) == 1) { redis.srem(indexId, sentenceId); } if (redis.smembers(indexId).isEmpty()) { redis.del(indexId, indexKey); } } redis.del(sentenceId, sentenceKey); LOGGER.info("Deleted rhyme: {}", sentence); } finally { disconnect(); } } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }
@Test public void testSum() { assertEquals(store.sum("foo"), "acbd18db4cc2f85cedef654fccc4a4d8"); assertEquals(store.sum("bar"), "37b51d194a7513e45b56f6524f2d51f2"); }
@VisibleForTesting String sum(final String value) { return Hashing.md5().hashString(value, encoding).toString(); }
RedisStore { @VisibleForTesting String sum(final String value) { return Hashing.md5().hashString(value, encoding).toString(); } }
RedisStore { @VisibleForTesting String sum(final String value) { return Hashing.md5().hashString(value, encoding).toString(); } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); }
RedisStore { @VisibleForTesting String sum(final String value) { return Hashing.md5().hashString(value, encoding).toString(); } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }
RedisStore { @VisibleForTesting String sum(final String value) { return Hashing.md5().hashString(value, encoding).toString(); } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }
@Test public void testKeymaker() { checkKeymaker(""); checkKeymaker(":"); checkKeymaker("test"); checkKeymaker(":test:"); checkKeymaker("test::"); checkKeymaker("::test"); checkKeymaker("test:test2"); }
public Keymaker(final String namespace) { this.namespace = checkNotNull(namespace, "Namespace cannot be null"); }
Keymaker { public Keymaker(final String namespace) { this.namespace = checkNotNull(namespace, "Namespace cannot be null"); } }
Keymaker { public Keymaker(final String namespace) { this.namespace = checkNotNull(namespace, "Namespace cannot be null"); } Keymaker(final String namespace); }
Keymaker { public Keymaker(final String namespace) { this.namespace = checkNotNull(namespace, "Namespace cannot be null"); } Keymaker(final String namespace); Keymaker build(final String... namespaces); @Override String toString(); }
Keymaker { public Keymaker(final String namespace) { this.namespace = checkNotNull(namespace, "Namespace cannot be null"); } Keymaker(final String namespace); Keymaker build(final String... namespaces); @Override String toString(); }
@Test public void testExecuteWithExistingRhyme() throws TwitterException { ReplyCommand replyCommand = createReplyCommand("Este test es casi perfecto"); replyCommand.execute(); assertTrue(twitter.getLastUpdatedStatus().contains("Rima por defecto")); }
@Override public void execute() throws TwitterException { String rhyme = null; String targetUser = status.getUser().getScreenName(); try { rhyme = rhymeStore.getRhyme(status.getText()); if (rhyme == null) { if (wordParser.isWord(targetUser)) { LOGGER.info("Trying to rhyme with the screen name: {}", targetUser); rhyme = rhymeStore.getRhyme(targetUser); } } if (rhyme == null) { rhyme = wordParser.getDefaultRhyme(); LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme); } } catch (IOException ex) { LOGGER.error( "An error occured while connecting to the rhyme store. Could not reply to {}", targetUser, ex); } try { String tweet = TwitterUtils.reply(targetUser, rhyme); LOGGER.info("Replying to {} with: {}", targetUser, tweet); StatusUpdate newStatus = new StatusUpdate(tweet); newStatus.setInReplyToStatusId(status.getId()); twitter.updateStatus(newStatus); } catch (TwitterException ex) { LOGGER.error("Could not send reply to tweet " + status.getId(), ex); } }
ReplyCommand extends AbstracTwitterCommand { @Override public void execute() throws TwitterException { String rhyme = null; String targetUser = status.getUser().getScreenName(); try { rhyme = rhymeStore.getRhyme(status.getText()); if (rhyme == null) { if (wordParser.isWord(targetUser)) { LOGGER.info("Trying to rhyme with the screen name: {}", targetUser); rhyme = rhymeStore.getRhyme(targetUser); } } if (rhyme == null) { rhyme = wordParser.getDefaultRhyme(); LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme); } } catch (IOException ex) { LOGGER.error( "An error occured while connecting to the rhyme store. Could not reply to {}", targetUser, ex); } try { String tweet = TwitterUtils.reply(targetUser, rhyme); LOGGER.info("Replying to {} with: {}", targetUser, tweet); StatusUpdate newStatus = new StatusUpdate(tweet); newStatus.setInReplyToStatusId(status.getId()); twitter.updateStatus(newStatus); } catch (TwitterException ex) { LOGGER.error("Could not send reply to tweet " + status.getId(), ex); } } }
ReplyCommand extends AbstracTwitterCommand { @Override public void execute() throws TwitterException { String rhyme = null; String targetUser = status.getUser().getScreenName(); try { rhyme = rhymeStore.getRhyme(status.getText()); if (rhyme == null) { if (wordParser.isWord(targetUser)) { LOGGER.info("Trying to rhyme with the screen name: {}", targetUser); rhyme = rhymeStore.getRhyme(targetUser); } } if (rhyme == null) { rhyme = wordParser.getDefaultRhyme(); LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme); } } catch (IOException ex) { LOGGER.error( "An error occured while connecting to the rhyme store. Could not reply to {}", targetUser, ex); } try { String tweet = TwitterUtils.reply(targetUser, rhyme); LOGGER.info("Replying to {} with: {}", targetUser, tweet); StatusUpdate newStatus = new StatusUpdate(tweet); newStatus.setInReplyToStatusId(status.getId()); twitter.updateStatus(newStatus); } catch (TwitterException ex) { LOGGER.error("Could not send reply to tweet " + status.getId(), ex); } } ReplyCommand(final Twitter twitter, final WordParser wordParser, final RedisStore rhymeStore, final Status status); }
ReplyCommand extends AbstracTwitterCommand { @Override public void execute() throws TwitterException { String rhyme = null; String targetUser = status.getUser().getScreenName(); try { rhyme = rhymeStore.getRhyme(status.getText()); if (rhyme == null) { if (wordParser.isWord(targetUser)) { LOGGER.info("Trying to rhyme with the screen name: {}", targetUser); rhyme = rhymeStore.getRhyme(targetUser); } } if (rhyme == null) { rhyme = wordParser.getDefaultRhyme(); LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme); } } catch (IOException ex) { LOGGER.error( "An error occured while connecting to the rhyme store. Could not reply to {}", targetUser, ex); } try { String tweet = TwitterUtils.reply(targetUser, rhyme); LOGGER.info("Replying to {} with: {}", targetUser, tweet); StatusUpdate newStatus = new StatusUpdate(tweet); newStatus.setInReplyToStatusId(status.getId()); twitter.updateStatus(newStatus); } catch (TwitterException ex) { LOGGER.error("Could not send reply to tweet " + status.getId(), ex); } } ReplyCommand(final Twitter twitter, final WordParser wordParser, final RedisStore rhymeStore, final Status status); @Override void execute(); }
ReplyCommand extends AbstracTwitterCommand { @Override public void execute() throws TwitterException { String rhyme = null; String targetUser = status.getUser().getScreenName(); try { rhyme = rhymeStore.getRhyme(status.getText()); if (rhyme == null) { if (wordParser.isWord(targetUser)) { LOGGER.info("Trying to rhyme with the screen name: {}", targetUser); rhyme = rhymeStore.getRhyme(targetUser); } } if (rhyme == null) { rhyme = wordParser.getDefaultRhyme(); LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme); } } catch (IOException ex) { LOGGER.error( "An error occured while connecting to the rhyme store. Could not reply to {}", targetUser, ex); } try { String tweet = TwitterUtils.reply(targetUser, rhyme); LOGGER.info("Replying to {} with: {}", targetUser, tweet); StatusUpdate newStatus = new StatusUpdate(tweet); newStatus.setInReplyToStatusId(status.getId()); twitter.updateStatus(newStatus); } catch (TwitterException ex) { LOGGER.error("Could not send reply to tweet " + status.getId(), ex); } } ReplyCommand(final Twitter twitter, final WordParser wordParser, final RedisStore rhymeStore, final Status status); @Override void execute(); }
@Test public void testExecuteWithScreenNameRhyme() throws TwitterException { ReplyCommand replyCommand = createReplyCommand("Rima esto con el usuario"); replyCommand.execute(); assertTrue(twitter.getLastUpdatedStatus().contains("Esta rima es infame")); }
@Override public void execute() throws TwitterException { String rhyme = null; String targetUser = status.getUser().getScreenName(); try { rhyme = rhymeStore.getRhyme(status.getText()); if (rhyme == null) { if (wordParser.isWord(targetUser)) { LOGGER.info("Trying to rhyme with the screen name: {}", targetUser); rhyme = rhymeStore.getRhyme(targetUser); } } if (rhyme == null) { rhyme = wordParser.getDefaultRhyme(); LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme); } } catch (IOException ex) { LOGGER.error( "An error occured while connecting to the rhyme store. Could not reply to {}", targetUser, ex); } try { String tweet = TwitterUtils.reply(targetUser, rhyme); LOGGER.info("Replying to {} with: {}", targetUser, tweet); StatusUpdate newStatus = new StatusUpdate(tweet); newStatus.setInReplyToStatusId(status.getId()); twitter.updateStatus(newStatus); } catch (TwitterException ex) { LOGGER.error("Could not send reply to tweet " + status.getId(), ex); } }
ReplyCommand extends AbstracTwitterCommand { @Override public void execute() throws TwitterException { String rhyme = null; String targetUser = status.getUser().getScreenName(); try { rhyme = rhymeStore.getRhyme(status.getText()); if (rhyme == null) { if (wordParser.isWord(targetUser)) { LOGGER.info("Trying to rhyme with the screen name: {}", targetUser); rhyme = rhymeStore.getRhyme(targetUser); } } if (rhyme == null) { rhyme = wordParser.getDefaultRhyme(); LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme); } } catch (IOException ex) { LOGGER.error( "An error occured while connecting to the rhyme store. Could not reply to {}", targetUser, ex); } try { String tweet = TwitterUtils.reply(targetUser, rhyme); LOGGER.info("Replying to {} with: {}", targetUser, tweet); StatusUpdate newStatus = new StatusUpdate(tweet); newStatus.setInReplyToStatusId(status.getId()); twitter.updateStatus(newStatus); } catch (TwitterException ex) { LOGGER.error("Could not send reply to tweet " + status.getId(), ex); } } }
ReplyCommand extends AbstracTwitterCommand { @Override public void execute() throws TwitterException { String rhyme = null; String targetUser = status.getUser().getScreenName(); try { rhyme = rhymeStore.getRhyme(status.getText()); if (rhyme == null) { if (wordParser.isWord(targetUser)) { LOGGER.info("Trying to rhyme with the screen name: {}", targetUser); rhyme = rhymeStore.getRhyme(targetUser); } } if (rhyme == null) { rhyme = wordParser.getDefaultRhyme(); LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme); } } catch (IOException ex) { LOGGER.error( "An error occured while connecting to the rhyme store. Could not reply to {}", targetUser, ex); } try { String tweet = TwitterUtils.reply(targetUser, rhyme); LOGGER.info("Replying to {} with: {}", targetUser, tweet); StatusUpdate newStatus = new StatusUpdate(tweet); newStatus.setInReplyToStatusId(status.getId()); twitter.updateStatus(newStatus); } catch (TwitterException ex) { LOGGER.error("Could not send reply to tweet " + status.getId(), ex); } } ReplyCommand(final Twitter twitter, final WordParser wordParser, final RedisStore rhymeStore, final Status status); }
ReplyCommand extends AbstracTwitterCommand { @Override public void execute() throws TwitterException { String rhyme = null; String targetUser = status.getUser().getScreenName(); try { rhyme = rhymeStore.getRhyme(status.getText()); if (rhyme == null) { if (wordParser.isWord(targetUser)) { LOGGER.info("Trying to rhyme with the screen name: {}", targetUser); rhyme = rhymeStore.getRhyme(targetUser); } } if (rhyme == null) { rhyme = wordParser.getDefaultRhyme(); LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme); } } catch (IOException ex) { LOGGER.error( "An error occured while connecting to the rhyme store. Could not reply to {}", targetUser, ex); } try { String tweet = TwitterUtils.reply(targetUser, rhyme); LOGGER.info("Replying to {} with: {}", targetUser, tweet); StatusUpdate newStatus = new StatusUpdate(tweet); newStatus.setInReplyToStatusId(status.getId()); twitter.updateStatus(newStatus); } catch (TwitterException ex) { LOGGER.error("Could not send reply to tweet " + status.getId(), ex); } } ReplyCommand(final Twitter twitter, final WordParser wordParser, final RedisStore rhymeStore, final Status status); @Override void execute(); }
ReplyCommand extends AbstracTwitterCommand { @Override public void execute() throws TwitterException { String rhyme = null; String targetUser = status.getUser().getScreenName(); try { rhyme = rhymeStore.getRhyme(status.getText()); if (rhyme == null) { if (wordParser.isWord(targetUser)) { LOGGER.info("Trying to rhyme with the screen name: {}", targetUser); rhyme = rhymeStore.getRhyme(targetUser); } } if (rhyme == null) { rhyme = wordParser.getDefaultRhyme(); LOGGER.info("No rhyme found. Using default rhyme: {}", rhyme); } } catch (IOException ex) { LOGGER.error( "An error occured while connecting to the rhyme store. Could not reply to {}", targetUser, ex); } try { String tweet = TwitterUtils.reply(targetUser, rhyme); LOGGER.info("Replying to {} with: {}", targetUser, tweet); StatusUpdate newStatus = new StatusUpdate(tweet); newStatus.setInReplyToStatusId(status.getId()); twitter.updateStatus(newStatus); } catch (TwitterException ex) { LOGGER.error("Could not send reply to tweet " + status.getId(), ex); } } ReplyCommand(final Twitter twitter, final WordParser wordParser, final RedisStore rhymeStore, final Status status); @Override void execute(); }
@Test public void testCapitalize() { assertEquals(capitalize(null), null); assertEquals(capitalize(""), ""); assertEquals(capitalize("hola"), "Hola"); assertEquals(capitalize("hOLA"), "HOLA"); }
public static String capitalize(final String str) { if (str == null) { return null; } switch (str.length()) { case 0: return str; case 1: return str.toUpperCase(); default: return str.substring(0, 1).toUpperCase() + str.substring(1); } }
WordUtils { public static String capitalize(final String str) { if (str == null) { return null; } switch (str.length()) { case 0: return str; case 1: return str.toUpperCase(); default: return str.substring(0, 1).toUpperCase() + str.substring(1); } } }
WordUtils { public static String capitalize(final String str) { if (str == null) { return null; } switch (str.length()) { case 0: return str; case 1: return str.toUpperCase(); default: return str.substring(0, 1).toUpperCase() + str.substring(1); } } }
WordUtils { public static String capitalize(final String str) { if (str == null) { return null; } switch (str.length()) { case 0: return str; case 1: return str.toUpperCase(); default: return str.substring(0, 1).toUpperCase() + str.substring(1); } } static String getLastWord(final String sentence); static String capitalize(final String str); static boolean isNumber(String word); }
WordUtils { public static String capitalize(final String str) { if (str == null) { return null; } switch (str.length()) { case 0: return str; case 1: return str.toUpperCase(); default: return str.substring(0, 1).toUpperCase() + str.substring(1); } } static String getLastWord(final String sentence); static String capitalize(final String str); static boolean isNumber(String word); }
@Test public void testGetLastWord() { assertEquals(getLastWord(null), ""); assertEquals(getLastWord(""), ""); assertEquals(getLastWord("hola"), "hola"); assertEquals(getLastWord("hola adios"), "adios"); assertEquals(getLastWord("hola ."), "."); }
public static String getLastWord(final String sentence) { String word = ""; if (sentence != null) { List<String> words = Arrays.asList(sentence.split(" ")); if (words.size() > 0) { word = words.get(words.size() - 1); } } return word; }
WordUtils { public static String getLastWord(final String sentence) { String word = ""; if (sentence != null) { List<String> words = Arrays.asList(sentence.split(" ")); if (words.size() > 0) { word = words.get(words.size() - 1); } } return word; } }
WordUtils { public static String getLastWord(final String sentence) { String word = ""; if (sentence != null) { List<String> words = Arrays.asList(sentence.split(" ")); if (words.size() > 0) { word = words.get(words.size() - 1); } } return word; } }
WordUtils { public static String getLastWord(final String sentence) { String word = ""; if (sentence != null) { List<String> words = Arrays.asList(sentence.split(" ")); if (words.size() > 0) { word = words.get(words.size() - 1); } } return word; } static String getLastWord(final String sentence); static String capitalize(final String str); static boolean isNumber(String word); }
WordUtils { public static String getLastWord(final String sentence) { String word = ""; if (sentence != null) { List<String> words = Arrays.asList(sentence.split(" ")); if (words.size() > 0) { word = words.get(words.size() - 1); } } return word; } static String getLastWord(final String sentence); static String capitalize(final String str); static boolean isNumber(String word); }
@Test public void testIsNumber() { assertFalse(isNumber(null)); assertFalse(isNumber("")); assertFalse(isNumber("a")); assertFalse(isNumber("-a")); assertFalse(isNumber("23a")); assertTrue(isNumber("-1")); assertTrue(isNumber("0")); assertTrue(isNumber("12345")); }
public static boolean isNumber(String word) { if (word == null) { return false; } String wordToParse = new String(word); if (wordToParse.startsWith("-")) { wordToParse = wordToParse.replaceFirst("-", ""); } if (wordToParse.length() == 0) { return false; } for (char c : wordToParse.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; }
WordUtils { public static boolean isNumber(String word) { if (word == null) { return false; } String wordToParse = new String(word); if (wordToParse.startsWith("-")) { wordToParse = wordToParse.replaceFirst("-", ""); } if (wordToParse.length() == 0) { return false; } for (char c : wordToParse.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; } }
WordUtils { public static boolean isNumber(String word) { if (word == null) { return false; } String wordToParse = new String(word); if (wordToParse.startsWith("-")) { wordToParse = wordToParse.replaceFirst("-", ""); } if (wordToParse.length() == 0) { return false; } for (char c : wordToParse.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; } }
WordUtils { public static boolean isNumber(String word) { if (word == null) { return false; } String wordToParse = new String(word); if (wordToParse.startsWith("-")) { wordToParse = wordToParse.replaceFirst("-", ""); } if (wordToParse.length() == 0) { return false; } for (char c : wordToParse.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; } static String getLastWord(final String sentence); static String capitalize(final String str); static boolean isNumber(String word); }
WordUtils { public static boolean isNumber(String word) { if (word == null) { return false; } String wordToParse = new String(word); if (wordToParse.startsWith("-")) { wordToParse = wordToParse.replaceFirst("-", ""); } if (wordToParse.length() == 0) { return false; } for (char c : wordToParse.toCharArray()) { if (!Character.isDigit(c)) { return false; } } return true; } static String getLastWord(final String sentence); static String capitalize(final String str); static boolean isNumber(String word); }
@Test public void testGetConfigValue() { assertNull(getConfigValue("unexisting")); assertEquals(getConfigValue(REDIS_HOST), "localhost"); }
static String getConfigValue(final String propertyName) { return getConfiguration().getProperty(propertyName); }
Configuration { static String getConfigValue(final String propertyName) { return getConfiguration().getProperty(propertyName); } }
Configuration { static String getConfigValue(final String propertyName) { return getConfiguration().getProperty(propertyName); } private Configuration(); }
Configuration { static String getConfigValue(final String propertyName) { return getConfiguration().getProperty(propertyName); } private Configuration(); }
Configuration { static String getConfigValue(final String propertyName) { return getConfiguration().getProperty(propertyName); } private Configuration(); static final String CONFIG_FILE; static final String REDIS_HOST; static final String REDIS_PORT; static final String REDIS_PASSWORD; static final String FALLBACK_RHYMES; static final String DEFAULT_RHYMES; }
@Test public void testGetRequiredConfigValue() { assertEquals(getRequiredConfigValue(REDIS_HOST), "localhost"); }
static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; }
Configuration { static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; } }
Configuration { static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; } private Configuration(); }
Configuration { static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; } private Configuration(); }
Configuration { static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; } private Configuration(); static final String CONFIG_FILE; static final String REDIS_HOST; static final String REDIS_PORT; static final String REDIS_PASSWORD; static final String FALLBACK_RHYMES; static final String DEFAULT_RHYMES; }
@Test(expectedExceptions = ConfigurationException.class) public void testGetUnexistingRequiredConfigValue() { getRequiredConfigValue("unexisting"); }
static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; }
Configuration { static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; } }
Configuration { static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; } private Configuration(); }
Configuration { static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; } private Configuration(); }
Configuration { static String getRequiredConfigValue(final String propertyName) { String value = getConfiguration().getProperty(propertyName); if (value == null) { throw new ConfigurationException("Te requested property [" + propertyName + "] was not set."); } return value; } private Configuration(); static final String CONFIG_FILE; static final String REDIS_HOST; static final String REDIS_PORT; static final String REDIS_PASSWORD; static final String FALLBACK_RHYMES; static final String DEFAULT_RHYMES; }
@Test public void testFindAll() throws IOException { assertEquals(store.findAll().size(), 2); }
public Set<String> findAll() throws IOException { Set<String> rhymes = new HashSet<String>(); connect(); try { String lastId = getLastId(sentencens); if (lastId != null) { Integer n = Integer.parseInt(getLastId(sentencens)); for (int i = 1; i <= n; i++) { String id = sentencens.build(String.valueOf(i)).toString(); if (redis.exists(id) == 1) { rhymes.add(URLDecoder.decode(redis.get(id), encoding.displayName())); } } } } finally { disconnect(); } return rhymes; }
RedisStore { public Set<String> findAll() throws IOException { Set<String> rhymes = new HashSet<String>(); connect(); try { String lastId = getLastId(sentencens); if (lastId != null) { Integer n = Integer.parseInt(getLastId(sentencens)); for (int i = 1; i <= n; i++) { String id = sentencens.build(String.valueOf(i)).toString(); if (redis.exists(id) == 1) { rhymes.add(URLDecoder.decode(redis.get(id), encoding.displayName())); } } } } finally { disconnect(); } return rhymes; } }
RedisStore { public Set<String> findAll() throws IOException { Set<String> rhymes = new HashSet<String>(); connect(); try { String lastId = getLastId(sentencens); if (lastId != null) { Integer n = Integer.parseInt(getLastId(sentencens)); for (int i = 1; i <= n; i++) { String id = sentencens.build(String.valueOf(i)).toString(); if (redis.exists(id) == 1) { rhymes.add(URLDecoder.decode(redis.get(id), encoding.displayName())); } } } } finally { disconnect(); } return rhymes; } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); }
RedisStore { public Set<String> findAll() throws IOException { Set<String> rhymes = new HashSet<String>(); connect(); try { String lastId = getLastId(sentencens); if (lastId != null) { Integer n = Integer.parseInt(getLastId(sentencens)); for (int i = 1; i <= n; i++) { String id = sentencens.build(String.valueOf(i)).toString(); if (redis.exists(id) == 1) { rhymes.add(URLDecoder.decode(redis.get(id), encoding.displayName())); } } } } finally { disconnect(); } return rhymes; } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }
RedisStore { public Set<String> findAll() throws IOException { Set<String> rhymes = new HashSet<String>(); connect(); try { String lastId = getLastId(sentencens); if (lastId != null) { Integer n = Integer.parseInt(getLastId(sentencens)); for (int i = 1; i <= n; i++) { String id = sentencens.build(String.valueOf(i)).toString(); if (redis.exists(id) == 1) { rhymes.add(URLDecoder.decode(redis.get(id), encoding.displayName())); } } } } finally { disconnect(); } return rhymes; } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }
@Test public void testGetRhyme() throws IOException { assertNull(store.getRhyme("no hay rima")); assertEquals(store.getRhyme("¿Hay algo que rime con tres?"), "Me escondo y no me ves"); assertEquals(store.getRhyme("Nada rima con dos"), "Ya son veintidós!!"); }
public String getRhyme(final String sentence) throws IOException { String lastWord = WordUtils.getLastWord(sentence); String rhymepart = wordParser.phoneticRhymePart(lastWord); StressType type = wordParser.stressType(lastWord); LOGGER.debug("Finding rhymes for {}", sentence); Set<String> rhymes = Sets.newHashSet(); connect(); try { rhymes.addAll(search(rhymepart, type)); } finally { disconnect(); } if (rhymes.isEmpty()) { return null; } else { List<String> rhymeList = new ArrayList<String>(rhymes); Random random = new Random(System.currentTimeMillis()); int index = random.nextInt(rhymeList.size()); return rhymeList.get(index); } }
RedisStore { public String getRhyme(final String sentence) throws IOException { String lastWord = WordUtils.getLastWord(sentence); String rhymepart = wordParser.phoneticRhymePart(lastWord); StressType type = wordParser.stressType(lastWord); LOGGER.debug("Finding rhymes for {}", sentence); Set<String> rhymes = Sets.newHashSet(); connect(); try { rhymes.addAll(search(rhymepart, type)); } finally { disconnect(); } if (rhymes.isEmpty()) { return null; } else { List<String> rhymeList = new ArrayList<String>(rhymes); Random random = new Random(System.currentTimeMillis()); int index = random.nextInt(rhymeList.size()); return rhymeList.get(index); } } }
RedisStore { public String getRhyme(final String sentence) throws IOException { String lastWord = WordUtils.getLastWord(sentence); String rhymepart = wordParser.phoneticRhymePart(lastWord); StressType type = wordParser.stressType(lastWord); LOGGER.debug("Finding rhymes for {}", sentence); Set<String> rhymes = Sets.newHashSet(); connect(); try { rhymes.addAll(search(rhymepart, type)); } finally { disconnect(); } if (rhymes.isEmpty()) { return null; } else { List<String> rhymeList = new ArrayList<String>(rhymes); Random random = new Random(System.currentTimeMillis()); int index = random.nextInt(rhymeList.size()); return rhymeList.get(index); } } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); }
RedisStore { public String getRhyme(final String sentence) throws IOException { String lastWord = WordUtils.getLastWord(sentence); String rhymepart = wordParser.phoneticRhymePart(lastWord); StressType type = wordParser.stressType(lastWord); LOGGER.debug("Finding rhymes for {}", sentence); Set<String> rhymes = Sets.newHashSet(); connect(); try { rhymes.addAll(search(rhymepart, type)); } finally { disconnect(); } if (rhymes.isEmpty()) { return null; } else { List<String> rhymeList = new ArrayList<String>(rhymes); Random random = new Random(System.currentTimeMillis()); int index = random.nextInt(rhymeList.size()); return rhymeList.get(index); } } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }
RedisStore { public String getRhyme(final String sentence) throws IOException { String lastWord = WordUtils.getLastWord(sentence); String rhymepart = wordParser.phoneticRhymePart(lastWord); StressType type = wordParser.stressType(lastWord); LOGGER.debug("Finding rhymes for {}", sentence); Set<String> rhymes = Sets.newHashSet(); connect(); try { rhymes.addAll(search(rhymepart, type)); } finally { disconnect(); } if (rhymes.isEmpty()) { return null; } else { List<String> rhymeList = new ArrayList<String>(rhymes); Random random = new Random(System.currentTimeMillis()); int index = random.nextInt(rhymeList.size()); return rhymeList.get(index); } } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }
@Test public void testDeleteWithoutText() throws IOException { store.delete(null); store.delete(""); }
public void delete(final String sentence) throws IOException { String word = WordUtils.getLastWord(sentence); if (word.isEmpty()) { return; } String rhyme = normalizeString(wordParser.phoneticRhymePart(word)); StressType type = wordParser.stressType(word); connect(); try { String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence)); if (redis.exists(sentenceKey) == 0) { throw new IOException("The element to remove does not exist."); } String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type)); String sentenceId = redis.get(sentenceKey); sentenceId = sentencens.build(sentenceId).toString(); if (redis.exists(indexKey) == 1) { String indexId = redis.get(indexKey); indexId = indexns.build(indexId).toString(); if (redis.exists(indexId) == 1) { redis.srem(indexId, sentenceId); } if (redis.smembers(indexId).isEmpty()) { redis.del(indexId, indexKey); } } redis.del(sentenceId, sentenceKey); LOGGER.info("Deleted rhyme: {}", sentence); } finally { disconnect(); } }
RedisStore { public void delete(final String sentence) throws IOException { String word = WordUtils.getLastWord(sentence); if (word.isEmpty()) { return; } String rhyme = normalizeString(wordParser.phoneticRhymePart(word)); StressType type = wordParser.stressType(word); connect(); try { String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence)); if (redis.exists(sentenceKey) == 0) { throw new IOException("The element to remove does not exist."); } String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type)); String sentenceId = redis.get(sentenceKey); sentenceId = sentencens.build(sentenceId).toString(); if (redis.exists(indexKey) == 1) { String indexId = redis.get(indexKey); indexId = indexns.build(indexId).toString(); if (redis.exists(indexId) == 1) { redis.srem(indexId, sentenceId); } if (redis.smembers(indexId).isEmpty()) { redis.del(indexId, indexKey); } } redis.del(sentenceId, sentenceKey); LOGGER.info("Deleted rhyme: {}", sentence); } finally { disconnect(); } } }
RedisStore { public void delete(final String sentence) throws IOException { String word = WordUtils.getLastWord(sentence); if (word.isEmpty()) { return; } String rhyme = normalizeString(wordParser.phoneticRhymePart(word)); StressType type = wordParser.stressType(word); connect(); try { String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence)); if (redis.exists(sentenceKey) == 0) { throw new IOException("The element to remove does not exist."); } String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type)); String sentenceId = redis.get(sentenceKey); sentenceId = sentencens.build(sentenceId).toString(); if (redis.exists(indexKey) == 1) { String indexId = redis.get(indexKey); indexId = indexns.build(indexId).toString(); if (redis.exists(indexId) == 1) { redis.srem(indexId, sentenceId); } if (redis.smembers(indexId).isEmpty()) { redis.del(indexId, indexKey); } } redis.del(sentenceId, sentenceKey); LOGGER.info("Deleted rhyme: {}", sentence); } finally { disconnect(); } } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); }
RedisStore { public void delete(final String sentence) throws IOException { String word = WordUtils.getLastWord(sentence); if (word.isEmpty()) { return; } String rhyme = normalizeString(wordParser.phoneticRhymePart(word)); StressType type = wordParser.stressType(word); connect(); try { String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence)); if (redis.exists(sentenceKey) == 0) { throw new IOException("The element to remove does not exist."); } String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type)); String sentenceId = redis.get(sentenceKey); sentenceId = sentencens.build(sentenceId).toString(); if (redis.exists(indexKey) == 1) { String indexId = redis.get(indexKey); indexId = indexns.build(indexId).toString(); if (redis.exists(indexId) == 1) { redis.srem(indexId, sentenceId); } if (redis.smembers(indexId).isEmpty()) { redis.del(indexId, indexKey); } } redis.del(sentenceId, sentenceKey); LOGGER.info("Deleted rhyme: {}", sentence); } finally { disconnect(); } } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }
RedisStore { public void delete(final String sentence) throws IOException { String word = WordUtils.getLastWord(sentence); if (word.isEmpty()) { return; } String rhyme = normalizeString(wordParser.phoneticRhymePart(word)); StressType type = wordParser.stressType(word); connect(); try { String sentenceKey = getUniqueIdKey(sentencens, normalizeString(sentence)); if (redis.exists(sentenceKey) == 0) { throw new IOException("The element to remove does not exist."); } String indexKey = getUniqueIdKey(indexns, buildUniqueToken(rhyme, type)); String sentenceId = redis.get(sentenceKey); sentenceId = sentencens.build(sentenceId).toString(); if (redis.exists(indexKey) == 1) { String indexId = redis.get(indexKey); indexId = indexns.build(indexId).toString(); if (redis.exists(indexId) == 1) { redis.srem(indexId, sentenceId); } if (redis.smembers(indexId).isEmpty()) { redis.del(indexId, indexKey); } } redis.del(sentenceId, sentenceKey); LOGGER.info("Deleted rhyme: {}", sentence); } finally { disconnect(); } } @Inject RedisStore(@Named("sentence") final Keymaker sentencens, @Named("index") final Keymaker indexns, final WordParser wordParser, final Jedis redis, final @Named(REDIS_PASSWORD) Optional<String> redisPassword, final Charset encoding); void add(final String sentence); void delete(final String sentence); Set<String> findAll(); String getRhyme(final String sentence); }
@Test public void test() { ArrayList<BatchScheduler.ActiveJob> activeJobs = new ArrayList<BatchScheduler.ActiveJob>(); activeJobs.addAll(Arrays.asList(job1,job2,job3,job4,job5,job6,job7,job8,job9,job10)); int numCpusAllocated = 5; int numCpusTotal = 10; double load = 0.4; PartitionStatistics partitionStatistics = new PartitionStatistics(numCpusAllocated, numCpusTotal, load); int userQuotaOde = 2; int userQuotaPde = 2; VCellServerID systemID = relSite; SchedulerDecisions schedulerDecisions = BatchScheduler.schedule(activeJobs, partitionStatistics, userQuotaOde, userQuotaPde, systemID); schedulerDecisions.show(); }
public static SchedulerDecisions schedule(List<ActiveJob> activeJobsAllSites, PartitionStatistics partitionStatistics, int userQuotaOde, int userQuotaPde, VCellServerID systemID) { Hashtable<User, UserQuotaInfo> userQuotaInfoMap = new Hashtable<User, UserQuotaInfo>(); int numPendingJobsAllSites = 0; for (ActiveJob activeJob : activeJobsAllSites) { UserQuotaInfo userQuotaInfo = userQuotaInfoMap.get(activeJob.simulationOwner); if (userQuotaInfo==null) { userQuotaInfo = new UserQuotaInfo(activeJob.simulationOwner); userQuotaInfoMap.put(activeJob.simulationOwner, userQuotaInfo); } if (!activeJob.schedulerStatus.isActive()) { continue; } if (activeJob.schedulerStatus.isWaiting()) { continue; } if (activeJob.schedulerStatus.isDispatched() || activeJob.schedulerStatus.isQueued()) { numPendingJobsAllSites++; } if(activeJob.isPDE) { userQuotaInfo.numPdeRunningJobsAllSites++; } else { userQuotaInfo.numOdeRunningJobsAllSites++; } } SchedulerDecisions schedulerDecisions = new SchedulerDecisions(activeJobsAllSites); ArrayList<ActiveJob> prioritizedJobList = new ArrayList<ActiveJob>(activeJobsAllSites); for (ActiveJob activeJob : activeJobsAllSites) { if (!activeJob.schedulerStatus.isActive()) { schedulerDecisions.setInactive(activeJob); prioritizedJobList.remove(activeJob); continue; } if (!activeJob.schedulerStatus.isWaiting()) { schedulerDecisions.setAlreadyRunningOrQueued(activeJob); prioritizedJobList.remove(activeJob); continue; } } Collections.sort(prioritizedJobList,new Comparator<ActiveJob>(){ @Override public int compare(ActiveJob o1, ActiveJob o2) { UserQuotaInfo userQuotaInfo1 = userQuotaInfoMap.get(o1.simulationOwner); UserQuotaInfo userQuotaInfo2 = userQuotaInfoMap.get(o2.simulationOwner); if (userQuotaInfo1.getNumRunningJobs() != userQuotaInfo2.getNumRunningJobs()){ return Integer.compare(userQuotaInfo1.getNumRunningJobs(), userQuotaInfo2.getNumRunningJobs()); } if (o1.isPDE != o2.isPDE){ if (o1.isPDE){ return 1; }else{ return -1; } } return Long.compare(o1.submitTimestamp, o2.submitTimestamp); } }); int index=0; for (ActiveJob activeJob : prioritizedJobList) { schedulerDecisions.setOrdinal(activeJob, index); index++; } HashSet<User> users = new HashSet<User>(); users.addAll(userQuotaInfoMap.keySet()); for (User user : users){ UserQuotaInfo userQuotaInfo = userQuotaInfoMap.get(user); int numDesiredRunningPDEsAllSites = userQuotaInfo.numPdeRunningJobsAllSites; int numDesiredRunningODEsAllSites = userQuotaInfo.numOdeRunningJobsAllSites; Iterator<ActiveJob> prioritizedJobIter = prioritizedJobList.iterator(); while (prioritizedJobIter.hasNext()){ ActiveJob waitingJob = prioritizedJobIter.next(); if (waitingJob.simulationOwner.equals(user)){ if (waitingJob.isPDE){ if (numDesiredRunningPDEsAllSites < userQuotaPde){ numDesiredRunningPDEsAllSites++; }else{ schedulerDecisions.setHeldUserQuotaPDE(waitingJob); prioritizedJobIter.remove(); } }else{ if (numDesiredRunningODEsAllSites < userQuotaOde){ numDesiredRunningODEsAllSites++; }else{ schedulerDecisions.setHeldUserQuotaODE(waitingJob); prioritizedJobIter.remove(); } } } } } int inUseCPUs = partitionStatistics.numCpusAllocated; int cpusAvailable = Math.max(0, partitionStatistics.numCpusTotal - inUseCPUs); int numJobsSlotsAvailable = Math.max(0, cpusAvailable - numPendingJobsAllSites); for (int i=0;i<prioritizedJobList.size();i++) { ActiveJob nextWaitingJob = prioritizedJobList.get(i); if (i<numJobsSlotsAvailable) { if (nextWaitingJob.serverId.equals(systemID)){ schedulerDecisions.setRunnableThisSite(nextWaitingJob); }else { schedulerDecisions.setRunnableOtherSite(nextWaitingJob); } }else { schedulerDecisions.setHeldClusterResources(nextWaitingJob); } } schedulerDecisions.verify(partitionStatistics); return schedulerDecisions; }
BatchScheduler { public static SchedulerDecisions schedule(List<ActiveJob> activeJobsAllSites, PartitionStatistics partitionStatistics, int userQuotaOde, int userQuotaPde, VCellServerID systemID) { Hashtable<User, UserQuotaInfo> userQuotaInfoMap = new Hashtable<User, UserQuotaInfo>(); int numPendingJobsAllSites = 0; for (ActiveJob activeJob : activeJobsAllSites) { UserQuotaInfo userQuotaInfo = userQuotaInfoMap.get(activeJob.simulationOwner); if (userQuotaInfo==null) { userQuotaInfo = new UserQuotaInfo(activeJob.simulationOwner); userQuotaInfoMap.put(activeJob.simulationOwner, userQuotaInfo); } if (!activeJob.schedulerStatus.isActive()) { continue; } if (activeJob.schedulerStatus.isWaiting()) { continue; } if (activeJob.schedulerStatus.isDispatched() || activeJob.schedulerStatus.isQueued()) { numPendingJobsAllSites++; } if(activeJob.isPDE) { userQuotaInfo.numPdeRunningJobsAllSites++; } else { userQuotaInfo.numOdeRunningJobsAllSites++; } } SchedulerDecisions schedulerDecisions = new SchedulerDecisions(activeJobsAllSites); ArrayList<ActiveJob> prioritizedJobList = new ArrayList<ActiveJob>(activeJobsAllSites); for (ActiveJob activeJob : activeJobsAllSites) { if (!activeJob.schedulerStatus.isActive()) { schedulerDecisions.setInactive(activeJob); prioritizedJobList.remove(activeJob); continue; } if (!activeJob.schedulerStatus.isWaiting()) { schedulerDecisions.setAlreadyRunningOrQueued(activeJob); prioritizedJobList.remove(activeJob); continue; } } Collections.sort(prioritizedJobList,new Comparator<ActiveJob>(){ @Override public int compare(ActiveJob o1, ActiveJob o2) { UserQuotaInfo userQuotaInfo1 = userQuotaInfoMap.get(o1.simulationOwner); UserQuotaInfo userQuotaInfo2 = userQuotaInfoMap.get(o2.simulationOwner); if (userQuotaInfo1.getNumRunningJobs() != userQuotaInfo2.getNumRunningJobs()){ return Integer.compare(userQuotaInfo1.getNumRunningJobs(), userQuotaInfo2.getNumRunningJobs()); } if (o1.isPDE != o2.isPDE){ if (o1.isPDE){ return 1; }else{ return -1; } } return Long.compare(o1.submitTimestamp, o2.submitTimestamp); } }); int index=0; for (ActiveJob activeJob : prioritizedJobList) { schedulerDecisions.setOrdinal(activeJob, index); index++; } HashSet<User> users = new HashSet<User>(); users.addAll(userQuotaInfoMap.keySet()); for (User user : users){ UserQuotaInfo userQuotaInfo = userQuotaInfoMap.get(user); int numDesiredRunningPDEsAllSites = userQuotaInfo.numPdeRunningJobsAllSites; int numDesiredRunningODEsAllSites = userQuotaInfo.numOdeRunningJobsAllSites; Iterator<ActiveJob> prioritizedJobIter = prioritizedJobList.iterator(); while (prioritizedJobIter.hasNext()){ ActiveJob waitingJob = prioritizedJobIter.next(); if (waitingJob.simulationOwner.equals(user)){ if (waitingJob.isPDE){ if (numDesiredRunningPDEsAllSites < userQuotaPde){ numDesiredRunningPDEsAllSites++; }else{ schedulerDecisions.setHeldUserQuotaPDE(waitingJob); prioritizedJobIter.remove(); } }else{ if (numDesiredRunningODEsAllSites < userQuotaOde){ numDesiredRunningODEsAllSites++; }else{ schedulerDecisions.setHeldUserQuotaODE(waitingJob); prioritizedJobIter.remove(); } } } } } int inUseCPUs = partitionStatistics.numCpusAllocated; int cpusAvailable = Math.max(0, partitionStatistics.numCpusTotal - inUseCPUs); int numJobsSlotsAvailable = Math.max(0, cpusAvailable - numPendingJobsAllSites); for (int i=0;i<prioritizedJobList.size();i++) { ActiveJob nextWaitingJob = prioritizedJobList.get(i); if (i<numJobsSlotsAvailable) { if (nextWaitingJob.serverId.equals(systemID)){ schedulerDecisions.setRunnableThisSite(nextWaitingJob); }else { schedulerDecisions.setRunnableOtherSite(nextWaitingJob); } }else { schedulerDecisions.setHeldClusterResources(nextWaitingJob); } } schedulerDecisions.verify(partitionStatistics); return schedulerDecisions; } }
BatchScheduler { public static SchedulerDecisions schedule(List<ActiveJob> activeJobsAllSites, PartitionStatistics partitionStatistics, int userQuotaOde, int userQuotaPde, VCellServerID systemID) { Hashtable<User, UserQuotaInfo> userQuotaInfoMap = new Hashtable<User, UserQuotaInfo>(); int numPendingJobsAllSites = 0; for (ActiveJob activeJob : activeJobsAllSites) { UserQuotaInfo userQuotaInfo = userQuotaInfoMap.get(activeJob.simulationOwner); if (userQuotaInfo==null) { userQuotaInfo = new UserQuotaInfo(activeJob.simulationOwner); userQuotaInfoMap.put(activeJob.simulationOwner, userQuotaInfo); } if (!activeJob.schedulerStatus.isActive()) { continue; } if (activeJob.schedulerStatus.isWaiting()) { continue; } if (activeJob.schedulerStatus.isDispatched() || activeJob.schedulerStatus.isQueued()) { numPendingJobsAllSites++; } if(activeJob.isPDE) { userQuotaInfo.numPdeRunningJobsAllSites++; } else { userQuotaInfo.numOdeRunningJobsAllSites++; } } SchedulerDecisions schedulerDecisions = new SchedulerDecisions(activeJobsAllSites); ArrayList<ActiveJob> prioritizedJobList = new ArrayList<ActiveJob>(activeJobsAllSites); for (ActiveJob activeJob : activeJobsAllSites) { if (!activeJob.schedulerStatus.isActive()) { schedulerDecisions.setInactive(activeJob); prioritizedJobList.remove(activeJob); continue; } if (!activeJob.schedulerStatus.isWaiting()) { schedulerDecisions.setAlreadyRunningOrQueued(activeJob); prioritizedJobList.remove(activeJob); continue; } } Collections.sort(prioritizedJobList,new Comparator<ActiveJob>(){ @Override public int compare(ActiveJob o1, ActiveJob o2) { UserQuotaInfo userQuotaInfo1 = userQuotaInfoMap.get(o1.simulationOwner); UserQuotaInfo userQuotaInfo2 = userQuotaInfoMap.get(o2.simulationOwner); if (userQuotaInfo1.getNumRunningJobs() != userQuotaInfo2.getNumRunningJobs()){ return Integer.compare(userQuotaInfo1.getNumRunningJobs(), userQuotaInfo2.getNumRunningJobs()); } if (o1.isPDE != o2.isPDE){ if (o1.isPDE){ return 1; }else{ return -1; } } return Long.compare(o1.submitTimestamp, o2.submitTimestamp); } }); int index=0; for (ActiveJob activeJob : prioritizedJobList) { schedulerDecisions.setOrdinal(activeJob, index); index++; } HashSet<User> users = new HashSet<User>(); users.addAll(userQuotaInfoMap.keySet()); for (User user : users){ UserQuotaInfo userQuotaInfo = userQuotaInfoMap.get(user); int numDesiredRunningPDEsAllSites = userQuotaInfo.numPdeRunningJobsAllSites; int numDesiredRunningODEsAllSites = userQuotaInfo.numOdeRunningJobsAllSites; Iterator<ActiveJob> prioritizedJobIter = prioritizedJobList.iterator(); while (prioritizedJobIter.hasNext()){ ActiveJob waitingJob = prioritizedJobIter.next(); if (waitingJob.simulationOwner.equals(user)){ if (waitingJob.isPDE){ if (numDesiredRunningPDEsAllSites < userQuotaPde){ numDesiredRunningPDEsAllSites++; }else{ schedulerDecisions.setHeldUserQuotaPDE(waitingJob); prioritizedJobIter.remove(); } }else{ if (numDesiredRunningODEsAllSites < userQuotaOde){ numDesiredRunningODEsAllSites++; }else{ schedulerDecisions.setHeldUserQuotaODE(waitingJob); prioritizedJobIter.remove(); } } } } } int inUseCPUs = partitionStatistics.numCpusAllocated; int cpusAvailable = Math.max(0, partitionStatistics.numCpusTotal - inUseCPUs); int numJobsSlotsAvailable = Math.max(0, cpusAvailable - numPendingJobsAllSites); for (int i=0;i<prioritizedJobList.size();i++) { ActiveJob nextWaitingJob = prioritizedJobList.get(i); if (i<numJobsSlotsAvailable) { if (nextWaitingJob.serverId.equals(systemID)){ schedulerDecisions.setRunnableThisSite(nextWaitingJob); }else { schedulerDecisions.setRunnableOtherSite(nextWaitingJob); } }else { schedulerDecisions.setHeldClusterResources(nextWaitingJob); } } schedulerDecisions.verify(partitionStatistics); return schedulerDecisions; } BatchScheduler(); }
BatchScheduler { public static SchedulerDecisions schedule(List<ActiveJob> activeJobsAllSites, PartitionStatistics partitionStatistics, int userQuotaOde, int userQuotaPde, VCellServerID systemID) { Hashtable<User, UserQuotaInfo> userQuotaInfoMap = new Hashtable<User, UserQuotaInfo>(); int numPendingJobsAllSites = 0; for (ActiveJob activeJob : activeJobsAllSites) { UserQuotaInfo userQuotaInfo = userQuotaInfoMap.get(activeJob.simulationOwner); if (userQuotaInfo==null) { userQuotaInfo = new UserQuotaInfo(activeJob.simulationOwner); userQuotaInfoMap.put(activeJob.simulationOwner, userQuotaInfo); } if (!activeJob.schedulerStatus.isActive()) { continue; } if (activeJob.schedulerStatus.isWaiting()) { continue; } if (activeJob.schedulerStatus.isDispatched() || activeJob.schedulerStatus.isQueued()) { numPendingJobsAllSites++; } if(activeJob.isPDE) { userQuotaInfo.numPdeRunningJobsAllSites++; } else { userQuotaInfo.numOdeRunningJobsAllSites++; } } SchedulerDecisions schedulerDecisions = new SchedulerDecisions(activeJobsAllSites); ArrayList<ActiveJob> prioritizedJobList = new ArrayList<ActiveJob>(activeJobsAllSites); for (ActiveJob activeJob : activeJobsAllSites) { if (!activeJob.schedulerStatus.isActive()) { schedulerDecisions.setInactive(activeJob); prioritizedJobList.remove(activeJob); continue; } if (!activeJob.schedulerStatus.isWaiting()) { schedulerDecisions.setAlreadyRunningOrQueued(activeJob); prioritizedJobList.remove(activeJob); continue; } } Collections.sort(prioritizedJobList,new Comparator<ActiveJob>(){ @Override public int compare(ActiveJob o1, ActiveJob o2) { UserQuotaInfo userQuotaInfo1 = userQuotaInfoMap.get(o1.simulationOwner); UserQuotaInfo userQuotaInfo2 = userQuotaInfoMap.get(o2.simulationOwner); if (userQuotaInfo1.getNumRunningJobs() != userQuotaInfo2.getNumRunningJobs()){ return Integer.compare(userQuotaInfo1.getNumRunningJobs(), userQuotaInfo2.getNumRunningJobs()); } if (o1.isPDE != o2.isPDE){ if (o1.isPDE){ return 1; }else{ return -1; } } return Long.compare(o1.submitTimestamp, o2.submitTimestamp); } }); int index=0; for (ActiveJob activeJob : prioritizedJobList) { schedulerDecisions.setOrdinal(activeJob, index); index++; } HashSet<User> users = new HashSet<User>(); users.addAll(userQuotaInfoMap.keySet()); for (User user : users){ UserQuotaInfo userQuotaInfo = userQuotaInfoMap.get(user); int numDesiredRunningPDEsAllSites = userQuotaInfo.numPdeRunningJobsAllSites; int numDesiredRunningODEsAllSites = userQuotaInfo.numOdeRunningJobsAllSites; Iterator<ActiveJob> prioritizedJobIter = prioritizedJobList.iterator(); while (prioritizedJobIter.hasNext()){ ActiveJob waitingJob = prioritizedJobIter.next(); if (waitingJob.simulationOwner.equals(user)){ if (waitingJob.isPDE){ if (numDesiredRunningPDEsAllSites < userQuotaPde){ numDesiredRunningPDEsAllSites++; }else{ schedulerDecisions.setHeldUserQuotaPDE(waitingJob); prioritizedJobIter.remove(); } }else{ if (numDesiredRunningODEsAllSites < userQuotaOde){ numDesiredRunningODEsAllSites++; }else{ schedulerDecisions.setHeldUserQuotaODE(waitingJob); prioritizedJobIter.remove(); } } } } } int inUseCPUs = partitionStatistics.numCpusAllocated; int cpusAvailable = Math.max(0, partitionStatistics.numCpusTotal - inUseCPUs); int numJobsSlotsAvailable = Math.max(0, cpusAvailable - numPendingJobsAllSites); for (int i=0;i<prioritizedJobList.size();i++) { ActiveJob nextWaitingJob = prioritizedJobList.get(i); if (i<numJobsSlotsAvailable) { if (nextWaitingJob.serverId.equals(systemID)){ schedulerDecisions.setRunnableThisSite(nextWaitingJob); }else { schedulerDecisions.setRunnableOtherSite(nextWaitingJob); } }else { schedulerDecisions.setHeldClusterResources(nextWaitingJob); } } schedulerDecisions.verify(partitionStatistics); return schedulerDecisions; } BatchScheduler(); static final int getMaxOdeJobsPerUser(); static final int getMaxPdeJobsPerUser(); static SchedulerDecisions schedule(List<ActiveJob> activeJobsAllSites, PartitionStatistics partitionStatistics, int userQuotaOde, int userQuotaPde, VCellServerID systemID); }
BatchScheduler { public static SchedulerDecisions schedule(List<ActiveJob> activeJobsAllSites, PartitionStatistics partitionStatistics, int userQuotaOde, int userQuotaPde, VCellServerID systemID) { Hashtable<User, UserQuotaInfo> userQuotaInfoMap = new Hashtable<User, UserQuotaInfo>(); int numPendingJobsAllSites = 0; for (ActiveJob activeJob : activeJobsAllSites) { UserQuotaInfo userQuotaInfo = userQuotaInfoMap.get(activeJob.simulationOwner); if (userQuotaInfo==null) { userQuotaInfo = new UserQuotaInfo(activeJob.simulationOwner); userQuotaInfoMap.put(activeJob.simulationOwner, userQuotaInfo); } if (!activeJob.schedulerStatus.isActive()) { continue; } if (activeJob.schedulerStatus.isWaiting()) { continue; } if (activeJob.schedulerStatus.isDispatched() || activeJob.schedulerStatus.isQueued()) { numPendingJobsAllSites++; } if(activeJob.isPDE) { userQuotaInfo.numPdeRunningJobsAllSites++; } else { userQuotaInfo.numOdeRunningJobsAllSites++; } } SchedulerDecisions schedulerDecisions = new SchedulerDecisions(activeJobsAllSites); ArrayList<ActiveJob> prioritizedJobList = new ArrayList<ActiveJob>(activeJobsAllSites); for (ActiveJob activeJob : activeJobsAllSites) { if (!activeJob.schedulerStatus.isActive()) { schedulerDecisions.setInactive(activeJob); prioritizedJobList.remove(activeJob); continue; } if (!activeJob.schedulerStatus.isWaiting()) { schedulerDecisions.setAlreadyRunningOrQueued(activeJob); prioritizedJobList.remove(activeJob); continue; } } Collections.sort(prioritizedJobList,new Comparator<ActiveJob>(){ @Override public int compare(ActiveJob o1, ActiveJob o2) { UserQuotaInfo userQuotaInfo1 = userQuotaInfoMap.get(o1.simulationOwner); UserQuotaInfo userQuotaInfo2 = userQuotaInfoMap.get(o2.simulationOwner); if (userQuotaInfo1.getNumRunningJobs() != userQuotaInfo2.getNumRunningJobs()){ return Integer.compare(userQuotaInfo1.getNumRunningJobs(), userQuotaInfo2.getNumRunningJobs()); } if (o1.isPDE != o2.isPDE){ if (o1.isPDE){ return 1; }else{ return -1; } } return Long.compare(o1.submitTimestamp, o2.submitTimestamp); } }); int index=0; for (ActiveJob activeJob : prioritizedJobList) { schedulerDecisions.setOrdinal(activeJob, index); index++; } HashSet<User> users = new HashSet<User>(); users.addAll(userQuotaInfoMap.keySet()); for (User user : users){ UserQuotaInfo userQuotaInfo = userQuotaInfoMap.get(user); int numDesiredRunningPDEsAllSites = userQuotaInfo.numPdeRunningJobsAllSites; int numDesiredRunningODEsAllSites = userQuotaInfo.numOdeRunningJobsAllSites; Iterator<ActiveJob> prioritizedJobIter = prioritizedJobList.iterator(); while (prioritizedJobIter.hasNext()){ ActiveJob waitingJob = prioritizedJobIter.next(); if (waitingJob.simulationOwner.equals(user)){ if (waitingJob.isPDE){ if (numDesiredRunningPDEsAllSites < userQuotaPde){ numDesiredRunningPDEsAllSites++; }else{ schedulerDecisions.setHeldUserQuotaPDE(waitingJob); prioritizedJobIter.remove(); } }else{ if (numDesiredRunningODEsAllSites < userQuotaOde){ numDesiredRunningODEsAllSites++; }else{ schedulerDecisions.setHeldUserQuotaODE(waitingJob); prioritizedJobIter.remove(); } } } } } int inUseCPUs = partitionStatistics.numCpusAllocated; int cpusAvailable = Math.max(0, partitionStatistics.numCpusTotal - inUseCPUs); int numJobsSlotsAvailable = Math.max(0, cpusAvailable - numPendingJobsAllSites); for (int i=0;i<prioritizedJobList.size();i++) { ActiveJob nextWaitingJob = prioritizedJobList.get(i); if (i<numJobsSlotsAvailable) { if (nextWaitingJob.serverId.equals(systemID)){ schedulerDecisions.setRunnableThisSite(nextWaitingJob); }else { schedulerDecisions.setRunnableOtherSite(nextWaitingJob); } }else { schedulerDecisions.setHeldClusterResources(nextWaitingJob); } } schedulerDecisions.verify(partitionStatistics); return schedulerDecisions; } BatchScheduler(); static final int getMaxOdeJobsPerUser(); static final int getMaxPdeJobsPerUser(); static SchedulerDecisions schedule(List<ActiveJob> activeJobsAllSites, PartitionStatistics partitionStatistics, int userQuotaOde, int userQuotaPde, VCellServerID systemID); }
@Test public void validateIndexes( ) { boolean punched[] = new boolean[index.getXYZ()]; for (int x = 0; x < mX; x++) for (int y = 0; y < mY; y++) for (int z = 0; z < mZ; z++) { final int idx = index.rollup(x,y,z); assertFalse(punched[idx]); punched[idx] = true; } for (int p = 0; p < punched.length; ++p) { assertTrue(punched[p]); } }
public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); int rollup(int xValue, int yValue, int zValue); }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); int rollup(int xValue, int yValue, int zValue); }
@Test(expected = RuntimeException.class) public void badX( ) { index.rollup(mX, 0,0); }
public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); int rollup(int xValue, int yValue, int zValue); }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); int rollup(int xValue, int yValue, int zValue); }
@Test(expected = RuntimeException.class) public void badY( ) { index.rollup(0, mY,0); }
public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); int rollup(int xValue, int yValue, int zValue); }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); int rollup(int xValue, int yValue, int zValue); }
@Test(expected = RuntimeException.class) public void badZ( ) { index.rollup(0,0,mZ); }
public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); int rollup(int xValue, int yValue, int zValue); }
DimensionalIndex extends ISize { public int rollup(int xValue, int yValue, int zValue) { check(xValue,super.getX(),'x'); check(yValue,super.getY(),'y'); check(zValue,super.getZ(),'z'); return xValue + yValue * getX( ) + zValue * xy; } DimensionalIndex(int newX, int newY, int newZ); DimensionalIndex(String newX, String newY, String newZ); DimensionalIndex(ISize source); int rollup(int xValue, int yValue, int zValue); }