src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
QueryBuilderFactoryImpl implements QueryBuilderFactory { public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType ) { NotQueryableException.throwIfNotQueryable( resultType ); final ServiceReference<EntityFinder> serviceReference; try { serviceReference = finder.findService( EntityFinder.class ); return new...
@Test public void givenPlainQueryWhenFindEntityExpectFirstEntityReturned() { Query<TestComposite> query = module.newQueryBuilder( TestComposite.class ).newQuery( composites ); assertEquals( "A", query.find().a().get() ); assertEquals( 6, query.count() ); } @Test public void givenPlainQueryWhenOrderByFirstPropertyExpect...
ValueBuilderTemplate { public T newInstance(Module module) { ValueBuilder<T> builder = module.newValueBuilder( type ); build( builder.prototype() ); return builder.newInstance(); } protected ValueBuilderTemplate( Class<T> type ); T newInstance(Module module); }
@Test public void testTemplate() { new TestBuilder( "Rickard" ).newInstance( module); } @Test public void testAnonymousTemplate() { new ValueBuilderTemplate<TestValue>(TestValue.class) { @Override protected void build( TestValue prototype ) { prototype.name().set( "Rickard" ); } }.newInstance( module ); }
Classes { public static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ) { Set<Class<?>> newSet = new LinkedHashSet<Class<?>>(); for( Class type : interfaces ) { if( type.isInterface() && type.getDeclaredMethods().length > 0 ) { newSet.add( type ); } } return newSet; } static Specification<Class<?>> isA...
@Test public void givenClassWithInterfacesWhenGetInterfacesWithMethodsThenGetCorrectSet() { HashSet<Class<?>> interfaces = new HashSet<Class<?>>(); interfaces.add( B.class ); Set<Class<?>> types = interfacesWithMethods( interfaces ); assertThat( "one interface returned", types.size(), equalTo( 1 ) ); assertThat( "corre...
Classes { public static String toURI( final Class clazz ) throws NullPointerException { return toURI( clazz.getName() ); } static Specification<Class<?>> isAssignableFrom( final Class clazz); static Specification<Object> instanceOf( final Class clazz); static Specification<Class<?>> hasModifier( final int classModifie...
@Test public void givenClassNameWhenToUriThenUriIsReturned() { assertThat( "URI is correct", Classes.toURI( A.class ), equalTo( "urn:qi4j:type:org.qi4j.api.util.ClassesTest-A" ) ); }
Classes { public static String toClassName( String uri ) throws NullPointerException { uri = uri.substring( "urn:qi4j:type:".length() ); uri = denormalizeURIToClass( uri ); return uri; } static Specification<Class<?>> isAssignableFrom( final Class clazz); static Specification<Object> instanceOf( final Class clazz); st...
@Test public void givenUriWhenToClassNameThenClassNameIsReturned() { assertThat( "Class name is correct", Classes.toClassName( "urn:qi4j:type:org.qi4j.api.util.ClassesTest-A" ), equalTo( "org.qi4j.api.util.ClassesTest$A" ) ); }
Classes { public static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ) { Type type = resolveTypeVariable( name, declaringClass, new HashMap<TypeVariable, Type>(), topClass ); if( type == null ) { type = Object.class; } return type; } static Specification<Class<?>> isAssignableFrom(...
@Test public void givenTypeVariableWhenResolveThenResolved() { for( Method method : Type1.class.getMethods() ) { Type type = method.getGenericReturnType(); TypeVariable typeVariable = (TypeVariable) type; Type resolvedType = Classes.resolveTypeVariable( typeVariable, method.getDeclaringClass(), Type1.class ); System.ou...
UnitOfWorkTemplate { public RESULT withModule(Module module) throws ThrowableType, UnitOfWorkCompletionException { int loop = 0; ThrowableType ex = null; do { UnitOfWork uow = module.newUnitOfWork( usecase ); try { RESULT result = withUnitOfWork( uow ); if (complete) { try { uow.complete(); return result; } catch( Conc...
@Test public void testTemplate() throws UnitOfWorkCompletionException { new UnitOfWorkTemplate<Void, RuntimeException>() { @Override protected Void withUnitOfWork( UnitOfWork uow ) throws RuntimeException { new EntityBuilderTemplate<TestEntity>(TestEntity.class) { @Override protected void build( TestEntity prototype ) ...
PropertyMapper { private static Object mapToType( Type propertyType, Object value ) { final String stringValue = value.toString(); MappingStrategy strategy; if( propertyType instanceof Class ) { Class type = (Class) propertyType; if( type.isArray() ) { strategy = STRATEGY.get( Array.class ); } else if( Enum.class.isAss...
@Test public void testMappingOfInteger() throws Exception { assertEquals( 5, mapToType( Integer.class, "5" ) ); assertEquals( -5, mapToType( Integer.class, "-5" ) ); assertEquals( Integer.class, mapToType( Integer.class, "5" ).getClass() ); } @Test public void testMappingOfLong() throws Exception { assertEquals( 5L, ma...
QualifiedName implements Comparable<QualifiedName>, Serializable { public String type() { return typeName.normalized(); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromNam...
@Test public void testQualifiedNameWithDollar() { assertEquals( "Name containing dollar is modified", "Test-Test", new QualifiedName( TypeName.nameOf( "Test$Test" ), "satisfiedBy" ).type() ); }
QualifiedName implements Comparable<QualifiedName>, Serializable { public static QualifiedName fromQN( String qualifiedName ) { NullArgumentException.validateNotEmpty( "qualifiedName", qualifiedName ); int idx = qualifiedName.lastIndexOf( ":" ); if( idx == -1 ) { throw new IllegalArgumentException( "Name '" + qualified...
@Test( expected = NullArgumentException.class ) public void nonNullArguments4() { QualifiedName.fromQN( null ); }
QualifiedName implements Comparable<QualifiedName>, Serializable { public static QualifiedName fromAccessor( AccessibleObject method ) { NullArgumentException.validateNotNull( "method", method ); return fromClass( ((Member)method).getDeclaringClass(), ((Member)method).getName() ); } QualifiedName( TypeName typeName, St...
@Test( expected = NullArgumentException.class ) public void nonNullArguments5() { QualifiedName.fromAccessor( null ); }
QualifiedName implements Comparable<QualifiedName>, Serializable { public static QualifiedName fromClass( Class type, String name ) { return new QualifiedName( TypeName.nameOf( type ), name ); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static Qualifi...
@Test( expected = NullArgumentException.class ) public void nonNullArguments6() { QualifiedName.fromClass( null, "satisfiedBy" ); } @Test( expected = NullArgumentException.class ) public void nonNullArguments7() { QualifiedName.fromClass( null, null ); }
ClassScanner { public static Iterable<Class<?>> getClasses( final Class<?> seedClass ) { CodeSource codeSource = seedClass.getProtectionDomain().getCodeSource(); if( codeSource == null ) { return Iterables.empty(); } URL location = codeSource.getLocation(); if( !location.getProtocol().equals( "file" ) ) { throw new Ill...
@Test public void testClassScannerJar() { Assert.assertEquals( 121, Iterables.count( getClasses( Test.class ) )); }
Iterables { public static <T> Iterable<T> constant( final T item ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { @Override public boolean hasNext() { return true; } @Override public T next() { return item; } @Override public void remove() { } }; } }; } static Iterabl...
@Test public void testConstant() { String str = ""; for( String string : Iterables.limit( 3, Iterables.constant( "123" ) ) ) { str += string; } assertThat( str, CoreMatchers.equalTo( "123123123" ) ); }
Iterables { public static <T> Iterable<T> unique( final Iterable<T> iterable) { return new Iterable<T>() { @Override public Iterator<T> iterator() { final Iterator<T> iterator = iterable.iterator(); return new Iterator<T>() { Set<T> items = new HashSet<T>(); T nextItem; @Override public boolean hasNext() { while(iterat...
@Test public void testUnique() { String str = ""; for( String string : Iterables.unique( Iterables.flatten( numbers, numbers, numbers ) )) { str += string; } assertThat( str, CoreMatchers.equalTo( "123" ) ); }
Iterables { public static <T, C extends Collection<T>> C addAll( C collection, Iterable<? extends T> iterable ) { for( T item : iterable ) { collection.add( item ); } return collection; } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iter...
@Test public void testAddAll() { List<String> strings = Iterables.toList( numbers ); assertThat( strings.toString(), equalTo( "[1, 2, 3]" ) ); assertThat( Iterables.toList( numberLongs ).toString(), equalTo( "[1, 2, 3]" ) ); }
Iterables { public static long count( Iterable<?> iterable ) { long c = 0; Iterator<?> iterator = iterable.iterator(); while( iterator.hasNext() ) { iterator.next(); c++; } return c; } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iterabl...
@Test public void testCount() { assertThat( Iterables.count( numbers ), equalTo( 3L ) ); }
Iterables { public static <X> Iterable<X> filter( Specification<? super X> specification, Iterable<X> i ) { return new FilterIterable<X>( i, specification ); } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iterable<T> iterable ); static I...
@Test public void testFilter() { assertThat( Iterables.first( Iterables.filter( Specifications.in( "2" ), numbers ) ), equalTo( "2" ) ); }
Iterables { public static <X> X first( Iterable<? extends X> i ) { Iterator<? extends X> iter = i.iterator(); if( iter.hasNext() ) { return iter.next(); } else { return null; } } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iterable<T> i...
@Test public void testFirst() { assertThat( Iterables.first( numbers ), equalTo( "1" ) ); assertThat( Iterables.first( Collections.<Object>emptyList() ), CoreMatchers.<Object>nullValue() ); }
Iterables { public static <X> X last( Iterable<? extends X> i ) { Iterator<? extends X> iter = i.iterator(); X item = null; while( iter.hasNext() ) item = iter.next(); return item; } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iterable<...
@Test public void testLast() { assertThat( Iterables.last( numbers ), equalTo( "3" ) ); assertThat( Iterables.last( Collections.<Object>emptyList() ), CoreMatchers.<Object>nullValue() ); }
Iterables { public static <FROM, TO> TO fold( Function<? super FROM, TO> function, Iterable<? extends FROM> i ) { return last( map( function, i ) ); } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iterable<T> iterable ); static Iterable<T...
@Test public void testFolding() { assertThat( Iterables.fold( new Function<Integer, Integer>() { int sum = 0; @Override public Integer map( Integer number ) { return sum += number; } }, numberIntegers ), equalTo( 6 ) ); }
Iterables { public static <T, C extends T> Iterable<T> append( final C item, final Iterable<T> iterable ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { final Iterator<T> iterator = iterable.iterator(); return new Iterator<T>() { T last = item; @Override public boolean hasNext() { if(iterator.ha...
@Test public void testAppend() { assertThat( Iterables.toList(Iterables.append( "C", Iterables.iterable( "A","B" ) )).toString(), equalTo( "[A, B, C]" ) ); }
Iterables { public static <X> Iterable<X> reverse( Iterable<X> iterable ) { List<X> list = toList( iterable ); Collections.reverse( list ); return list; } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iterable<T> iterable ); static Iterab...
@Test public void testReverse() { assertThat( Iterables.reverse( numbers ).toString(), equalTo( "[3, 2, 1]" ) ); assertThat( Iterables.reverse( Collections.<Object>emptyList() ), equalTo( (Object) Collections.<Object>emptyList() ) ); }
Iterables { public static <T> boolean matchesAny( Specification<? super T> specification, Iterable<T> iterable ) { boolean result = false; for( T item : iterable ) { if( specification.satisfiedBy( item ) ) { result = true; break; } } return result; } static Iterable<T> empty(); static Iterable<T> constant( final T ite...
@Test public void testMatchesAny() { assertThat( Iterables.matchesAny( Specifications.in( "2" ), numbers ), equalTo( true ) ); assertThat( Iterables.matchesAny( Specifications.in( "4" ), numbers ), equalTo( false ) ); }
Iterables { public static <T> boolean matchesAll( Specification<? super T> specification, Iterable<T> iterable ) { boolean result = true; for( T item : iterable ) { if( !specification.satisfiedBy( item ) ) { result = false; } } return result; } static Iterable<T> empty(); static Iterable<T> constant( final T item ); s...
@Test public void testMatchesAll() { assertThat( Iterables.matchesAll( Specifications.in( "1", "2", "3" ), numbers ), equalTo( true ) ); assertThat( Iterables.matchesAll( Specifications.in( "2", "3", "4" ), numbers ), equalTo( false ) ); }
Iterables { public static <X, I extends Iterable<? extends X>> Iterable<X> flatten( I... multiIterator ) { return new FlattenIterable<X, I>( Arrays.asList( multiIterator ) ); } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iterable<T> ite...
@Test public void testFlatten() { assertThat( Iterables.toList( Iterables.flatten( numbers, numbers ) ) .toString(), equalTo( "[1, 2, 3, 1, 2, 3]" ) ); Iterable<? extends Number> flatten = Iterables.flatten( numberIntegers, numberLongs ); assertThat( Iterables.toList( flatten ) .toString(), equalTo( "[1, 2, 3, 1, 2, 3]...
Iterables { public static <X, I extends Iterable<? extends X>> Iterable<X> flattenIterables( Iterable<I> multiIterator ) { return new FlattenIterable<X, I>( multiIterator ); } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iterable<T> iter...
@Test public void testFlattenIterables() { Iterable<List<String>> iterable = Iterables.iterable( numbers, numbers ); assertThat( Iterables.toList( Iterables.flattenIterables( iterable ) ) .toString(), equalTo( "[1, 2, 3, 1, 2, 3]" ) ); }
Iterables { public static <T> Iterable<T> mix( final Iterable<T>... iterables ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { final Iterable<Iterator<T>> iterators = toList(map( new Function<Iterable<T>, Iterator<T>>() { @Override public Iterator<T> map( Iterable<T> iterable ) { return iterable...
@Test public void testMix() { assertThat( Iterables.toList(Iterables.mix( Iterables.iterable( "A","B","C" ),Iterables.iterable( "1","2","3","4","5" ),Iterables.iterable( "X","Y","Z" ) )).toString(), equalTo( "[A, 1, X, B, 2, Y, C, 3, Z, 4, 5]" )); }
Iterables { public static <FROM, TO> Iterable<TO> map( Function<? super FROM, TO> function, Iterable<FROM> from ) { return new MapIterable<FROM, TO>( from, function ); } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iterable<T> iterable )...
@Test public void testMap() { assertThat( Iterables.toList( Iterables.map( new Function<String, String>() { public String map( String s ) { return s + s; } }, numbers ) ).toString(), equalTo( "[11, 22, 33]" ) ); Iterable<List<String>> numberIterable = Iterables.iterable( numbers, numbers, numbers ); assertThat( Iterabl...
Iterables { public static <T, C> Iterable<T> cast( Iterable<C> iterable ) { Iterable iter = iterable; return iter; } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iterable<T> iterable ); static Iterable<T> unique( final Iterable<T> iterab...
@Test public void testCast() { Iterable<Long> values = numberLongs; Iterable<Number> numbers = Iterables.cast(values); }
Iterables { public static <T> Iterable<T> debug( String format, final Iterable<T> iterable, final Function<T, String>... functions ) { final MessageFormat msgFormat = new MessageFormat( format ); return map( new Function<T, T>() { @Override public T map( T t ) { if( functions.length == 0 ) debugLogger.info( msgFormat.f...
@Test public void testDebug() { assertThat( Iterables.first( Iterables.debug( "Filtered number:{0}", Iterables.filter( Specifications.in( "2" ), Iterables.debug( "Number:{0}", numbers ) ) ) ), equalTo( "2" ) ); }
Iterables { public static <T> Iterable<T> cache(Iterable<T> iterable) { return new CacheIterable<T>(iterable); } static Iterable<T> empty(); static Iterable<T> constant( final T item ); static Iterable<T> limit( final int limitItems, final Iterable<T> iterable ); static Iterable<T> unique( final Iterable<T> iterable);...
@Test public void testCache() { final int[] count = new int[1]; Iterable<String> b = Iterables.cache(Iterables.filter( Specifications.and( new Specification<String>() { @Override public boolean satisfiedBy( String item ) { count[0] = count[0]+1; return true; } }, Specifications.in( "B" )), Iterables.iterable( "A", "B",...
Specifications { public static <T> Specification<T> TRUE() { return new Specification<T>() { public boolean satisfiedBy( T instance ) { return true; } }; } static Specification<T> TRUE(); static Specification<T> not( final Specification<T> specification ); static AndSpecification<T> and( final Specification<T>... spec...
@Test public void testTRUE() { Assert.assertThat( Specifications.<Object>TRUE().satisfiedBy( new Object() ), equalTo( true ) ); }
Specifications { public static <T> Specification<T> not( final Specification<T> specification ) { return new Specification<T>() { public boolean satisfiedBy( T instance ) { return !specification.satisfiedBy( instance ); } }; } static Specification<T> TRUE(); static Specification<T> not( final Specification<T> specific...
@Test public void testNot() { Assert.assertThat( Specifications.not( Specifications.<Object>TRUE() ) .satisfiedBy( new Object() ), equalTo( false ) ); }
Specifications { public static <T> AndSpecification<T> and( final Specification<T>... specifications ) { return and( Iterables.iterable( specifications )); } static Specification<T> TRUE(); static Specification<T> not( final Specification<T> specification ); static AndSpecification<T> and( final Specification<T>... sp...
@Test public void testAnd() { Specification<Object> trueSpec = Specifications.<Object>TRUE(); Specification<Object> falseSpec = Specifications.not( Specifications.<Object>TRUE() ); Assert.assertThat( Specifications.and( falseSpec, falseSpec ).satisfiedBy( new Object() ), equalTo( false ) ); Assert.assertThat( Specifica...
Specifications { public static <T> OrSpecification<T> or( final Specification<T>... specifications ) { return or( Iterables.iterable( specifications ) ); } static Specification<T> TRUE(); static Specification<T> not( final Specification<T> specification ); static AndSpecification<T> and( final Specification<T>... spec...
@Test public void testOr() { Specification<Object> trueSpec = Specifications.<Object>TRUE(); Specification<Object> falseSpec = Specifications.not( Specifications.<Object>TRUE() ); Assert.assertThat( Specifications.or( falseSpec, falseSpec ).satisfiedBy( new Object() ), equalTo( false ) ); Assert.assertThat( Specificati...
Specifications { public static <T> Specification<T> in( final T... allowed ) { return in( Iterables.iterable( allowed ) ); } static Specification<T> TRUE(); static Specification<T> not( final Specification<T> specification ); static AndSpecification<T> and( final Specification<T>... specifications ); static AndSpecifi...
@Test public void testIn() { Assert.assertThat( Specifications.in( "1", "2", "3" ).satisfiedBy( "2" ), equalTo( true ) ); Assert.assertThat( Specifications.in( "1", "2", "3" ).satisfiedBy( "4" ), equalTo( false ) ); }
Specifications { public static <FROM,TO> Specification<FROM> translate( final Function<FROM,TO> function, final Specification<? super TO> specification) { return new Specification<FROM>() { @Override public boolean satisfiedBy( FROM item ) { return specification.satisfiedBy( function.map( item ) ); } }; } static Speci...
@Test public void testTranslate() { Function<Object, String> stringifier = new Function<Object, String>() { @Override public String map( Object s ) { return s.toString(); } }; Assert.assertTrue( Specifications.translate( stringifier, Specifications.in( "3" ) ).satisfiedBy( 3L ) ); }
Functions { public static <A,B,C> Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose() { return new Function2<Function<? super B, C>, Function<A, B>, Function<A, C>>() { @Override public Function<A, C> map( Function<? super B, C> bcFunction, Function<A, B> abFunction ) { return compose( bcFunction, a...
@Test public void testCompose() { assertThat( Functions.<Object, String, Integer>compose().map( length, stringifier ).map( 12345L ), equalTo( 5 ) ); assertThat( compose( length, stringifier ).map( 12345L ), equalTo( 5 ) ); }
Functions { public static <FROM,TO> Function<FROM,TO> fromMap( final Map<FROM,TO> map) { return new Function<FROM,TO>() { @Override public TO map( FROM from ) { return map.get( from ); } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose(); static Function<FROM,TO> compose( final Functio...
@Test public void testFromMap() { Map<String,String> map = new HashMap<String, String>( ); map.put( "A","1" ); map.put( "B","2" ); map.put( "C","3" ); assertThat( Iterables.toList( Iterables.filter( Specifications.notNull(), Iterables.map( Functions.fromMap( map ), Iterables.iterable( "A", "B", "D" ) ) ) ).toString(), ...
Functions { public static <T> Function<T,T> withDefault( final T defaultValue) { return new Function<T, T>() { @Override public T map( T from ) { if (from == null) return defaultValue; else return from; } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose(); static Function<FROM,TO> comp...
@Test public void testWithDefault() { assertThat( Iterables.toList( Iterables.map( Functions.withDefault( "DEFAULT" ), Iterables.iterable( "123", null, "456" ) ) ).toString(), equalTo( "[123, DEFAULT, 456]" ) ); }
Functions { public static final Function<Number, Long> longSum() { return new Function<Number, Long>() { long sum; @Override public Long map( Number number ) { sum += number.longValue(); return sum; } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose(); static Function<FROM,TO> compose(...
@Test public void testLongSum() { assertThat( last( map( longSum(), iterable( 1, 2L, 3F, 4D ) ) ), equalTo( 10L ) ); }
Functions { public static Function<Number, Integer> intSum() { return new Function<Number, Integer>() { int sum; @Override public Integer map( Number number ) { sum += number.intValue(); return sum; } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A,C>> compose(); static Function<FROM,TO> compose(...
@Test public void testIntSum() { assertThat( last( map( intSum(), iterable( 1, 2L, 3F, 4D ) ) ), equalTo( 10 ) ); }
Functions { public static <T> Function<T, Integer> count( final Specification<T> specification) { return new Function<T, Integer>() { int count; @Override public Integer map( T item ) { if (specification.satisfiedBy( item )) count++; return count; } }; } static Function2<Function<? super B,C>,Function<A,B>, Function<A...
@Test public void testCount() { assertThat( last( map( count( in( "X" ) ), iterable( "X","Y","X","X","Y" ) ) ), equalTo( 3 ) ); }
Functions { public static <T> Function<T, Integer> indexOf( final Specification<T> specification) { return new Function<T, Integer>() { int index = -1; int current = 0; @Override public Integer map( T item ) { if (index == -1 && specification.satisfiedBy( item )) index = current; current++; return index; } }; } static...
@Test public void testIndexOf() { assertThat( last( map( indexOf( in( "D" ) ), iterable( "A","B","C","D","D" ) ) ), equalTo( 3 ) ); } @Test public void testIndexOf2() { assertThat( indexOf( "D", iterable( "A","B","C","D","D" )), equalTo( 3 ) ); }
Functions { public static <T> Comparator<T> comparator( final Function<T, Comparable> comparableFunction) { return new Comparator<T>() { Map<T, Comparable> compareKeys = new HashMap<T, Comparable>(); public int compare( T o1, T o2 ) { Comparable key1 = compareKeys.get( o1 ); if (key1 == null) { key1 = comparableFunctio...
@Test public void testComparator() { Comparator<Integer> comparator = Functions.comparator( new Function<Integer, Comparable>() { @Override public Comparable map( Integer integer ) { return integer.toString(); } } ); List<Integer> integers = Iterables.toList( Iterables.iterable( 1, 5, 3, 6, 8 ) ); Collections.sort( int...
IterableQuerySource implements QuerySource { @Override public <T> Iterator<T> iterator( Class<T> resultType, Specification<Composite> whereClause, Iterable<OrderBy> orderBySegments, Integer firstResult, Integer maxResults, Map<String, Object> variables ) { return list(resultType, whereClause, orderBySegments, firstResu...
@Test public void givenManyAssociationContainsQueryWhenExecutedThenReturnCorrect() throws EntityFinderException { QueryBuilder<Person> qb = qbf.newQueryBuilder( Person.class ); Person person = templateFor( Person.class ); Domain value = Network.domains().iterator().next(); Query<Person> query = qb.where( QueryExpressio...
UsageGraph { public List<K> resolveOrder() throws BindingException { if( resolved == null ) { buildUsageGraph(); resolved = new LinkedList<K>(); for( K item : data ) { int pos = resolved.size(); for( K entry : resolved ) { if( transitiveUse( entry, item ) ) { pos = resolved.indexOf( entry ); break; } } resolved.add( po...
@Test public void whenAskingForDependencyGivenThatGraphContainsCyclicDepThenDetectTheError() throws Exception { Thing thing1 = new Thing(); Thing thing2 = new Thing(); Thing thing3 = new Thing(); Thing thing4 = new Thing(); Thing thing5 = new Thing(); Thing thing6 = new Thing(); Thing thing7 = new Thing(); thing1.uses....
JRubyMixin implements InvocationHandler, ScriptReloadable { public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { try { Class declaringClass = method.getDeclaringClass(); IRubyObject rubyObject = rubyObjects.get( declaringClass ); if( rubyObject == null ) { try { rubyObject = runtime.eva...
@Test public void testInvoke() throws Throwable { JRubyComposite domain = module.newTransientBuilder( JRubyComposite.class ).newInstance(); Assert.assertEquals( "do1() in Ruby mixin.", domain.do1() ); }
GroovyMixin implements InvocationHandler { public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { final FunctionResource groovySource = getFunctionResource( method ); if( groovySource != null ) { if( groovySource.script ) { return invokeAsObject( method, args, groovySource.url ); } return...
@Test public void testInvoke() { GroovyComposite domain1 = module.newTransient( GroovyComposite.class ); GroovyComposite domain2 = module.newTransient( GroovyComposite.class ); Assert.assertEquals( "do1() in Groovy:1", domain1.do1() ); Assert.assertEquals( "do1() in Groovy:2", domain1.do1() ); Assert.assertEquals( "do1...
JavaScriptMixin implements InvocationHandler, ScriptReloadable { public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { Context cx = Context.enter(); try { Scriptable proxyScope = Context.toObject( proxy, instanceScope ); proxyScope.setPrototype( instanceScope ); proxyScope.put( "composit...
@Test public void testInvoke() throws Throwable { JavaScriptComposite domain = module.newTransient( JavaScriptComposite.class ); Assert.assertEquals( "do1 script \" and ' for many cases is harder.", domain.do1() ); }
BeanShellMixin implements InvocationHandler, ScriptReloadable { public Object invoke( Object proxy, Method method, Object[] args ) throws Throwable { Interpreter runtime; synchronized( BeanShellMixin.class ) { runtime = runtimes.get( module ); } if( runtime == null ) { runtime = new Interpreter(); BshClassManager.creat...
@Test public void testInvoke() throws Throwable { BeanShellComposite domain1 = module.newTransient( BeanShellComposite.class ); BeanShellComposite domain2 = module.newTransient( BeanShellComposite.class ); Assert.assertEquals( "do1() in Beanshell:1", domain1.do1() ); Assert.assertEquals( "do1() in Beanshell:2", domain1...
EventRouter implements Output<DomainEventValue, T>, Receiver<UnitOfWorkDomainEventsValue, T> { public EventRouter route( Specification<DomainEventValue> specification, Receiver<DomainEventValue, T> receiver ) { routeEvent.put( specification, receiver ); return this; } EventRouter route( Specification<DomainEventValue>...
@Test public void testRouter() throws IOException { final List<DomainEventValue> matched = new ArrayList<DomainEventValue>( ); EventRouter<IOException> router = new EventRouter<IOException>(); router.route( Events.withNames( "Test1", "Test2" ), new Receiver<DomainEventValue,IOException>() { @Override public void receiv...
Events { public static Iterable<DomainEventValue> events( Iterable<UnitOfWorkDomainEventsValue> transactions ) { return Iterables.flattenIterables( Iterables.map( new Function<UnitOfWorkDomainEventsValue, Iterable<DomainEventValue>>() { @Override public Iterable<DomainEventValue> map( UnitOfWorkDomainEventsValue unitOf...
@Test public void testIterablesEvents() { assertThat( count( events( list ) ), equalTo( 6L ) ); iterable( events( list ) ).transferTo( systemOut() ); }
EntityTypeSerializer { public EntityTypeSerializer() { dataTypes.put( String.class.getName(), XMLSchema.STRING ); dataTypes.put( Integer.class.getName(), XMLSchema.INT ); dataTypes.put( Boolean.class.getName(), XMLSchema.BOOLEAN ); dataTypes.put( Byte.class.getName(), XMLSchema.BYTE ); dataTypes.put( BigDecimal.class.g...
@Test public void testEntityTypeSerializer() throws RDFHandlerException { EntityDescriptor entityDescriptor = module.entityDescriptor(TestEntity.class.getName()); Iterable<Statement> graph = serializer.serialize( entityDescriptor ); String[] prefixes = new String[]{ "rdf", "dc", " vc", "qi4j" }; String[] namespaces = n...
ParameterizedTypes { public static <S, T extends S> ParameterizedType findParameterizedType( Class<T> type, Class<S> searchType ) { return ParameterizedTypes.findParameterizedType( (Type) type, searchType ); } private ParameterizedTypes(); static Type[] findTypeVariables( Class<T> type, Class<S> searchType ); static P...
@Test public void findParameterizedType() { assertEquals( GarbageMan.class.getGenericInterfaces()[ 0 ], ParameterizedTypes.findParameterizedType( GarbageMan.class, HandlerOf.class ) ); }
ParameterizedTypes { public static <S, T extends S> Type[] findTypeVariables( Class<T> type, Class<S> searchType ) { return ParameterizedTypes.findParameterizedType( type, searchType ).getActualTypeArguments(); } private ParameterizedTypes(); static Type[] findTypeVariables( Class<T> type, Class<S> searchType ); stati...
@Test public void findTypeVariables() { assertArrayEquals( ((ParameterizedType) GarbageMan.class.getGenericInterfaces()[0]).getActualTypeArguments(), ParameterizedTypes.findTypeVariables( GarbageMan.class, HandlerOf.class ) ); }
DBInitializer implements Serializable { public final void initialize( String schemaUrl, String dataUrl, String dbUrl, Properties connectionProperties ) throws SQLException, IOException { Connection connection1 = getSqlConnection( dbUrl, connectionProperties ); runScript( schemaUrl, connection1 ); Connection connection2...
@Test @Ignore( "The entire QRM is buggered." ) public void testInitializer() throws Exception { final DBInitializerConfiguration info = derbyDatabaseHandler.createDbInitializerConfigMock(); final DBInitializer initializer = new DBInitializer(); Properties connectionProperties = info.connectionProperties().get(); String...
CapitalizingIdentifierConverter implements IdentifierConverter { public String convertIdentifier( final QualifiedName qualifiedIdentifier ) { final String name = qualifiedIdentifier.name(); if( name.equalsIgnoreCase( "identity" ) ) { return "ID"; } return name.toUpperCase(); } String convertIdentifier( final Qualified...
@Test public void convertToUpperCase() { assertEquals( "identity -> ID", "ID", converter.convertIdentifier( QualifiedName.fromQN( "abc:identity" ) ) ); assertEquals( "uppercase ABC", "ABC", converter.convertIdentifier( QualifiedName.fromQN( "abc:abc" ) ) ); assertEquals( "removed qualified prefix", "ABC", converter.con...
CapitalizingIdentifierConverter implements IdentifierConverter { public Object getValueFromData( final Map<String, Object> rawData, final QualifiedName qualifiedName ) { String convertedIdentifier = convertIdentifier( qualifiedName ); if( rawData.containsKey( convertedIdentifier ) ) { return rawData.remove( convertedId...
@Test public void removeFromMap() { Map<String, Object> rawData = new HashMap<String, Object>(); rawData.put( "ABC", "test" ); assertEquals( "converted key and found value", "test", converter.getValueFromData( rawData, QualifiedName.fromQN( "aaa:abc" ) ) ); assertEquals( "entry removed", 0, rawData.size() ); } @Test pu...
CapitalizingIdentifierConverter implements IdentifierConverter { public Map<String, Object> convertKeys( Map<QualifiedName, Object> rawData ) { Map<String, Object> result = new HashMap<String, Object>( rawData.size() ); for( Map.Entry<QualifiedName, Object> entry : rawData.entrySet() ) { final String convertedIdentifie...
@Test public void convertMapKeys() { Map<QualifiedName, Object> rawData = new HashMap<QualifiedName, Object>(); rawData.put( QualifiedName.fromQN( "abc:abc" ), "test1" ); rawData.put( QualifiedName.fromQN( "abc:DEF" ), "test2" ); rawData.put( QualifiedName.fromQN( "aaa:GHI" ), "test3" ); rawData.put( QualifiedName.from...
OpenSDSInfo extends BaseArrayInfo { public OpenSDSInfo() { super(); } OpenSDSInfo(); OpenSDSInfo(String id, String hostName, String port); @Override boolean equals(Object obj); @Override int hashCode(); String getProductSN(); void setProductSN(String productSN); boolean getauthEnabled(); void setauthEnabled(boolean au...
@Test void testOpenSDSInfo() { OpenSDSInfo OpenSDSInfo = new OpenSDSInfo("testId", "testHostName", "testPort"); OpenSDSInfo.hashCode(); OpenSDSInfo.getHostName(); OpenSDSInfo.getURL(); OpenSDSInfo.getProductSN(); OpenSDSInfo.toString(); }
OpenSDSInfo extends BaseArrayInfo { @Override public boolean equals(Object obj) { if (obj instanceof OpenSDSInfo) { OpenSDSInfo openSDSInfo = (OpenSDSInfo) obj; if (openSDSInfo.getId().equals(getId())) { return true; } } return false; } OpenSDSInfo(); OpenSDSInfo(String id, String hostName, String port); @Override boo...
@Test void testEqualsObject() { OpenSDSInfo OpenSDSInfo = new OpenSDSInfo("testId", "testHostName", "testPort"); OpenSDSInfo obj = new OpenSDSInfo("testId", "testHostName", "testPort"); OpenSDSInfo.equals(obj); } @Test void testNotEqualsObject() { OpenSDSInfo OpenSDSInfo = new OpenSDSInfo(); OpenSDSInfo obj = new OpenS...
VolumeService { public void createVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity, String profile) throws Exception { OpenSDS opensds = new OpenSDS(); opensds.login(openSDSInfo); log.info("Logged in to OpenSDS"); VolumeMO volume = opensds.createVolume(name, description, capacity, profile)...
@Test void testCreateVolume() throws Exception { readDefaultConfig(); VolumeService volumeService = new VolumeService(); volumeService.createVolume(arrayInfo, "test_script_vol", "test_script_vol", 1, profileId); }
VolumeService { public String createAndAttachVolume(OpenSDSInfo openSDSInfo, String name, String description, long capacity, String profile, String hostIP, String iqn) throws Exception { OpenSDS opensds = new OpenSDS(); opensds.login(openSDSInfo); VolumeMO volume = opensds.createVolume(name, description, capacity, prof...
@Test void testcreateAndAttachVolume() throws Exception { VolumeService volumeService = new VolumeService(); readDefaultConfig(); volumeService.createAndAttachVolume(arrayInfo, "attach_vol", "attach volume test", 1, profileId, esxIP, esxIQN); }
VolumeService { public void deleteVolume(OpenSDSInfo openSDSInfo, String id) throws Exception { OpenSDS opensds = new OpenSDS(); opensds.login(openSDSInfo); log.info("Logged in to OpenSDS"); opensds.deleteVolume(id); log.info("Volume " + id + "is deleted"); } void createVolume(OpenSDSInfo openSDSInfo, String name, Str...
@Test void testDeleteVolume() throws Exception { VolumeService volumeService = new VolumeService(); readDefaultConfig(); volumeService.deleteVolume(arrayInfo, volId); }
VolumeService { public void expandVolume(OpenSDSInfo openSDSInfo, String id, long capacity) throws Exception { OpenSDS opensds = new OpenSDS(); opensds.login(openSDSInfo); log.info("Logged in to OpenSDS"); opensds.expandVolume(id, capacity); } void createVolume(OpenSDSInfo openSDSInfo, String name, String description,...
@Test void testexpandVolume() throws Exception { VolumeService volumeService = new VolumeService(); readDefaultConfig(); volumeService.expandVolume(arrayInfo, volId, 2); }
Configuration { public void register(String arrayName, String hostname, String port, String username, String password, boolean authEnabled, String productModel) throws Exception { String uniqId = hostname + "-" + port; OpenSDSInfo arrayInfo = new OpenSDSInfo(uniqId, hostname, port); arrayInfo.setArrayName(arrayName); a...
@Test void testRegister() throws Exception { Configuration conf = new Configuration("testID", "opensds"); conf.register("OpenSDS_Test", "127.0.0.1", "50040", "admin", "opensds@123", true, "V1"); }
MyWidget extends Composite { public void setName(String firstName, String lastName) { name.setText(firstName + " " + lastName); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); }
@Test public void testSetName() { widget.setName("John", "Smith"); verify(widget.name).setText("John Smith"); } @Test public void testSetNameWithFakes() { GwtMockito.useProviderForType(HasText.class, new FakeProvider<HasText>() { @Override public HasText getFake(Class<?> type) { return new HasText() { private String te...
GwtMockito { public static void useProviderForType(Class<?> type, FakeProvider<?> provider) { if (bridge == null) { throw new IllegalStateException("Must call initMocks() before calling useProviderForType()"); } if (bridge.registeredMocks.containsKey(type)) { throw new IllegalArgumentException( "Can't use a provider fo...
@Test public void shouldFailForAmbiguousProviders() { GwtMockito.useProviderForType(AnotherInterface.class, new FakeProvider<AnotherInterface>() { @Override public AnotherInterface getFake(Class<?> type) { return mock(AnotherInterface.class); } }); GwtMockito.useProviderForType(YetAnotherInterface.class, new FakeProvid...
GwtMockito { public static <T> T getFake(Class<T> type) { T fake = getFakeFromProviderMap( type, bridge != null ? bridge.registeredProviders : DEFAULT_FAKE_PROVIDERS); if (fake == null) { throw new IllegalArgumentException("No fake provider has been registered " + "for " + type.getSimpleName() + ". Call useProviderForT...
@Test public void getFakeShouldReturnDefaultFakes() { SampleMessages messages = GwtMockito.getFake(SampleMessages.class); assertEquals("noArgs", messages.noArgs()); } @Test public void getFakeShouldFailForUnregisteredFakes() { try { GwtMockito.getFake(SampleInterface.class); fail("Exception not thrown"); } catch (Illeg...
MyWidget extends Composite { public void updateData() { data.setText(dataProvider.getData()); } MyWidget(); void setName(String firstName, String lastName); void updateData(); void loadDataFromRpc(); }
@Test public void testUpdateData() { when(dataProvider.getData()).thenReturn("data"); widget.updateData(); verify(widget.data).setText("data"); }
MyWidget extends Composite { public void loadDataFromRpc() { MyServiceAsync service = GWT.create(MyService.class); service.getData(new AsyncCallback<String>() { @Override public void onSuccess(String result) { data.setText(result); } @Override public void onFailure(Throwable caught) {} }); } MyWidget(); void setName(St...
@Test @SuppressWarnings("unchecked") public void testMockRpcs() { doAnswer(returnSuccess("some data")).when(myService).getData(any(AsyncCallback.class)); widget.loadDataFromRpc(); verify(widget.data).setText("some data"); }
GwtMockito { public static void initMocks(Object owner) { bridge = new Bridge(); for (Entry<Class<?>, FakeProvider<?>> entry : DEFAULT_FAKE_PROVIDERS.entrySet()) { useProviderForType(entry.getKey(), entry.getValue()); } boolean success = false; try { setGwtBridge(bridge); registerGwtMocks(owner); MockitoAnnotations.ini...
@Test(expected = IllegalArgumentException.class) public void shouldNotAllowMultipleGwtMocksForSameType() { GwtMockito.initMocks(new Object() { @GwtMock SampleInterface mock1; @GwtMock SampleInterface mock2; }); }
EventBinderWriter { void writeDoBindEventHandlers(JClassType target, SourceWriter writer, TypeOracle typeOracle) throws UnableToCompleteException { writeBindMethodHeader(writer, target.getQualifiedSourceName()); for (JMethod method : target.getInheritableMethods()) { EventHandler annotation = method.getAnnotation(Event...
@Test public void shouldWriteDoBindEventHandler() throws Exception { JClassType eventType1 = getEventType(MyEvent1.class); JClassType eventType2 = getEventType(MyEvent2.class); JMethod method1 = newMethod("method1", eventType1); JMethod method2 = newMethod("method2", eventType2); JMethod method3 = newMethod("method3", ...
InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { handleRegistration(info, leaseDuration, isReplication); super.register(info, leaseDuration, isReplication); } InstanceRegistry(EurekaS...
@Test public void testRegister() throws Exception { final LeaseInfo leaseInfo = getLeaseInfo(); final InstanceInfo instanceInfo = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, leaseInfo); instanceRegistry.register(instanceInfo, false); assertEquals(1, this.testEvents.applicationEvents.size()); assertTrue(this...
InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override protected boolean internalCancel(String appName, String id, boolean isReplication) { handleCancelation(appName, id, isReplication); return super.internalCancel(appName, id, isReplication); } InstanceRegistry(EurekaServ...
@Test public void testInternalCancel() throws Exception { instanceRegistry.internalCancel(APP_NAME, HOST_NAME, false); assertEquals(1, this.testEvents.applicationEvents.size()); assertTrue(this.testEvents.applicationEvents.get(0) instanceof EurekaInstanceCanceledEvent); final EurekaInstanceCanceledEvent registeredEvent...
InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { @Override public boolean renew(final String appName, final String serverId, boolean isReplication) { log("renew " + appName + " serverId " + serverId + ", isReplication {}" + isReplication); List<Application> applications = getS...
@Test public void testRenew() throws Exception { final InstanceInfo instanceInfo1 = getInstanceInfo(APP_NAME, HOST_NAME, INSTANCE_ID, PORT, null); final InstanceInfo instanceInfo2 = getInstanceInfo(APP_NAME, HOST_NAME, "my-host-name:8009", 8009, null); final Application application = new Application(APP_NAME, Arrays.as...
EurekaController { @RequestMapping(method = RequestMethod.GET) public String status(HttpServletRequest request, Map<String, Object> model) { populateBase(request, model); populateApps(model); StatusInfo statusInfo; try { statusInfo = new StatusResource().getStatusInfo(); } catch (Exception e) { statusInfo = StatusInfo....
@Test public void testStatus() throws Exception { Map<String, Object> model = new HashMap<>(); EurekaController controller = new EurekaController(infoManager); controller.status(new MockHttpServletRequest("GET", "/"), model); Map<String, Object> app = getFirst(model, "apps"); Map<String, Object> instanceInfo = getFirst...
HttpClient { public Response get(String host, String endpoint) throws IOException { return performRequest("GET", host, endpoint, Collections.emptyMap(), null); } private HttpClient(); Response get(String host, String endpoint); Response post(String host, String endpoint, JSONObject entity); Response put(String host, S...
@Test public void get() throws Exception { Response response = HttpClient.getInstance().get("http: System.out.println(response); }
ClassUtils { public static Set<Class<?>> getAnnotatedClasses(String packageName, Class<? extends Annotation> annotation) { Reflections reflections = new Reflections(packageName); Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(annotation); return annotated; } static Set<Class<?>> getAnnotatedClasses(String...
@Test public void getAnnotatedClasses() { ClassUtils.getAnnotatedClasses("com.timeyang.search.entity", Document.class).forEach(System.out::println); }
JsonUtils { public static String convertToString(JSONObject jsonObject) { try { return mapper.writeValueAsString(jsonObject); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } static String convertToString(JSONObject jsonObject); static byte[] convertToBytes(JSONObject jsonObject); static JSONOb...
@Test public void convertToString() throws Exception { JSONObject jsonObject = new JSONObject(); jsonObject.put("settings", new JSONObject().put("index", new JSONObject().put("number_of_shards", 3) .put("number_of_replicas", 2) ) ); String settings = JsonUtils.convertToString(jsonObject); System.out.println(settings); ...
KafkaConnectClient { public void deleteConnector(String connectorName) { if(!checkConnectorExists(connectorName)) throw new IllegalArgumentException("The specified connector[" + connectorName + "] doesn't exist"); String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); locks.putIfAbsent(conn...
@Test public void deleteConnector() throws Exception { JkesProperties jkesProperties = new DefaultJkesPropertiesImpl() { @Override public String getKafkaConnectServers() { return "http: } }; Config.setJkesProperties(jkesProperties); String connectorName = KafkaConnectUtils.getConnectorName(Person.class); new KafkaConne...
KafkaConnectClient { public boolean checkConnectorExists(String connectorName) { String endpoint = "connectors/" + connectorName; try { String url = getRandomUrl(); Response response; locks.putIfAbsent(connectorName, new ReentrantLock()); try { locks.get(connectorName).lock(); response = HTTP_CLIENT.get(url, endpoint);...
@Test public void checkConnectorExists() throws Exception { JkesProperties jkesProperties = new DefaultJkesPropertiesImpl() { @Override public String getKafkaConnectServers() { return "http: } }; Config.setJkesProperties(jkesProperties); String connectorName = KafkaConnectUtils.getConnectorName(Person.class); System.ou...
IndicesBuilder { public JSONObject buildIndex(Class<?> clazz) { Asserts.check(clazz.isAnnotationPresent(Document.class), "The class " + clazz.getCanonicalName() + " must be annotated with " + Document.class.getCanonicalName()); JSONObject settings = new JSONObject(); settings.put("index.mapper.dynamic", false); setting...
@Test public void buildIndex() throws Exception { IndicesBuilder indicesBuilder = IndicesBuilder.getInstance(); JSONObject indices = indicesBuilder.buildIndex(PersonGroup.class); System.out.println(JsonUtils.convertToString(indices)); }
IndicesAdminClient { @PostConstruct public void init() { logger.info("search init begin"); Set<Class<?>> annotatedClasses = metadata.getAnnotatedDocuments(); check(annotatedClasses); for(Class clazz : annotatedClasses) { if(checkExists(DocumentUtils.getIndexName(clazz))) { updateIndex(clazz); }else { createIndex(clazz)...
@Test public void start() throws Exception { indicesAdminClient.init(); }
IndicesAdminClient { public void createIndex(Class clazz) { String indexName = DocumentUtils.getIndexName(clazz); JSONObject index = this.indicesBuilder.buildIndex(clazz); locks.putIfAbsent(indexName, new ReentrantLock()); locks.get(indexName).lock(); this.esRestClient.performRequest("PUT", indexName, index); locks.get...
@Test public void createIndex() throws Exception { if(!indicesAdminClient.checkExists("my_index")) indicesAdminClient.createIndex(PersonGroup.class); }
IndicesAdminClient { public boolean checkExists(String index) { locks.putIfAbsent(index, new ReentrantLock()); locks.get(index).lock(); Response response = this.esRestClient.performRequest("HEAD", index); locks.get(index).unlock(); return response.getStatusLine().getStatusCode() == 200; } @Inject IndicesAdminClient(Es...
@Test public void checkExists() throws Exception { indicesAdminClient.checkExists("my_index"); }
MappingBuilder { public JSONObject buildMapping(Class<?> clazz) { JSONObject mapping = new JSONObject(); mapping.put("dynamic", "strict"); mapping.put(FIELD_PROPERTIES, getEntityMappingProperties(clazz)); return mapping; } JSONObject buildMapping(Class<?> clazz); }
@Test public void buildMapping() { JSONObject mapping = new MappingBuilder().buildMapping(PersonGroup.class); System.out.println(JsonUtils.convertToString(mapping)); }
HttpClient { public Response post(String host, String endpoint, JSONObject entity) throws IOException { return performRequest("POST", host, endpoint, Collections.emptyMap(), entity); } private HttpClient(); Response get(String host, String endpoint); Response post(String host, String endpoint, JSONObject entity); Resp...
@Test public void post() throws Exception { }
HttpClient { static URI buildUri(String path, Map<String, String> params) { Objects.requireNonNull(path, "path must not be null"); try { URIBuilder uriBuilder = new URIBuilder(path); for (Map.Entry<String, String> param : params.entrySet()) { uriBuilder.addParameter(param.getKey(), param.getValue()); } return uriBuilde...
@Test public void buildUri() throws Exception { String url = "http: InetAddress address = InetAddress.getByName(new URL(url).getHost()); String ip = address.getHostAddress(); System.out.println(ip); }
HttpUtils { public static String parseIpFromUrl(String url) throws MalformedURLException, UnknownHostException { Asserts.notBlank(url, "url can't be null"); InetAddress address = InetAddress.getByName(new URL(url).getHost()); return address.getHostAddress(); } static String parseIpFromUrl(String url); static String[] ...
@Test public void parseIpFromUrl() throws Exception { System.out.println(HttpUtils.parseIpFromUrl("http: }
HttpUtils { public static String[] getIpsFromUrls(String... urls) throws MalformedURLException, UnknownHostException { if(urls == null || urls.length == 0) return null; String[] ips = new String[urls.length]; for (int i = 0, urlsLength = urls.length; i < urlsLength; i++) { String url = urls[i]; InetAddress address = In...
@Test public void getIpsFormUrls() throws Exception { System.out.println(Arrays.toString(HttpUtils.getIpsFromUrls("http: }
HttpUtils { public static String[] getIpsFromDomainNames(String... domainNames) throws UnknownHostException { if(domainNames == null || domainNames.length == 0) return null; String[] ips = new String[domainNames.length]; for (int i = 0, urlsLength = domainNames.length; i < urlsLength; i++) { String url = "http: try { I...
@Test public void getIpsFormDomainNames() throws Exception { System.out.println(Arrays.toString(HttpUtils.getIpsFromDomainNames("timeyang.com", "github.com"))); }
ReflectionUtils { public static List<String> getReturnTypeParameters(Method method) { List<String> typeParameters = new ArrayList<>(); Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); Pattern p = Pattern.compile("<((\\S+\\.?),?\\s*)>"); Matcher m = p.matcher(typeName); while (m.find()) {...
@Test public void getReturnTypeParameters() throws Exception { Method method = PersonGroup.class.getDeclaredMethod("getPersons"); ReflectionUtils.getReturnTypeParameters(method); }
ReflectionUtils { public static String getInnermostType(Method method) { Type type = method.getGenericReturnType(); String typeName = type.getTypeName(); String[] types = typeName.split(",\\s*|<|<|>+"); return types[types.length - 1]; } static List<String> getReturnTypeParameters(Method method); static String getTypeN...
@Test public void getActualReturnType() throws Exception { Method method1 = ComplexEntity.class.getDeclaredMethod("getCars"); System.out.println(ReflectionUtils.getInnermostType(method1)); Method method2 = ComplexEntity.class.getDeclaredMethod("getBooks"); System.out.println(ReflectionUtils.getInnermostType(method2)); ...
SimpleClassUtils { static Class[] getClasses(String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); Li...
@Test public void testGetClasses() throws IOException, ClassNotFoundException { Class[] classes = SimpleClassUtils.getClasses("com.timeyang.search.entity"); for (Class c : classes) { System.out.println(c); } for (Class c : SimpleClassUtils.getClasses("com.fasterxml.jackson.databind.module")) { System.out.println(c); } ...
ClassUtils { static Set<Class<?>> getClasses(String packageName) { List<ClassLoader> classLoadersList = new LinkedList<>(); classLoadersList.add(ClasspathHelper.contextClassLoader()); classLoadersList.add(ClasspathHelper.staticClassLoader()); Reflections reflections = new Reflections(new ConfigurationBuilder() .setScan...
@Test public void getCLasses() { ClassUtils.getClasses("com.timeyang.search.entity").forEach(System.out::println); ClassUtils.getClasses("com.fasterxml.jackson.databind.module").forEach(System.out::println); }
ExceptionStack implements Serializable { public Collection<Throwable> getCauseElements() { return Collections.unmodifiableCollection(this.causes); } ExceptionStack(); ExceptionStack(final Throwable exception); @Deprecated protected ExceptionStack(final Collection<Throwable> causeChainElements, final int currentElemen...
@Test public void testSQLExceptionUnwrap() { SQLTransactionRollbackException transactionRollbackException = new SQLTransactionRollbackException(); SQLRecoverableException recoverableException = new SQLRecoverableException(); SQLSyntaxErrorException syntaxErrorException = new SQLSyntaxErrorException(); recoverableExcept...
RouteService { public Schema route(String sql) { SQLStatement sqlStatement = SQLUtils.parseSingleMysqlStatement(sql); return null; } RouteService(MetadataManager metadataManager); static RouteService create(MetadataManager metadataManager); Schema route(String sql); }
@Test public void test(){ String sql = "select 1"; String text = route(sql); Assert.assertSame(text,""); }