Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
5,300
public class ReverseArrayIterator<T> implements Iterator<T> { private final T[] array; private int index; public ReverseArrayIterator( T[] array ) { this.array = array; this.index = array.length-1; } public boolean hasNext() { return index >= 0; } public T next() { if ( !hasNext() ) throw new NoSuchElementException(); return array[index--]; } public void remove() { throw new UnsupportedOperationException(); } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_ReverseArrayIterator.java
5,301
return new ResourceClosingIterator<T, T>( resource, iterator ) { @Override public T map( T elem ) { return elem; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_ResourceClosingIterator.java
5,302
public abstract class ResourceClosingIterator<T, V> implements ResourceIterator<V> { public static <T> ResourceIterator<T> newResourceIterator( Resource resource, Iterator<T> iterator ) { return new ResourceClosingIterator<T, T>( resource, iterator ) { @Override public T map( T elem ) { return elem; } }; } private Resource resource; private final Iterator<T> iterator; ResourceClosingIterator( Resource resource, Iterator<T> iterator ) { this.resource = resource; this.iterator = iterator; } @Override public void close() { resource.close(); resource = Resource.EMPTY; } @Override public boolean hasNext() { boolean hasNext = iterator.hasNext(); if ( !hasNext ) { close(); } return hasNext; } public abstract V map(T elem); @Override public V next() { try { return map( iterator.next() ); } catch ( NoSuchElementException e ) { close(); throw e; } } @Override public void remove() { iterator.remove(); } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_ResourceClosingIterator.java
5,303
public class RangeIterator extends PrefetchingIterator<Integer> { private int current; private final int end; private final int stride; public RangeIterator( int end ) { this( 0, end ); } public RangeIterator( int start, int end ) { this( start, end, 1 ); } public RangeIterator( int start, int end, int stride ) { this.current = start; this.end = end; this.stride = stride; } @Override protected Integer fetchNextOrNull() { try { return current < end ? current : null; } finally { current += stride; } } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_RangeIterator.java
5,304
{ private PrimitiveLongIterator current; @Override public boolean hasNext() { while ( current == null || !current.hasNext() ) { if ( !source.hasNext() ) { return false; } current = source.next(); } return true; } @Override public long next() { if ( !hasNext() ) { throw new NoSuchElementException(); } return current.next(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,305
{ @Override public boolean hasNext() { return iterator.hasNext(); } @Override public int next() { Integer nextValue = iterator.next(); if ( null == nextValue ) { throw new IllegalArgumentException( "Cannot convert null Long to primitive long" ); } return nextValue; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,306
{ @Override public boolean hasNext() { return iterator.hasNext(); } @Override public long next() { Long nextValue = iterator.next(); if ( null == nextValue ) { throw new IllegalArgumentException( "Cannot convert null Long to primitive long" ); } return nextValue; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,307
{ @Override public boolean hasNext() { return primIterator.hasNext(); } @Override public Long next() { return primIterator.next(); } @Override public void remove() { throw new UnsupportedOperationException( ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,308
{ @Override public Iterator<T> iterator() { final Iterator<T> iterator = iterable.iterator(); return new Iterator<T>() { Set<T> items = new HashSet<>(); T nextItem; @Override public boolean hasNext() { while ( iterator.hasNext() ) { nextItem = iterator.next(); if ( items.add( nextItem ) ) { return true; } } return false; } @Override public T next() { if ( nextItem == null && !hasNext() ) { throw new NoSuchElementException(); } return nextItem; } @Override public void remove() { } }; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,309
{ @Override public Iterable<T> apply( Iterable<T> ts ) { return limit( limitItems, ts ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,310
{ int count; @Override public boolean hasNext() { return count < limitItems && iterator.hasNext(); } @Override public T next() { count++; return iterator.next(); } @Override public void remove() { iterator.remove(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,311
{ @Override public Iterator<T> iterator() { final Iterator<T> iterator = iterable.iterator(); return new Iterator<T>() { int count; @Override public boolean hasNext() { return count < limitItems && iterator.hasNext(); } @Override public T next() { count++; return iterator.next(); } @Override public void remove() { iterator.remove(); } }; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,312
{ @SuppressWarnings( "unchecked" ) @Override public int compare( T o1, T o2 ) { return compareFunction.apply( o1 ).compareTo( compareFunction.apply( o2 ) ); } } );
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,313
{ private boolean returned; @Override protected T fetchNextOrNull() { try { return !returned ? item : null; } finally { returned = true; } } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,314
{ @Override public Iterator<T> iterator() { return new PrefetchingIterator<T>() { private boolean returned; @Override protected T fetchNextOrNull() { try { return !returned ? item : null; } finally { returned = true; } } }; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,315
{ @Override public ResourceIterator<T> iterator() { return asResourceIterator( labels.iterator() ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,316
{ T last = item; @Override public boolean hasNext() { return iterator.hasNext() || last != null; } @Override public T next() { if ( iterator.hasNext() ) { return iterator.next(); } else { try { return last; } finally { last = null; } } } @Override public void remove() { } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,317
{ @Override public Iterator<T> iterator() { final Iterator<T> iterator = iterable.iterator(); return new Iterator<T>() { T last = item; @Override public boolean hasNext() { return iterator.hasNext() || last != null; } @Override public T next() { if ( iterator.hasNext() ) { return iterator.next(); } else { try { return last; } finally { last = null; } } } @Override public void remove() { } }; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,318
{ T first = item; Iterator<T> iterator; @Override public boolean hasNext() { if ( first != null ) { return true; } else { if ( iterator == null ) { iterator = iterable.iterator(); } } return iterator.hasNext(); } @Override public T next() { if ( first != null ) { try { return first; } finally { first = null; } } else { return iterator.next(); } } @Override public void remove() { } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,319
{ @Override public Iterator<T> iterator() { return new Iterator<T>() { T first = item; Iterator<T> iterator; @Override public boolean hasNext() { if ( first != null ) { return true; } else { if ( iterator == null ) { iterator = iterable.iterator(); } } return iterator.hasNext(); } @Override public T next() { if ( first != null ) { try { return first; } finally { first = null; } } else { return iterator.next(); } } @Override public void remove() { } }; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,320
{ @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,321
{ Iterator iterator = new Iterator() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { } }; @Override public Iterator iterator() { return iterator; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,322
public final class Iterables { private static Iterable EMPTY = new Iterable() { Iterator iterator = new Iterator() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { } }; @Override public Iterator iterator() { return iterator; } }; @SuppressWarnings("unchecked") public static <T> Iterable<T> empty() { return EMPTY; } public static <T> Iterable<T> limit( final int limitItems, final Iterable<T> iterable ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { final Iterator<T> iterator = iterable.iterator(); return new Iterator<T>() { int count; @Override public boolean hasNext() { return count < limitItems && iterator.hasNext(); } @Override public T next() { count++; return iterator.next(); } @Override public void remove() { iterator.remove(); } }; } }; } public static <T> Function<Iterable<T>, Iterable<T>> limit( final int limitItems ) { return new Function<Iterable<T>, Iterable<T>>() { @Override public Iterable<T> apply( Iterable<T> ts ) { return limit( limitItems, ts ); } }; } 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 nextItem; @Override public boolean hasNext() { while ( iterator.hasNext() ) { nextItem = iterator.next(); if ( items.add( nextItem ) ) { return true; } } return false; } @Override public T next() { if ( nextItem == null && !hasNext() ) { throw new NoSuchElementException(); } return nextItem; } @Override public void remove() { } }; } }; } public static <T, C extends Collection<T>> C addAll( C collection, Iterable<? extends T> iterable ) { for ( T item : iterable ) { collection.add( item ); } return collection; } public static long count( Iterable<?> iterable ) { long c = 0; for ( Iterator<?> iterator = iterable.iterator(); iterator.hasNext(); iterator.next() ) { c++; } return c; } public static <X> Iterable<X> filter( Predicate<? super X> specification, Iterable<X> i ) { return new FilterIterable<>( i, specification ); } public static <X> Iterator<X> filter( Predicate<? super X> specification, Iterator<X> i ) { return new FilterIterable.FilterIterator<>( i, specification ); } public static <X> X first( Iterable<? extends X> i ) { Iterator<? extends X> iter = i.iterator(); if ( iter.hasNext() ) { return iter.next(); } else { return null; } } public static <X> X single( Iterable<? extends X> i ) { return IteratorUtil.single( i ); } public static <X> Iterable<X> skip( final int skip, final Iterable<X> iterable ) { return new Iterable<X>() { @Override public Iterator<X> iterator() { Iterator<X> iterator = iterable.iterator(); for ( int i = 0; i < skip; i++ ) { if ( iterator.hasNext() ) { iterator.next(); } else { return Iterables.<X>empty().iterator(); } } return iterator; } }; } 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; } public static <X> Iterable<X> reverse( Iterable<X> iterable ) { List<X> list = toList( iterable ); Collections.reverse( list ); return list; } @SafeVarargs public static <X, I extends Iterable<? extends X>> Iterable<X> flatten( I... multiIterator ) { return new FlattenIterable<>( asList(multiIterator) ); } @SafeVarargs 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> apply( Iterable<T> iterable ) { return iterable.iterator(); } }, asList(iterables) ) ); return new Iterator<T>() { Iterator<Iterator<T>> iterator; Iterator<T> iter; @Override public boolean hasNext() { for ( Iterator<T> iterator : iterators ) { if ( iterator.hasNext() ) { return true; } } return false; } @Override public T next() { if ( iterator == null ) { iterator = iterators.iterator(); } while ( iterator.hasNext() ) { iter = iterator.next(); if ( iter.hasNext() ) { return iter.next(); } } iterator = null; return next(); } @Override public void remove() { if ( iter != null ) { iter.remove(); } } }; } }; } public static <FROM, TO> Iterable<TO> map( Function<? super FROM, ? extends TO> function, Iterable<FROM> from ) { return new MapIterable<>( from, function ); } public static <FROM, TO> Iterator<TO> map( Function<? super FROM, ? extends TO> function, Iterator<FROM> from ) { return new MapIterable.MapIterator<>( from, function ); } public static <FROM, TO> Iterator<TO> flatMap( Function<? super FROM, ? extends Iterator<TO>> function, Iterator<FROM> from ) { return new CombiningIterator<>( map(function, from) ); } public static <T> Iterator<T> map( final FunctionFromPrimitiveLong<T> mapFunction, final PrimitiveLongIterator source ) { return new Iterator<T>() { @Override public boolean hasNext() { return source.hasNext(); } @Override public T next() { return mapFunction.apply( source.next() ); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } public static <T> Iterator<T> map( final FunctionFromPrimitiveInt<T> mapFunction, final PrimitiveIntIterator source ) { return new Iterator<T>() { @Override public boolean hasNext() { return source.hasNext(); } @Override public T next() { return mapFunction.apply( source.next() ); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @SafeVarargs @SuppressWarnings("unchecked") public static <T, C extends T> Iterable<T> iterable( C... items ) { return (Iterable<T>) asList(items); } @SuppressWarnings("unchecked") public static <T, C> Iterable<T> cast( Iterable<C> iterable ) { return (Iterable) iterable; } @SafeVarargs @SuppressWarnings("unchecked") public static <T> Iterable<T> concat( Iterable<? extends T>... iterables ) { return concat( asList( (Iterable<T>[]) iterables ) ); } public static <T> Iterable<T> concat( final Iterable<Iterable<T>> iterables ) { return new CombiningIterable<>( iterables ); } @SafeVarargs @SuppressWarnings("unchecked") public static <T> Iterator<T> concat( Iterator<? extends T>... iterables ) { return concat( Arrays.asList( (Iterator<T>[]) iterables ).iterator() ); } public static <T> ResourceIterator<T> concatResourceIterators( Iterator<ResourceIterator<T>> iterators ) { return new CombiningResourceIterator<>(iterators); } public static <T> Iterator<T> concat( Iterator<Iterator<T>> iterators ) { return new CombiningIterator<>(iterators); } public static <FROM, TO> Function<FROM, TO> cast() { return new Function<FROM, TO>() { @Override @SuppressWarnings("unchecked") public TO apply( FROM from ) { return (TO) from; } }; } public static <T, C extends T> Iterable<T> prepend( final C item, final Iterable<T> iterable ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { T first = item; Iterator<T> iterator; @Override public boolean hasNext() { if ( first != null ) { return true; } else { if ( iterator == null ) { iterator = iterable.iterator(); } } return iterator.hasNext(); } @Override public T next() { if ( first != null ) { try { return first; } finally { first = null; } } else { return iterator.next(); } } @Override public void remove() { } }; } }; } 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() { return iterator.hasNext() || last != null; } @Override public T next() { if ( iterator.hasNext() ) { return iterator.next(); } else { try { return last; } finally { last = null; } } } @Override public void remove() { } }; } }; } public static <T> Iterable<T> cache( Iterable<T> iterable ) { return new CacheIterable<>( iterable ); } public static <T> List<T> toList( Iterable<T> iterable ) { return addAll( new ArrayList<T>(), iterable ); } public static Object[] toArray( Iterable<Object> iterable ) { return toArray( Object.class, iterable ); } @SuppressWarnings("unchecked") public static <T> T[] toArray( Class<T> componentType, Iterable<T> iterable ) { if ( iterable == null ) { return null; } List<T> list = toList( iterable ); return list.toArray( (T[]) Array.newInstance( componentType, list.size() ) ); } public static <T> ResourceIterable<T> asResourceIterable( final Iterable<T> labels ) { return new ResourceIterable<T>() { @Override public ResourceIterator<T> iterator() { return asResourceIterator( labels.iterator() ); } }; } public static <T> Set<T> toSet( Iterable<T> iterable ) { return addAll( new HashSet<T>(), iterable ); } public static String toString( Iterable<?> values, String separator ) { Iterator<?> it = values.iterator(); StringBuilder sb = new StringBuilder(); while(it.hasNext()) { sb.append( it.next().toString() ); if(it.hasNext()) { sb.append( separator ); } } return sb.toString(); } private static class MapIterable<FROM, TO> implements Iterable<TO> { private final Iterable<FROM> from; private final Function<? super FROM, ? extends TO> function; public MapIterable( Iterable<FROM> from, Function<? super FROM, ? extends TO> function ) { this.from = from; this.function = function; } @Override public Iterator<TO> iterator() { return new MapIterator<>( from.iterator(), function ); } static class MapIterator<FROM, TO> implements Iterator<TO> { private final Iterator<FROM> fromIterator; private final Function<? super FROM, ? extends TO> function; public MapIterator( Iterator<FROM> fromIterator, Function<? super FROM, ? extends TO> function ) { this.fromIterator = fromIterator; this.function = function; } @Override public boolean hasNext() { return fromIterator.hasNext(); } @Override public TO next() { FROM from = fromIterator.next(); return function.apply( from ); } @Override public void remove() { fromIterator.remove(); } } } private static class FilterIterable<T> implements Iterable<T> { private final Iterable<T> iterable; private final Predicate<? super T> specification; public FilterIterable( Iterable<T> iterable, Predicate<? super T> specification ) { this.iterable = iterable; this.specification = specification; } @Override public Iterator<T> iterator() { return new FilterIterator<>( iterable.iterator(), specification ); } static class FilterIterator<T> implements Iterator<T> { private final Iterator<T> iterator; private final Predicate<? super T> specification; private T currentValue; boolean finished = false; boolean nextConsumed = true; public FilterIterator( Iterator<T> iterator, Predicate<? super T> specification ) { this.specification = specification; this.iterator = iterator; } public boolean moveToNextValid() { boolean found = false; while ( !found && iterator.hasNext() ) { T currentValue = iterator.next(); boolean satisfies = specification.accept( currentValue ); if ( satisfies ) { found = true; this.currentValue = currentValue; nextConsumed = false; } } if ( !found ) { finished = true; } return found; } @Override public T next() { if ( !nextConsumed ) { nextConsumed = true; return currentValue; } else { if ( !finished ) { if ( moveToNextValid() ) { nextConsumed = true; return currentValue; } } } throw new NoSuchElementException( "This iterator is exhausted." ); } @Override public boolean hasNext() { return !finished && (!nextConsumed || moveToNextValid()); } @Override public void remove() { } } } private static class FlattenIterable<T, I extends Iterable<? extends T>> implements Iterable<T> { private final Iterable<I> iterable; public FlattenIterable( Iterable<I> iterable ) { this.iterable = iterable; } @Override public Iterator<T> iterator() { return new FlattenIterator<>( iterable.iterator() ); } static class FlattenIterator<T, I extends Iterable<? extends T>> implements Iterator<T> { private final Iterator<I> iterator; private Iterator<? extends T> currentIterator; public FlattenIterator( Iterator<I> iterator ) { this.iterator = iterator; currentIterator = null; } @Override public boolean hasNext() { if ( currentIterator == null ) { if ( iterator.hasNext() ) { I next = iterator.next(); currentIterator = next.iterator(); } else { return false; } } while ( !currentIterator.hasNext() && iterator.hasNext() ) { currentIterator = iterator.next().iterator(); } return currentIterator.hasNext(); } @Override public T next() { return currentIterator.next(); } @Override public void remove() { if ( currentIterator == null ) { throw new IllegalStateException(); } currentIterator.remove(); } } } private static class CacheIterable<T> implements Iterable<T> { private final Iterable<T> iterable; private Iterable<T> cache; private CacheIterable( Iterable<T> iterable ) { this.iterable = iterable; } @Override public Iterator<T> iterator() { if ( cache != null ) { return cache.iterator(); } final Iterator<T> source = iterable.iterator(); return new Iterator<T>() { List<T> iteratorCache = new ArrayList<>(); @Override public boolean hasNext() { boolean hasNext = source.hasNext(); if ( !hasNext ) { cache = iteratorCache; } return hasNext; } @Override public T next() { T next = source.next(); iteratorCache.add( next ); return next; } @Override public void remove() { } }; } } /** * Returns the index of the first occurrence of the specified element * in this iterable, or -1 if this iterable does not contain the element. * More formally, returns the lowest index <tt>i</tt> such that * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>, * or -1 if there is no such index. */ public static <T> int indexOf( T itemToFind, Iterable<T> iterable ) { if ( itemToFind == null ) { int index = 0; for ( T item : iterable ) { if ( item == null ) { return index; } index++; } } else { int index = 0; for ( T item : iterable ) { if ( itemToFind.equals( item ) ) { return index; } index++; } } return -1; } public static <T> Iterable<T> option( final T item ) { if ( item == null ) { return Collections.emptyList(); } return new Iterable<T>() { @Override public Iterator<T> iterator() { return new PrefetchingIterator<T>() { private boolean returned; @Override protected T fetchNextOrNull() { try { return !returned ? item : null; } finally { returned = true; } } }; } }; } @SuppressWarnings( "rawtypes" ) public static <T, S extends Comparable> Iterable<T> sort( Iterable<T> iterable, final Function<T, S> compareFunction ) { List<T> list = toList( iterable ); Collections.sort( list, new Comparator<T>() { @SuppressWarnings( "unchecked" ) @Override public int compare( T o1, T o2 ) { return compareFunction.apply( o1 ).compareTo( compareFunction.apply( o2 ) ); } } ); return list; } public static String join( String joinString, Iterable<?> iter ) { return join( joinString, iter.iterator() ); } public static String join( String joinString, Iterator<?> iter ) { StringBuilder sb = new StringBuilder(); while(iter.hasNext()) { sb.append( iter.next().toString() ); if(iter.hasNext()) { sb.append( joinString ); } } return sb.toString(); } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,323
private class MyIteratorWrapper extends IteratorWrapper<T, U> { public MyIteratorWrapper( Iterator<U> iteratorToWrap ) { super( iteratorToWrap ); } @Override protected T underlyingObjectToObject( U object ) { return IterableWrapper.this.underlyingObjectToObject( object ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IterableWrapper.java
5,324
public abstract class IterableWrapper<T, U> implements Iterable<T> { private Iterable<U> source; public IterableWrapper( Iterable<U> iterableToWrap ) { this.source = iterableToWrap; } protected abstract T underlyingObjectToObject( U object ); public Iterator<T> iterator() { return new MyIteratorWrapper( source.iterator() ); } private class MyIteratorWrapper extends IteratorWrapper<T, U> { public MyIteratorWrapper( Iterator<U> iteratorToWrap ) { super( iteratorToWrap ); } @Override protected T underlyingObjectToObject( U object ) { return IterableWrapper.this.underlyingObjectToObject( object ); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IterableWrapper.java
5,325
public class FirstItemIterableTest { @Test public void testEmptyIterator() throws Exception { final FirstItemIterable firstItemIterable = new FirstItemIterable(Collections.emptyList()); final Iterator empty = firstItemIterable.iterator(); assertEquals(false, empty.hasNext()); try { empty.next(); fail(); } catch(NoSuchElementException nse) {} assertEquals(null, firstItemIterable.getFirst()); } @Test public void testSingleIterator() throws Exception { final FirstItemIterable firstItemIterable = new FirstItemIterable(Collections.singleton(Boolean.TRUE)); final Iterator empty = firstItemIterable.iterator(); assertEquals(true, empty.hasNext()); assertEquals(Boolean.TRUE, empty.next()); assertEquals(Boolean.TRUE, firstItemIterable.getFirst()); assertEquals(false, empty.hasNext()); try { empty.next(); fail(); } catch(NoSuchElementException nse) {} assertEquals(Boolean.TRUE, firstItemIterable.getFirst()); } @Test public void testMultiIterator() throws Exception { final FirstItemIterable firstItemIterable = new FirstItemIterable(Arrays.asList(Boolean.TRUE,Boolean.FALSE)); final Iterator empty = firstItemIterable.iterator(); assertEquals(true, empty.hasNext()); assertEquals(Boolean.TRUE, empty.next()); assertEquals(Boolean.TRUE, firstItemIterable.getFirst()); assertEquals(true, empty.hasNext()); assertEquals(Boolean.FALSE, empty.next()); assertEquals(Boolean.TRUE, firstItemIterable.getFirst()); assertEquals(false, empty.hasNext()); try { empty.next(); fail(); } catch(NoSuchElementException nse) {} assertEquals(Boolean.TRUE, firstItemIterable.getFirst()); } }
false
community_kernel_src_test_java_org_neo4j_helpers_collection_FirstItemIterableTest.java
5,326
return new Iterator<T>() { @Override public boolean hasNext() { return pos == 0 || iterator.hasNext(); } @Override public T next() { if (pos < 0) throw new NoSuchElementException(); return pos++ == 0 ? first : iterator.next(); } @Override public void remove() { } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_FirstItemIterable.java
5,327
{ Set<T> items = new HashSet<>(); T nextItem; @Override public boolean hasNext() { while ( iterator.hasNext() ) { nextItem = iterator.next(); if ( items.add( nextItem ) ) { return true; } } return false; } @Override public T next() { if ( nextItem == null && !hasNext() ) { throw new NoSuchElementException(); } return nextItem; } @Override public void remove() { } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,328
{ @Override public Iterator<X> iterator() { Iterator<X> iterator = iterable.iterator(); for ( int i = 0; i < skip; i++ ) { if ( iterator.hasNext() ) { iterator.next(); } else { return Iterables.<X>empty().iterator(); } } return iterator; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,329
{ @Override public Iterator<T> iterator() { final Iterable<Iterator<T>> iterators = toList( map( new Function<Iterable<T>, Iterator<T>>() { @Override public Iterator<T> apply( Iterable<T> iterable ) { return iterable.iterator(); } }, asList(iterables) ) ); return new Iterator<T>() { Iterator<Iterator<T>> iterator; Iterator<T> iter; @Override public boolean hasNext() { for ( Iterator<T> iterator : iterators ) { if ( iterator.hasNext() ) { return true; } } return false; } @Override public T next() { if ( iterator == null ) { iterator = iterators.iterator(); } while ( iterator.hasNext() ) { iter = iterator.next(); if ( iter.hasNext() ) { return iter.next(); } } iterator = null; return next(); } @Override public void remove() { if ( iter != null ) { iter.remove(); } } }; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,330
static class FlattenIterator<T, I extends Iterable<? extends T>> implements Iterator<T> { private final Iterator<I> iterator; private Iterator<? extends T> currentIterator; public FlattenIterator( Iterator<I> iterator ) { this.iterator = iterator; currentIterator = null; } @Override public boolean hasNext() { if ( currentIterator == null ) { if ( iterator.hasNext() ) { I next = iterator.next(); currentIterator = next.iterator(); } else { return false; } } while ( !currentIterator.hasNext() && iterator.hasNext() ) { currentIterator = iterator.next().iterator(); } return currentIterator.hasNext(); } @Override public T next() { return currentIterator.next(); } @Override public void remove() { if ( currentIterator == null ) { throw new IllegalStateException(); } currentIterator.remove(); } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,331
{ @Override public T apply( T from ) { return itemClass.cast( from.clone() ); } }, items );
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,332
{ @Override public boolean hasNext() { return false; } @Override public int next() { throw new NoSuchElementException(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,333
{ @Override public boolean hasNext() { return false; } @Override public long next() { throw new NoSuchElementException(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,334
{ @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public void close() { // do nothing } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,335
{ long next = -1; boolean hasNext = false; { computeNext(); } @Override public boolean hasNext() { return hasNext; } @Override public long next() { if ( hasNext ) { long result = next; computeNext(); return result; } else { throw new NoSuchElementException(); } } private void computeNext() { while ( iterator.hasNext() ) { next = iterator.next(); if ( predicate.accept( next ) ) { hasNext = true; return; } } hasNext = false; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,336
public abstract class IteratorUtil { /** * Returns the given iterator's first element or {@code null} if no * element found. * * @param <T> the type of elements in {@code iterator}. * @param iterator the {@link Iterator} to get elements from. * @return the first element in the {@code iterator}, or {@code null} if no * element found. */ public static <T> T firstOrNull( Iterator<T> iterator ) { return iterator.hasNext() ? iterator.next() : null; } /** * Returns the given iterator's first element. If no element is found a * {@link NoSuchElementException} is thrown. * * @param <T> the type of elements in {@code iterator}. * @param iterator the {@link Iterator} to get elements from. * @return the first element in the {@code iterator}. * @throws NoSuchElementException if no element found. */ public static <T> T first( Iterator<T> iterator ) { return assertNotNull( iterator, firstOrNull( iterator ) ); } /** * Returns the given iterator's last element or {@code null} if no * element found. * * @param <T> the type of elements in {@code iterator}. * @param iterator the {@link Iterator} to get elements from. * @return the last element in the {@code iterator}, or {@code null} if no * element found. */ public static <T> T lastOrNull( Iterator<T> iterator ) { T result = null; while ( iterator.hasNext() ) { result = iterator.next(); } return result; } /** * Returns the given iterator's last element. If no element is found a * {@link NoSuchElementException} is thrown. * * @param <T> the type of elements in {@code iterator}. * @param iterator the {@link Iterator} to get elements from. * @return the last element in the {@code iterator}. * @throws NoSuchElementException if no element found. */ public static <T> T last( Iterator<T> iterator ) { return assertNotNull( iterator, lastOrNull( iterator ) ); } /** * Returns the given iterator's single element or {@code null} if no * element found. If there is more than one element in the iterator a * {@link NoSuchElementException} will be thrown. * * @param <T> the type of elements in {@code iterator}. * @param iterator the {@link Iterator} to get elements from. * @return the single element in {@code iterator}, or {@code null} if no * element found. * @throws NoSuchElementException if more than one element was found. */ public static <T> T singleOrNull( Iterator<T> iterator ) { return single( iterator, null ); } /** * Returns the given iterator's single element. If there are no elements * or more than one element in the iterator a {@link NoSuchElementException} * will be thrown. * * @param <T> the type of elements in {@code iterator}. * @param iterator the {@link Iterator} to get elements from. * @return the single element in the {@code iterator}. * @throws NoSuchElementException if there isn't exactly one element. */ public static <T> T single( Iterator<T> iterator ) { return assertNotNull( iterator, singleOrNull( iterator ) ); } /** * Returns the iterator's n:th item from the end of the iteration. * If the iterator has got less than n-1 items in it * {@link NoSuchElementException} is thrown. * * @param <T> the type of elements in {@code iterator}. * @param iterator the {@link Iterator} to get elements from. * @param n the n:th item from the end to get. * @return the iterator's n:th item from the end of the iteration. * @throws NoSuchElementException if the iterator contains less than n-1 items. */ public static <T> T fromEnd( Iterator<T> iterator, int n ) { return assertNotNull( iterator, fromEndOrNull( iterator, n ) ); } /** * Returns the iterator's n:th item from the end of the iteration. * If the iterator has got less than n-1 items in it {@code null} is returned. * * @param <T> the type of elements in {@code iterator}. * @param iterator the {@link Iterator} to get elements from. * @param n the n:th item from the end to get. * @return the iterator's n:th item from the end of the iteration, * or {@code null} if the iterator doesn't contain that many items. */ public static <T> T fromEndOrNull( Iterator<T> iterator, int n ) { Deque<T> trail = new ArrayDeque<>( n ); while ( iterator.hasNext() ) { if ( trail.size() > n ) { trail.removeLast(); } trail.addFirst( iterator.next() ); } return trail.size() == n + 1 ? trail.getLast() : null; } /** * Iterates over the full iterators, and checks equality for each item in them. Note that this * will consume the iterators. */ public static boolean iteratorsEqual( Iterator<?> first, Iterator<?> other ) { while ( true ) { if ( first.hasNext() && other.hasNext() ) { if ( !first.next().equals( other.next() ) ) { return false; } } else { return first.hasNext() == other.hasNext(); } } } private static <T> T assertNotNull( Iterator<T> iterator, T result ) { if ( result == null ) { throw new NoSuchElementException( "No element found in " + iterator ); } return result; } /** * Returns the given iterable's first element or {@code null} if no * element found. * * @param <T> the type of elements in {@code iterable}. * @param iterable the {@link Iterable} to get elements from. * @return the first element in the {@code iterable}, or {@code null} if no * element found. */ public static <T> T firstOrNull( Iterable<T> iterable ) { return firstOrNull( iterable.iterator() ); } /** * Returns the given iterable's first element. If no element is found a * {@link NoSuchElementException} is thrown. * * @param <T> the type of elements in {@code iterable}. * @param iterable the {@link Iterable} to get elements from. * @return the first element in the {@code iterable}. * @throws NoSuchElementException if no element found. */ public static <T> T first( Iterable<T> iterable ) { return first( iterable.iterator() ); } /** * Returns the given iterable's last element or {@code null} if no * element found. * * @param <T> the type of elements in {@code iterable}. * @param iterable the {@link Iterable} to get elements from. * @return the last element in the {@code iterable}, or {@code null} if no * element found. */ public static <T> T lastOrNull( Iterable<T> iterable ) { return lastOrNull( iterable.iterator() ); } /** * Returns the given iterable's last element. If no element is found a * {@link NoSuchElementException} is thrown. * * @param <T> the type of elements in {@code iterable}. * @param iterable the {@link Iterable} to get elements from. * @return the last element in the {@code iterable}. * @throws NoSuchElementException if no element found. */ public static <T> T last( Iterable<T> iterable ) { return last( iterable.iterator() ); } /** * Returns the given iterable's single element or {@code null} if no * element found. If there is more than one element in the iterable a * {@link NoSuchElementException} will be thrown. * * @param <T> the type of elements in {@code iterable}. * @param iterable the {@link Iterable} to get elements from. * @return the single element in {@code iterable}, or {@code null} if no * element found. * @throws NoSuchElementException if more than one element was found. */ public static <T> T singleOrNull( Iterable<T> iterable ) { return singleOrNull( iterable.iterator() ); } /** * Returns the given iterable's single element. If there are no elements * or more than one element in the iterable a {@link NoSuchElementException} * will be thrown. * * @param <T> the type of elements in {@code iterable}. * @param iterable the {@link Iterable} to get elements from. * @return the single element in the {@code iterable}. * @throws NoSuchElementException if there isn't exactly one element. */ public static <T> T single( Iterable<T> iterable ) { return single( iterable.iterator() ); } /** * Returns the given iterable's single element or {@code null} if no * element found. If there is more than one element in the iterable a * {@link NoSuchElementException} will be thrown. * * @param <T> the type of elements in {@code iterable}. * @param iterable the {@link Iterable} to get elements from. * @return the single element in {@code iterable}, or {@code null} if no * element found. * @throws NoSuchElementException if more than one element was found. */ public static <T> T single( Iterable<T> iterable, T itemIfNone ) { return single( iterable.iterator(), itemIfNone ); } /** * Returns the given iterator's single element or {@code itemIfNone} if no * element found. If there is more than one element in the iterator a * {@link NoSuchElementException} will be thrown. * * @param <T> the type of elements in {@code iterator}. * @param iterator the {@link Iterator} to get elements from. * @return the single element in {@code iterator}, or {@code itemIfNone} if no * element found. * @throws NoSuchElementException if more than one element was found. */ public static <T> T single( Iterator<T> iterator, T itemIfNone ) { try { T result = iterator.hasNext() ? iterator.next() : itemIfNone; if ( iterator.hasNext() ) { throw new NoSuchElementException( "More than one element in " + iterator + ". First element is '" + result + "' and the second element is '" + iterator.next() + "'" ); } return result; } finally { if ( iterator instanceof Resource ) { ((Resource) iterator).close(); } } } /** * Returns the given iterator's single element or {@code itemIfNone} if no * element found. If there is more than one element in the iterator a * {@link NoSuchElementException} will be thrown. * * @param iterator the {@link Iterator} to get elements from. * @return the single element in {@code iterator}, or {@code itemIfNone} if no * element found. * @throws NoSuchElementException if more than one element was found. */ public static long single( PrimitiveLongIterator iterator, long itemIfNone ) { try { if ( iterator.hasNext() ) { long result = iterator.next(); if ( iterator.hasNext() ) { throw new NoSuchElementException( "More than one element in " + iterator + ". First element is '" + result + "' and the second element is '" + iterator.next() + "'" ); } return result; } return itemIfNone; } finally { if ( iterator instanceof Resource ) { ((Resource) iterator).close(); } } } /** * Returns a new iterator with all elements found in the input iterator that are accepted by the given predicate * * @param predicate predicate to use for selecting elements * @param iterator input source of elements to be filtered * @return new iterator that contains exactly all elements from iterator that are accepted by predicate */ public static PrimitiveLongIterator filter( final PrimitiveLongPredicate predicate, final PrimitiveLongIterator iterator ) { return new PrimitiveLongIterator() { long next = -1; boolean hasNext = false; { computeNext(); } @Override public boolean hasNext() { return hasNext; } @Override public long next() { if ( hasNext ) { long result = next; computeNext(); return result; } else { throw new NoSuchElementException(); } } private void computeNext() { while ( iterator.hasNext() ) { next = iterator.next(); if ( predicate.accept( next ) ) { hasNext = true; return; } } hasNext = false; } }; } /** * Returns the iterator's n:th item from the end of the iteration. * If the iterator has got less than n-1 items in it * {@link NoSuchElementException} is thrown. * * @param <T> the type of elements in {@code iterator}. * @param iterable the {@link Iterable} to get elements from. * @param n the n:th item from the end to get. * @return the iterator's n:th item from the end of the iteration. * @throws NoSuchElementException if the iterator contains less than n-1 items. */ public static <T> T fromEnd( Iterable<T> iterable, int n ) { return fromEnd( iterable.iterator(), n ); } /** * Adds all the items in {@code iterator} to {@code collection}. * @param <C> the type of {@link Collection} to add to items to. * @param <T> the type of items in the collection and iterator. * @param iterator the {@link Iterator} to grab the items from. * @param collection the {@link Collection} to add the items to. * @return the {@code collection} which was passed in, now filled * with the items from {@code iterator}. */ public static <C extends Collection<T>,T> C addToCollection( Iterator<T> iterator, C collection ) { while ( iterator.hasNext() ) { collection.add( iterator.next() ); } return collection; } /** * Adds all the items in {@code iterator} to {@code collection}. * @param <C> the type of {@link Collection} to add to items to. * @param iterator the {@link Iterator} to grab the items from. * @param collection the {@link Collection} to add the items to. * @return the {@code collection} which was passed in, now filled * with the items from {@code iterator}. */ public static <C extends Collection<Long>> C addToCollection( PrimitiveLongIterator iterator, C collection ) { while ( iterator.hasNext() ) { collection.add( iterator.next() ); } return collection; } /** * Adds all the items in {@code iterator} to {@code collection}. * @param <C> the type of {@link Collection} to add to items to. * @param iterator the {@link Iterator} to grab the items from. * @param collection the {@link Collection} to add the items to. * @return the {@code collection} which was passed in, now filled * with the items from {@code iterator}. */ public static <C extends Collection<Integer>> C addToCollection( PrimitiveIntIterator iterator, C collection ) { while ( iterator.hasNext() ) { collection.add( iterator.next() ); } return collection; } /** * Adds all the items in {@code iterator} to {@code collection}. * @param <C> the type of {@link Collection} to add to items to. * @param <T> the type of items in the collection and iterator. * @param iterator the {@link Iterator} to grab the items from. * @param collection the {@link Collection} to add the items to. * @return the {@code collection} which was passed in, now filled * with the items from {@code iterator}. */ public static <C extends Collection<T>,T> C addToCollectionUnique( Iterator<T> iterator, C collection ) { while ( iterator.hasNext() ) { addUnique( collection, iterator.next() ); } return collection; } private static <T, C extends Collection<T>> void addUnique( C collection, T item ) { if ( !collection.add( item ) ) { throw new IllegalStateException( "Encountered an already added item:" + item + " when adding items uniquely to a collection:" + collection ); } } /** * Adds all the items in {@code iterator} to {@code collection}. * @param <C> the type of {@link Collection} to add to items to. * @param <T> the type of items in the collection and iterator. * @param iterable the {@link Iterator} to grab the items from. * @param collection the {@link Collection} to add the items to. * @return the {@code collection} which was passed in, now filled * with the items from {@code iterator}. */ public static <C extends Collection<T>,T> C addToCollection( Iterable<T> iterable, C collection ) { return addToCollection( iterable.iterator(), collection ); } /** * Adds all the items in {@code iterator} to {@code collection}. * @param <C> the type of {@link Collection} to add to items to. * @param <T> the type of items in the collection and iterator. * @param iterable the {@link Iterator} to grab the items from. * @param collection the {@link Collection} to add the items to. * @return the {@code collection} which was passed in, now filled * with the items from {@code iterator}. */ public static <C extends Collection<T>,T> C addToCollectionUnique( Iterable<T> iterable, C collection ) { return addToCollectionUnique( iterable.iterator(), collection ); } /** * Convenience method for looping over an {@link Iterator}. Converts the * {@link Iterator} to an {@link Iterable} by wrapping it in an * {@link Iterable} that returns the {@link Iterator}. It breaks the * contract of {@link Iterable} in that it returns the supplied iterator * instance for each call to {@code iterator()} on the returned * {@link Iterable} instance. This method exists to make it easy to use an * {@link Iterator} in a for-loop. * * @param <T> the type of items in the iterator. * @param iterator the iterator to expose as an {@link Iterable}. * @return the supplied iterator posing as an {@link Iterable}. */ public static <T> Iterable<T> loop( final Iterator<T> iterator ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return iterator; } }; } /** * Exposes {@code iterator} as an {@link Iterable}. It breaks the contract * of {@link Iterable} in that it returns the supplied iterator instance for * each call to {@code iterator()} on the returned {@link Iterable} * instance. This method mostly exists to make it easy to use an * {@link Iterator} in a for-loop. * * @param <T> the type of items in the iterator. * @param iterator the iterator to expose as an {@link Iterable}. * @return the supplied iterator posing as an {@link Iterable}. */ //@Deprecated * @deprecated use {@link #loop(Iterator) the loop method} instead. public static <T> Iterable<T> asIterable( final Iterator<T> iterator ) { return loop( iterator ); } /** * Counts the number of items in the {@code iterator} by looping * through it. * @param <T> the type of items in the iterator. * @param iterator the {@link Iterator} to count items in. * @return the number of found in {@code iterator}. */ public static <T> int count( Iterator<T> iterator ) { int result = 0; while ( iterator.hasNext() ) { iterator.next(); result++; } return result; } /** * Counts the number of items in the {@code iterable} by looping through it. * * @param <T> the type of items in the iterator. * @param iterable the {@link Iterable} to count items in. * @return the number of found in {@code iterator}. */ public static <T> int count( Iterable<T> iterable ) { return count( iterable.iterator() ); } /** * Creates a collection from an iterable. * * @param iterable The iterable to create the collection from. * @param <T> The generic type of both the iterable and the collection. * @return a collection containing all items from the iterable. */ public static <T> Collection<T> asCollection( Iterable<T> iterable ) { return addToCollection( iterable, new ArrayList<T>() ); } public static <T> Collection<T> asCollection( Iterator<T> iterable ) { return addToCollection( iterable, new ArrayList<T>() ); } public static <T> List<T> asList( Iterator<T> iterator ) { return addToCollection( iterator, new ArrayList<T>() ); } public static <T> List<T> asList( Iterable<T> iterator ) { return addToCollection( iterator, new ArrayList<T>() ); } /** * Creates a {@link Set} from an {@link Iterable}. * * @param iterable The items to create the set from. * @param <T> The generic type of items. * @return a set containing all items from the {@link Iterable}. */ public static <T> Set<T> asSet( Iterable<T> iterable ) { return addToCollection( iterable, new HashSet<T>() ); } public static <T> Set<T> asSet( Iterator<T> iterator ) { return addToCollection( iterator, new HashSet<T>() ); } /** * Creates a {@link Set} from an {@link Iterable}. * * @param iterable The items to create the set from. * @param <T> The generic type of items. * @return a set containing all items from the {@link Iterable}. */ public static <T> Set<T> asUniqueSet( Iterable<T> iterable ) { return addToCollectionUnique( iterable, new HashSet<T>() ); } /** * Creates a {@link Set} from an array of items. * * @param items the items to add to the set. * @return the {@link Set} containing the items. */ @SafeVarargs public static <T> Set<T> asSet( T... items ) { return new HashSet<>( Arrays.asList( items ) ); } public static <T> Set<T> emptySetOf( @SuppressWarnings("unused"/*just used as a type marker*/) Class<T> type ) { return Collections.emptySet(); } public static <T> List<T> emptyListOf( @SuppressWarnings("unused"/*just used as a type marker*/) Class<T> type ) { return Collections.emptyList(); } /** * Alias for asSet() */ @SafeVarargs public static <T> Set<T> set( T... items) { return asSet(items); } /** * Creates a {@link Set} from an array of items. * * @param items the items to add to the set. * @return the {@link Set} containing the items. */ @SafeVarargs public static <T> Set<T> asUniqueSet( T... items ) { HashSet<T> set = new HashSet<>(); for ( T item : items ) { addUnique( set, item ); } return set; } /** * Creates a {@link Set} from an array of items. * * @param items the items to add to the set. * @return the {@link Set} containing the items. */ public static <T> Set<T> asUniqueSet( Iterator<T> items ) { HashSet<T> set = new HashSet<>(); while( items.hasNext() ) { addUnique( set, items.next() ); } return set; } /** * Function for converting Enum to String */ @SuppressWarnings( "rawtypes" ) public final static Function<Enum, String> ENUM_NAME = new Function<Enum, String>() { @Override public String apply( Enum from ) { return from.name(); } }; /** * Converts an {@link Iterable} of enums to {@link Set} of their names. * * @param enums the enums to convert. * @return the set of enum names */ @SuppressWarnings( "rawtypes" ) public static Set<String> asEnumNameSet( Iterable<Enum> enums ) { return asSet( map( ENUM_NAME, enums ) ); } /** * Converts an enum class to to {@link Set} of the names of all valid enum values * * @param clazz enum class * @param <E> enum type bound * @return the set of enum names */ public static <E extends Enum<E>> Set<String> asEnumNameSet( Class<E> clazz) { return asSet( map( ENUM_NAME, allOf( clazz ) ) ); } /** * Creates an {@link Iterable} for iterating over the lines of a text file. * @param file the file to get the lines for. * @return an {@link Iterable} for iterating over the lines of a text file. */ public static ClosableIterable<String> asIterable( final File file, final String encoding ) { return new ClosableIterable<String>() { private ClosableIterator<String> mostRecentIterator; @Override public Iterator<String> iterator() { try { if ( mostRecentIterator != null ) { mostRecentIterator.close(); } mostRecentIterator = asIterator( file, encoding ); return mostRecentIterator; } catch ( IOException e ) { throw new RuntimeException( e ); } } @Override public void close() { if ( mostRecentIterator != null ) { mostRecentIterator.close(); } } }; } /** * Creates an {@link Iterator} for iterating over the lines of a text file. * The opened file is closed if an exception occurs during reading or when * the files has been read through all the way. * @param file the file to get the lines for. * @param encoding to be used for reading the file * @return an {@link Iterator} for iterating over the lines of a text file. */ public static ClosableIterator<String> asIterator( File file, String encoding ) throws IOException { return new LinesOfFileIterator( file, encoding ); } public static Iterable<Long> asIterable( final long... array ) { return new Iterable<Long>() { @Override public Iterator<Long> iterator() { return asIterator( array ); } }; } @SafeVarargs public static <T> Iterable<T> asIterable( final T... array ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return IteratorUtil.iterator( array ); } }; } public static Iterator<Long> asIterator( final long... array ) { return new PrefetchingIterator<Long>() { private int index; @Override protected Long fetchNextOrNull() { try { return index < array.length ? array[index] : null; } finally { index++; } } }; } public static PrimitiveLongIterator asPrimitiveIterator( final long... array ) { return new PrimitiveLongIteratorForArray( array ); } public static PrimitiveIntIterator asPrimitiveIterator( final int... array ) { return new PrimitiveIntIteratorForArray( array ); } @SafeVarargs public static <T> Iterator<T> asIterator( final int maxItems, final T... array ) { return new PrefetchingIterator<T>() { private int index; @Override protected T fetchNextOrNull() { try { return index < array.length && index < maxItems ? array[index] : null; } finally { index++; } } }; } @SafeVarargs public static <T> Iterator<T> iterator( T ... items ) { return asIterator( items.length, items ); } @SafeVarargs public static <T> Iterator<T> iterator( int maxItems, T ... items ) { return asIterator( maxItems, items ); } public static PrimitiveLongIterator singletonPrimitiveLongIterator( final long item ) { return new AbstractPrimitiveLongIterator() { { next( item ); } @Override protected void computeNext() { endReached(); } }; } @SuppressWarnings( "rawtypes" ) private static final ResourceIterator EMPTY_ITERATOR = new ResourceIterator() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public void close() { // do nothing } }; private static final PrimitiveLongIterator EMPTY_PRIMITIVE_LONG_ITERATOR = new PrimitiveLongIterator() { @Override public boolean hasNext() { return false; } @Override public long next() { throw new NoSuchElementException(); } }; private static final PrimitiveIntIterator EMPTY_PRIMITIVE_INT_ITERATOR = new PrimitiveIntIterator() { @Override public boolean hasNext() { return false; } @Override public int next() { throw new NoSuchElementException(); } }; @SuppressWarnings( "unchecked" ) public static <T> ResourceIterator<T> emptyIterator() { return EMPTY_ITERATOR; } public static PrimitiveLongIterator emptyPrimitiveLongIterator() { return EMPTY_PRIMITIVE_LONG_ITERATOR; } public static PrimitiveIntIterator emptyPrimitiveIntIterator() { return EMPTY_PRIMITIVE_INT_ITERATOR; } public static <T> boolean contains( Iterator<T> iterator, T item ) { try { for ( T element : loop( iterator ) ) { if ( item == null ? element == null : item.equals( element ) ) { return true; } } return false; } finally { if ( iterator instanceof ResourceIterator<?> ) { ((ResourceIterator<?>) iterator).close(); } } } public static boolean contains( PrimitiveLongIterator iterator, long item ) { try { while ( iterator.hasNext() ) { if ( item == iterator.next() ) { return true; } } return false; } finally { if ( iterator instanceof ResourceIterator<?> ) { ((ResourceIterator<?>) iterator).close(); } } } public static boolean contains( PrimitiveIntIterator iterator, int item ) { try { while ( iterator.hasNext() ) { if ( item == iterator.next() ) { return true; } } return false; } finally { if ( iterator instanceof ResourceIterator<?> ) { ((ResourceIterator<?>) iterator).close(); } } } public static <T extends CloneableInPublic> Iterable<T> cloned( Iterable<T> items, final Class<T> itemClass ) { return Iterables.map( new Function<T,T>() { @Override public T apply( T from ) { return itemClass.cast( from.clone() ); } }, items ); } public static <T> ResourceIterator<T> asResourceIterator( final Iterator<T> iterator ) { return new WrappingResourceIterator<>( iterator ); } @SuppressWarnings("UnusedDeclaration"/*Useful when debugging in tests, but not used outside of debugging sessions*/) public static Iterator<Long> toJavaIterator( final PrimitiveLongIterator primIterator ) { return new Iterator<Long>() { @Override public boolean hasNext() { return primIterator.hasNext(); } @Override public Long next() { return primIterator.next(); } @Override public void remove() { throw new UnsupportedOperationException( ); } }; } public static List<Long> primitivesList( PrimitiveLongIterator iterator ) { ArrayList<Long> result = new ArrayList<>(); while ( iterator.hasNext() ) { result.add( iterator.next() ); } return result; } public static Set<Long> asSet( PrimitiveLongIterator iterator ) { return internalAsSet( iterator, false ); } private static Set<Long> internalAsSet( PrimitiveLongIterator iterator, boolean allowDuplicates ) { Set<Long> set = new HashSet<>(); while ( iterator.hasNext() ) { long value = iterator.next(); if ( !set.add( value ) && !allowDuplicates ) { throw new IllegalStateException( "Duplicates found. Tried to add " + value + " to " + set ); } } return set; } public static Set<Integer> asSet( PrimitiveIntIterator iterator ) { Set<Integer> set = new HashSet<>(); while ( iterator.hasNext() ) { set.add( iterator.next() ); } return set; } /** * Creates a {@link Set} from an array of iterator. * * @param iterator the iterator to add to the set. * @return the {@link Set} containing the iterator. */ public static Set<Long> asUniqueSet( PrimitiveLongIterator iterator ) { HashSet<Long> set = new HashSet<>(); while ( iterator.hasNext() ) { addUnique( set, iterator.next() ); } return set; } public static PrimitiveLongIterator toPrimitiveLongIterator( final Iterator<Long> iterator ) { return new PrimitiveLongIterator() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public long next() { Long nextValue = iterator.next(); if ( null == nextValue ) { throw new IllegalArgumentException( "Cannot convert null Long to primitive long" ); } return nextValue; } }; } public static PrimitiveIntIterator toPrimitiveIntIterator( final Iterator<Integer> iterator ) { return new PrimitiveIntIterator() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public int next() { Integer nextValue = iterator.next(); if ( null == nextValue ) { throw new IllegalArgumentException( "Cannot convert null Long to primitive long" ); } return nextValue; } }; } public static PrimitiveLongIterator flatten( final Iterator<PrimitiveLongIterator> source ) { return new PrimitiveLongIterator() { private PrimitiveLongIterator current; @Override public boolean hasNext() { while ( current == null || !current.hasNext() ) { if ( !source.hasNext() ) { return false; } current = source.next(); } return true; } @Override public long next() { if ( !hasNext() ) { throw new NoSuchElementException(); } return current.next(); } }; } public static PrimitiveLongResourceIterator resourceIterator( final PrimitiveLongIterator iterator, final Resource resource ) { return new PrimitiveLongResourceIterator() { @Override public void close() { resource.close(); } @Override public long next() { return iterator.next(); } @Override public boolean hasNext() { return iterator.hasNext(); } }; } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,337
static class MapIterator<FROM, TO> implements Iterator<TO> { private final Iterator<FROM> fromIterator; private final Function<? super FROM, ? extends TO> function; public MapIterator( Iterator<FROM> fromIterator, Function<? super FROM, ? extends TO> function ) { this.fromIterator = fromIterator; this.function = function; } @Override public boolean hasNext() { return fromIterator.hasNext(); } @Override public TO next() { FROM from = fromIterator.next(); return function.apply( from ); } @Override public void remove() { fromIterator.remove(); } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,338
private static class MapIterable<FROM, TO> implements Iterable<TO> { private final Iterable<FROM> from; private final Function<? super FROM, ? extends TO> function; public MapIterable( Iterable<FROM> from, Function<? super FROM, ? extends TO> function ) { this.from = from; this.function = function; } @Override public Iterator<TO> iterator() { return new MapIterator<>( from.iterator(), function ); } static class MapIterator<FROM, TO> implements Iterator<TO> { private final Iterator<FROM> fromIterator; private final Function<? super FROM, ? extends TO> function; public MapIterator( Iterator<FROM> fromIterator, Function<? super FROM, ? extends TO> function ) { this.fromIterator = fromIterator; this.function = function; } @Override public boolean hasNext() { return fromIterator.hasNext(); } @Override public TO next() { FROM from = fromIterator.next(); return function.apply( from ); } @Override public void remove() { fromIterator.remove(); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,339
private static class FlattenIterable<T, I extends Iterable<? extends T>> implements Iterable<T> { private final Iterable<I> iterable; public FlattenIterable( Iterable<I> iterable ) { this.iterable = iterable; } @Override public Iterator<T> iterator() { return new FlattenIterator<>( iterable.iterator() ); } static class FlattenIterator<T, I extends Iterable<? extends T>> implements Iterator<T> { private final Iterator<I> iterator; private Iterator<? extends T> currentIterator; public FlattenIterator( Iterator<I> iterator ) { this.iterator = iterator; currentIterator = null; } @Override public boolean hasNext() { if ( currentIterator == null ) { if ( iterator.hasNext() ) { I next = iterator.next(); currentIterator = next.iterator(); } else { return false; } } while ( !currentIterator.hasNext() && iterator.hasNext() ) { currentIterator = iterator.next().iterator(); } return currentIterator.hasNext(); } @Override public T next() { return currentIterator.next(); } @Override public void remove() { if ( currentIterator == null ) { throw new IllegalStateException(); } currentIterator.remove(); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,340
{ @Override public Iterator<T> apply( Iterable<T> iterable ) { return iterable.iterator(); } }, asList(iterables) ) );
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,341
static class FilterIterator<T> implements Iterator<T> { private final Iterator<T> iterator; private final Predicate<? super T> specification; private T currentValue; boolean finished = false; boolean nextConsumed = true; public FilterIterator( Iterator<T> iterator, Predicate<? super T> specification ) { this.specification = specification; this.iterator = iterator; } public boolean moveToNextValid() { boolean found = false; while ( !found && iterator.hasNext() ) { T currentValue = iterator.next(); boolean satisfies = specification.accept( currentValue ); if ( satisfies ) { found = true; this.currentValue = currentValue; nextConsumed = false; } } if ( !found ) { finished = true; } return found; } @Override public T next() { if ( !nextConsumed ) { nextConsumed = true; return currentValue; } else { if ( !finished ) { if ( moveToNextValid() ) { nextConsumed = true; return currentValue; } } } throw new NoSuchElementException( "This iterator is exhausted." ); } @Override public boolean hasNext() { return !finished && (!nextConsumed || moveToNextValid()); } @Override public void remove() { } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,342
private static class FilterIterable<T> implements Iterable<T> { private final Iterable<T> iterable; private final Predicate<? super T> specification; public FilterIterable( Iterable<T> iterable, Predicate<? super T> specification ) { this.iterable = iterable; this.specification = specification; } @Override public Iterator<T> iterator() { return new FilterIterator<>( iterable.iterator(), specification ); } static class FilterIterator<T> implements Iterator<T> { private final Iterator<T> iterator; private final Predicate<? super T> specification; private T currentValue; boolean finished = false; boolean nextConsumed = true; public FilterIterator( Iterator<T> iterator, Predicate<? super T> specification ) { this.specification = specification; this.iterator = iterator; } public boolean moveToNextValid() { boolean found = false; while ( !found && iterator.hasNext() ) { T currentValue = iterator.next(); boolean satisfies = specification.accept( currentValue ); if ( satisfies ) { found = true; this.currentValue = currentValue; nextConsumed = false; } } if ( !found ) { finished = true; } return found; } @Override public T next() { if ( !nextConsumed ) { nextConsumed = true; return currentValue; } else { if ( !finished ) { if ( moveToNextValid() ) { nextConsumed = true; return currentValue; } } } throw new NoSuchElementException( "This iterator is exhausted." ); } @Override public boolean hasNext() { return !finished && (!nextConsumed || moveToNextValid()); } @Override public void remove() { } } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,343
{ List<T> iteratorCache = new ArrayList<>(); @Override public boolean hasNext() { boolean hasNext = source.hasNext(); if ( !hasNext ) { cache = iteratorCache; } return hasNext; } @Override public T next() { T next = source.next(); iteratorCache.add( next ); return next; } @Override public void remove() { } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,344
private static class CacheIterable<T> implements Iterable<T> { private final Iterable<T> iterable; private Iterable<T> cache; private CacheIterable( Iterable<T> iterable ) { this.iterable = iterable; } @Override public Iterator<T> iterator() { if ( cache != null ) { return cache.iterator(); } final Iterator<T> source = iterable.iterator(); return new Iterator<T>() { List<T> iteratorCache = new ArrayList<>(); @Override public boolean hasNext() { boolean hasNext = source.hasNext(); if ( !hasNext ) { cache = iteratorCache; } return hasNext; } @Override public T next() { T next = source.next(); iteratorCache.add( next ); return next; } @Override public void remove() { } }; } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,345
{ @Override @SuppressWarnings("unchecked") public TO apply( FROM from ) { return (TO) from; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,346
{ @Override public boolean hasNext() { return source.hasNext(); } @Override public T next() { return mapFunction.apply( source.next() ); } @Override public void remove() { throw new UnsupportedOperationException(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,347
{ @Override public boolean hasNext() { return source.hasNext(); } @Override public T next() { return mapFunction.apply( source.next() ); } @Override public void remove() { throw new UnsupportedOperationException(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,348
{ Iterator<Iterator<T>> iterator; Iterator<T> iter; @Override public boolean hasNext() { for ( Iterator<T> iterator : iterators ) { if ( iterator.hasNext() ) { return true; } } return false; } @Override public T next() { if ( iterator == null ) { iterator = iterators.iterator(); } while ( iterator.hasNext() ) { iter = iterator.next(); if ( iter.hasNext() ) { return iter.next(); } } iterator = null; return next(); } @Override public void remove() { if ( iter != null ) { iter.remove(); } } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Iterables.java
5,349
{ @Override public Iterator<T> iterator() { try { @SuppressWarnings("unchecked") Iterator<T> result = (Iterator<T>) providers.invoke( null, type ); return result; } catch ( Exception e ) { throw new RuntimeException( "Failed to invoke sun.misc.Service.providers(forClass)", e ); } } } );
false
community_kernel_src_main_java_org_neo4j_helpers_Service.java
5,350
{ @Override public Iterator<T> iterator() { return new PrefetchingIterator<T>() { final Iterator<T> iterator = iterable.iterator(); @Override protected T fetchNextOrNull() { while ( iterator.hasNext() ) { try { return iterator.next(); } catch ( Throwable e ) { } } return null; } }; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Service.java
5,351
static class SinglePartProgressListener extends ProgressListener { final Indicator indicator; private final long totalCount; private long value = 0; private int lastReported = 0; private boolean stared = false; SinglePartProgressListener( Indicator indicator, long totalCount ) { this.indicator = indicator; this.totalCount = totalCount; } @Override public void started() { if ( !stared ) { stared = true; indicator.startProcess( totalCount ); } } @Override public void set( long progress ) { update( value = progress ); } @Override public void add( long progress ) { update( value += progress ); } @Override public void done() { set( totalCount ); indicator.completeProcess(); } @Override public void failed( Throwable e ) { indicator.failure(e); } void update( long progress ) { started(); int current = totalCount == 0 ? 0 : (int) ((progress * indicator.reportResolution()) / totalCount); if ( current > lastReported ) { indicator.progress( lastReported, current ); lastReported = current; } } }
false
community_kernel_src_main_java_org_neo4j_helpers_progress_ProgressListener.java
5,352
@Ignore("A good idea but the test is too high level, is fragile and takes too long.") public class PullStormIT { @Rule public TargetDirectory.TestDirectory testDirectory = TargetDirectory.testDirForTest( getClass() ); @Rule public LoggerRule logger = new LoggerRule(); @Test public void testPullStorm() throws Throwable { // given ClusterManager clusterManager = new ClusterManager( ClusterManager.clusterWithAdditionalArbiters( 2, 1 ), testDirectory.directory(), stringMap( HaSettings.pull_interval.name(), "0", HaSettings.tx_push_factor.name(), "1") ); clusterManager.start(); try { ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster(); cluster.await( ClusterManager.masterAvailable( ) ); cluster.await( ClusterManager.masterSeesSlavesAsAvailable( 1 ) ); // Create data final HighlyAvailableGraphDatabase master = cluster.getMaster(); { System.out.println( "Creating data" ); Transaction tx = master.beginTx(); for ( int i = 0; i < 1000; i++ ) { master.createNode().setProperty( "foo", "bar" ); } tx.success(); tx.finish(); } // Slave goes down HighlyAvailableGraphDatabase slave = cluster.getAnySlave(); System.out.println( "Slave failed" ); ClusterManager.RepairKit repairKit = cluster.fail( slave ); // Create more data System.out.println( "Creating more data" ); for ( int i = 0; i < 1000; i++ ) { { Transaction tx = master.beginTx(); for ( int j = 0; j < 1000; j++ ) { master.createNode().setProperty( "foo", "bar" ); master.createNode().setProperty( "foo", "bar" ); } tx.success(); tx.finish(); } } // Slave comes back online System.out.println( "Slave comes up" ); repairKit.repair(); cluster.await( ClusterManager.masterSeesSlavesAsAvailable( 1 ) ); // when // Create 20 concurrent transactions System.out.println( "Pull storm" ); ExecutorService executor = Executors.newFixedThreadPool( 20 ); for ( int i = 0; i < 20; i++ ) { executor.submit( new Runnable() { @Override public void run() { Transaction tx = master.beginTx(); master.createNode().setProperty( "foo", "bar" ); tx.success(); tx.finish(); // This should cause lots of concurrent calls to pullUpdate() } } ); } executor.shutdown(); executor.awaitTermination( 1, TimeUnit.MINUTES ); System.out.println( "Pull storm done" ); // then long masterLastCommittedTxId = lastCommittedTxId( master ); for ( HighlyAvailableGraphDatabase member : cluster.getAllMembers() ) { assertEquals( masterLastCommittedTxId, lastCommittedTxId( member ) ); } } finally { System.err.println( "Shutting down" ); clusterManager.shutdown(); System.err.println( "Shut down" ); } } private long lastCommittedTxId( HighlyAvailableGraphDatabase highlyAvailableGraphDatabase ) { return ((NeoStoreXaDataSource)highlyAvailableGraphDatabase.getDependencyResolver() .resolveDependency( XaDataSourceManager.class ) .getXaDataSource( NeoStoreXaDataSource.DEFAULT_DATA_SOURCE_NAME )).getNeoStore().getLastCommittedTx(); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_PullStormIT.java
5,353
public class ForeignStoreIdIT { @Test public void emptyForeignDbShouldJoinAfterHavingItsEmptyDbDeleted() throws Exception { // GIVEN // -- one instance running firstInstance = new HighlyAvailableGraphDatabaseFactory() .newHighlyAvailableDatabaseBuilder( DIR.cleanDirectory( "1" ).getAbsolutePath() ) .setConfig( server_id, "1" ) .setConfig( cluster_server, "127.0.0.1:5001" ) .setConfig( ha_server, "127.0.0.1:6031" ) .setConfig( initial_hosts, "127.0.0.1:5001" ) .newGraphDatabase(); // -- another instance preparing to join with a store with a different store ID String foreignDbStoreDir = createAnotherStore( DIR.cleanDirectory( "2" ), 0 ); // WHEN // -- the other joins foreignInstance = new HighlyAvailableGraphDatabaseFactory() .newHighlyAvailableDatabaseBuilder( foreignDbStoreDir ) .setConfig( server_id, "2" ) .setConfig( initial_hosts, "127.0.0.1:5001" ) .setConfig( cluster_server, "127.0.0.1:5002" ) .setConfig( ha_server, "127.0.0.1:6032" ) .newGraphDatabase(); // -- and creates a node long foreignNode = createNode( foreignInstance, "foreigner" ); // THEN // -- that node should arrive at the master assertEquals( foreignNode, findNode( firstInstance, "foreigner" ) ); } @Test public void nonEmptyForeignDbShouldNotBeAbleToJoin() throws Exception { // GIVEN // -- one instance running firstInstance = new HighlyAvailableGraphDatabaseFactory() .newHighlyAvailableDatabaseBuilder( DIR.cleanDirectory( "1" ).getAbsolutePath() ) .setConfig( server_id, "1" ) .setConfig( initial_hosts, "127.0.0.1:5001" ) .setConfig( cluster_server, "127.0.0.1:5001" ) .setConfig( ha_server, "127.0.0.1:6041" ) .newGraphDatabase(); createNodes( firstInstance, 3, "first" ); // -- another instance preparing to join with a store with a different store ID String foreignDbStoreDir = createAnotherStore( DIR.cleanDirectory( "2" ), 1 ); // WHEN // -- the other joins foreignInstance = new HighlyAvailableGraphDatabaseFactory() .newHighlyAvailableDatabaseBuilder( foreignDbStoreDir ) .setConfig( server_id, "2" ) .setConfig( initial_hosts, "127.0.0.1:5001" ) .setConfig( cluster_server, "127.0.0.1:5002" ) .setConfig( ha_server, "127.0.0.1:6042" ) .setConfig( state_switch_timeout, "5s" ) .newGraphDatabase(); try { // THEN // -- that node should arrive at the master createNode( foreignInstance, "foreigner" ); fail( "Shouldn't be able to create a node, since it shouldn't have joined" ); } catch ( Exception e ) { // Good } } private final TargetDirectory DIR = TargetDirectory.forTest( getClass() ); private GraphDatabaseService firstInstance, foreignInstance; @After public void after() throws Exception { if ( foreignInstance != null ) foreignInstance.shutdown(); if ( firstInstance != null ) firstInstance.shutdown(); } private long findNode( GraphDatabaseService db, String name ) { Transaction transaction = db.beginTx(); try { for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() ) if ( name.equals( node.getProperty( "name", null ) ) ) return node.getId(); fail( "Didn't find node '" + name + "' in " + db ); return -1; // will never happen } finally { transaction.finish(); } } private String createAnotherStore( File directory, int transactions ) { String storeDir = directory.getAbsolutePath(); GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir ); createNodes( db, transactions, "node" ); db.shutdown(); return storeDir; } private void createNodes( GraphDatabaseService db, int transactions, String prefix ) { for ( int i = 0; i < transactions; i++ ) createNode( db, prefix + i ); } private long createNode( GraphDatabaseService db, String name ) { Transaction tx = db.beginTx(); try { Node node = db.createNode(); node.setProperty( "name", name ); tx.success(); return node.getId(); } finally { tx.finish(); } } }
false
enterprise_ha_src_test_java_org_neo4j_ha_ForeignStoreIdIT.java
5,354
public class FinishTx implements WorkerCommand<HighlyAvailableGraphDatabase, Void> { private final Transaction tx; private final boolean successful; public FinishTx( Transaction tx, boolean successful ) { this.tx = tx; this.successful = successful; } @Override public Void doWork( HighlyAvailableGraphDatabase state ) { if ( successful ) tx.success(); tx.finish(); return null; } }
false
enterprise_ha_src_test_java_org_neo4j_ha_FinishTx.java
5,355
public class DefaultElectionCredentialsTest { @Test public void testCompareToDifferentTxId() throws Exception { DefaultElectionCredentials highTxId = new DefaultElectionCredentials( 3, 12, false ); DefaultElectionCredentials mediumTxId = new DefaultElectionCredentials( 1, 11, false ); DefaultElectionCredentials lowTxId = new DefaultElectionCredentials( 2, 10, false ); List<ElectionCredentials> toSort = new ArrayList<ElectionCredentials>( 2 ); toSort.add( mediumTxId); toSort.add( highTxId); toSort.add( lowTxId ); Collections.sort( toSort ); assertEquals(toSort.get( 0 ), lowTxId); assertEquals(toSort.get( 1 ), mediumTxId); assertEquals(toSort.get( 2 ), highTxId); } @Test public void testCompareToSameTxId() throws Exception { // Lower id means higher priority DefaultElectionCredentials highSameTxId = new DefaultElectionCredentials( 1, 10, false ); DefaultElectionCredentials lowSameTxId = new DefaultElectionCredentials( 2, 10, false ); List<ElectionCredentials> toSort = new ArrayList<ElectionCredentials>( 2 ); toSort.add( highSameTxId ); toSort.add(lowSameTxId); Collections.sort( toSort ); assertEquals(toSort.get( 0 ), lowSameTxId); assertEquals(toSort.get( 1 ), highSameTxId); } @Test public void testExistingMasterLosesWhenComparedToHigherTxIdHigherId() { DefaultElectionCredentials currentMaster = new DefaultElectionCredentials( 1, 10, true ); DefaultElectionCredentials incoming = new DefaultElectionCredentials( 2, 11, false ); List<ElectionCredentials> toSort = new ArrayList<ElectionCredentials>( 2 ); toSort.add( currentMaster ); toSort.add( incoming ); Collections.sort( toSort ); assertEquals( toSort.get( 0 ), currentMaster ); assertEquals( toSort.get( 1 ), incoming ); } @Test public void testExistingMasterWinsWhenComparedToLowerIdSameTxId() { DefaultElectionCredentials currentMaster = new DefaultElectionCredentials( 2, 10, true ); DefaultElectionCredentials incoming = new DefaultElectionCredentials( 1, 10, false ); List<ElectionCredentials> toSort = new ArrayList<ElectionCredentials>( 2 ); toSort.add( currentMaster ); toSort.add( incoming ); Collections.sort( toSort ); assertEquals( toSort.get( 0 ), incoming ); assertEquals( toSort.get( 1 ), currentMaster ); } @Test public void testExistingMasterWinsWhenComparedToHigherIdLowerTxId() { DefaultElectionCredentials currentMaster = new DefaultElectionCredentials( 1, 10, true ); DefaultElectionCredentials incoming = new DefaultElectionCredentials( 2, 9, false ); List<ElectionCredentials> toSort = new ArrayList<ElectionCredentials>( 2 ); toSort.add( currentMaster ); toSort.add( incoming ); Collections.sort( toSort ); assertEquals( toSort.get( 0 ), incoming ); assertEquals( toSort.get( 1 ), currentMaster ); } @Test public void testEquals() throws Exception { DefaultElectionCredentials sameAsNext = new DefaultElectionCredentials( 1, 10, false ); DefaultElectionCredentials sameAsPrevious = new DefaultElectionCredentials( 1, 10, false ); assertEquals( sameAsNext, sameAsPrevious ); assertEquals( sameAsNext, sameAsNext ); DefaultElectionCredentials differentTxIdFromNext = new DefaultElectionCredentials( 1, 11, false ); DefaultElectionCredentials differentTxIdFromPrevious = new DefaultElectionCredentials( 1, 10, false ); assertFalse( differentTxIdFromNext.equals( differentTxIdFromPrevious ) ); assertFalse( differentTxIdFromPrevious.equals( differentTxIdFromNext ) ); DefaultElectionCredentials differentURIFromNext = new DefaultElectionCredentials( 1, 11, false ); DefaultElectionCredentials differentURIFromPrevious = new DefaultElectionCredentials( 2, 11, false ); assertFalse( differentTxIdFromNext.equals( differentURIFromPrevious ) ); assertFalse( differentTxIdFromPrevious.equals( differentURIFromNext ) ); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_DefaultElectionCredentialsTest.java
5,356
@Ignore("Not a test") public class CreateEmptyDb { public static void main( String[] args ) { at( args[0] ); } public static void at( String storeDir ) { new GraphDatabaseFactory().newEmbeddedDatabase( storeDir ).shutdown(); } public static void at( File storeDir ) { at( storeDir.getAbsolutePath() ); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_CreateEmptyDb.java
5,357
public class ConstraintsInHAIT { @Test public void creatingConstraintOnSlaveIsNotAllowed() throws Exception { // given ClusterManager.ManagedCluster cluster = clusterRule.startCluster(); HighlyAvailableGraphDatabase slave = cluster.getAnySlave(); slave.beginTx(); try { ConstraintCreator constraintCreator = slave.schema() .constraintFor( DynamicLabel.label( "LabelName" ) ).assertPropertyIsUnique( "PropertyName" ); // when constraintCreator.create(); fail( "should have thrown exception" ); } catch ( InvalidTransactionTypeException e ) { assertThat(e.getMessage(), equalTo("Modifying the database schema can only be done on the master server, " + "this server is a slave. Please issue schema modification commands directly to the master.")); } } @Rule public ClusterRule clusterRule = new ClusterRule( getClass() ); }
false
enterprise_ha_src_test_java_org_neo4j_ha_ConstraintsInHAIT.java
5,358
{ @Override public void notifyStatusChanged( Object instance, LifecycleStatus from, LifecycleStatus to ) { if ( instance.getClass().getName().contains( "DatabaseAvailability" ) && to == LifecycleStatus .STOPPED ) { result.run(); } } } );
false
enterprise_ha_src_test_java_org_neo4j_ha_ClusterTransactionTest.java
5,359
{ @Override public Boolean call() throws Exception { try ( Transaction tx = slave.beginTx() ) { tx.acquireWriteLock( slave.getNodeById( 0 ) ); // Fail return false; } catch ( Exception e ) { // Ok! return true; } } } );
false
enterprise_ha_src_test_java_org_neo4j_ha_ClusterTransactionTest.java
5,360
public class ClusterTransactionTest { @Test public void givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave() throws Throwable { // Given ClusterManager clusterManager = new ClusterManager( fromXml( getClass().getResource( "/threeinstances.xml" ) .toURI() ), TargetDirectory.forTest( getClass() ).cleanDirectory( "testCluster" ), MapUtil.stringMap( HaSettings.ha_server.name(), ":6001-6005", HaSettings.tx_push_factor.name(), "2" ) ); try { clusterManager.start(); clusterManager.getDefaultCluster().await( ClusterManager.allSeesAllAsAvailable() ); GraphDatabaseAPI master = clusterManager.getDefaultCluster().getMaster(); final GraphDatabaseAPI slave = clusterManager.getDefaultCluster().getAnySlave(); // When final FutureTask<Boolean> result = new FutureTask<Boolean>( new Callable() { @Override public Boolean call() throws Exception { try ( Transaction tx = slave.beginTx() ) { tx.acquireWriteLock( slave.getNodeById( 0 ) ); // Fail return false; } catch ( Exception e ) { // Ok! return true; } } } ); master.getDependencyResolver().resolveDependency( LifeSupport.class ).addLifecycleListener( new LifecycleListener() { @Override public void notifyStatusChanged( Object instance, LifecycleStatus from, LifecycleStatus to ) { if ( instance.getClass().getName().contains( "DatabaseAvailability" ) && to == LifecycleStatus .STOPPED ) { result.run(); } } } ); master.shutdown(); // Then Assert.assertThat( result.get(), CoreMatchers.equalTo( true ) ); } finally { clusterManager.stop(); } } }
false
enterprise_ha_src_test_java_org_neo4j_ha_ClusterTransactionTest.java
5,361
public class BeginTx implements WorkerCommand<HighlyAvailableGraphDatabase, Transaction> { @Override public Transaction doWork( HighlyAvailableGraphDatabase state ) { return state.beginTx(); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_BeginTx.java
5,362
{ @Override protected void config( GraphDatabaseBuilder builder, String clusterName, int serverId ) { builder.setConfig( OnlineBackupSettings.online_backup_server, (":"+(4444 + serverId) )); } };
false
enterprise_ha_src_test_java_org_neo4j_ha_BackupHaIT.java
5,363
@Ignore("Breaks occasionally, needs investigation") public class BackupHaIT { private DbRepresentation representation; private ClusterManager clusterManager; private ManagedCluster cluster; @Before public void startCluster() throws Throwable { FileUtils.deleteDirectory( PATH ); FileUtils.deleteDirectory( BACKUP_PATH ); clusterManager = new ClusterManager( fromXml( getClass().getResource( "/threeinstances.xml" ).toURI() ), PATH, MapUtil.stringMap( OnlineBackupSettings.online_backup_enabled.name(), Settings.TRUE ) ) { @Override protected void config( GraphDatabaseBuilder builder, String clusterName, int serverId ) { builder.setConfig( OnlineBackupSettings.online_backup_server, (":"+(4444 + serverId) )); } }; clusterManager.start(); cluster = clusterManager.getDefaultCluster(); // Really doesn't matter which instance representation = createSomeData( cluster.getMaster() ); } @After public void stopCluster() throws Throwable { clusterManager.stop(); clusterManager.shutdown(); } @Test public void makeSureBackupCanBePerformedFromClusterWithDefaultName() throws Throwable { testBackupFromCluster( null ); } @Test public void makeSureBackupCanBePerformedFromWronglyNamedCluster() throws Throwable { assertEquals( 0, runBackupToolFromOtherJvmToGetExitCode( backupArguments( "ha://localhost:5001", BACKUP_PATH.getPath(), "non.existent" ) ) ); } private void testBackupFromCluster( String askForCluster ) throws Throwable { assertEquals( 0, runBackupToolFromOtherJvmToGetExitCode( backupArguments( "ha://localhost:5001", BACKUP_PATH.getPath(), askForCluster ) ) ); assertEquals( representation, DbRepresentation.of( BACKUP_PATH ) ); ManagedCluster cluster = clusterManager.getCluster( askForCluster == null ? "neo4j.ha" : askForCluster ); DbRepresentation newRepresentation = createSomeData( cluster.getAnySlave() ); assertEquals( 0, runBackupToolFromOtherJvmToGetExitCode( backupArguments( "ha://localhost:5001", BACKUP_PATH.getPath(), askForCluster ) ) ); assertEquals( newRepresentation, DbRepresentation.of( BACKUP_PATH ) ); } private String[] backupArguments( String from, String to, String clusterName ) { List<String> args = new ArrayList<String>(); args.add( "-from" ); args.add( from ); args.add( "-to" ); args.add( to ); if ( clusterName != null ) { args.add( "-cluster" ); args.add( clusterName ); } return args.toArray( new String[args.size()] ); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_BackupHaIT.java
5,364
@Deprecated public class RegexPattern extends AbstractFilterExpression { private final Pattern pattern; /** * Constructs a new regex pattern for filtering. * * @param label the {@link PatternNode} label. * @param property the property key to filter in. * @param pattern the pattern which the value should match. * @param options options for regex matching. */ public RegexPattern( String label, String property, String pattern, String options ) { super( label, property ); int op = 0; op |= hasOption( options, 'i' ) ? Pattern.CASE_INSENSITIVE : 0; this.pattern = Pattern.compile( pattern, op ); } public boolean matches( FilterValueGetter valueGetter ) { Object values[] = valueGetter.getValues( getLabel() ); for ( Object value : values ) { boolean matches = this.pattern.matcher( value.toString() ).find(); if ( matches ) { return true; } } return false; } private static boolean hasOption( String options, char option ) { return options != null && options.indexOf( option ) > -1; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_filter_RegexPattern.java
5,365
@Deprecated public class FilterBinaryNode implements FilterExpression { private FilterExpression e1; private FilterExpression e2; private boolean trueForAnd; /** * Constructs a new binary node which has two expressions, grouped together * as one. * @param expression1 the first expression. * @param trueForAnd {@code true} if AND, else OR. * @param expression2 the second expression. */ public FilterBinaryNode( FilterExpression expression1, boolean trueForAnd, FilterExpression expression2 ) { this.e1 = expression1; this.e2 = expression2; this.trueForAnd = trueForAnd; } public boolean matches( FilterValueGetter valueGetter ) { return this.trueForAnd ? this.e1.matches( valueGetter ) && this.e2.matches( valueGetter ) : this.e1.matches( valueGetter ) || this.e2.matches( valueGetter ); } /** * @return the first expression of the two. */ public FilterExpression getLeftExpression() { return this.e1; } /** * @return the second expression of the two. */ public FilterExpression getRightExpression() { return this.e2; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_filter_FilterBinaryNode.java
5,366
@Deprecated public class CompareExpression extends AbstractFilterExpression { private final String operator; private final Object compareValue; /** * Constructs a new comparison expression. * @param label the {@link PatternNode} label. * @param property property key. * @param operator operator, f.ex. >= or < or = * @param value value to compare against. */ public CompareExpression( String label, String property, String operator, Object value ) { super( label, property ); this.operator = operator; this.compareValue = value; } public boolean matches( FilterValueGetter valueGetter ) { for ( Object value : valueGetter.getValues( getLabel() ) ) { int comparison = 0; try { comparison = ( ( Comparable<Object> ) value ).compareTo( ( ( Comparable<Object> ) this.compareValue ) ); } catch ( Exception e ) { comparison = value.toString().compareTo( this.compareValue.toString() ); } boolean match = false; if ( operator.equals( "<" ) ) { match = comparison < 0; } else if ( operator.equals( "<=" ) ) { match = comparison <= 0; } else if ( operator.equals( "=" ) ) { match = comparison == 0; } else if ( operator.equals( ">=" ) ) { match = comparison >= 0; } else if ( operator.equals( ">" ) ) { match = comparison > 0; } if ( match ) { return true; } } return false; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_filter_CompareExpression.java
5,367
@Deprecated public abstract class AbstractFilterExpression implements FilterExpression { private final String label; private final String property; /** * Constructs a new filter expression. * @param label the {@link PatternNode} label. * @param property the property key. */ public AbstractFilterExpression( String label, String property ) { this.label = label; this.property = property; } /** * @return The {@link PatternNode} label. */ public String getLabel() { return this.label; } /** * @return the property key. */ public String getProperty() { return this.property; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_filter_AbstractFilterExpression.java
5,368
@Deprecated public class PatternUtil { /** * Print a pattern graph rooted at a particular {@link PatternNode} to the * specified {@link PrintStream}. * * @param startNode the root of the pattern graph. * @param out the stream to print to. */ public static void printGraph( PatternNode startNode, PrintStream out ) { printGraph( startNode, "", new HashSet<PatternNode>(), out ); } private static void printGraph( PatternNode startNode, String prefix, Set<PatternNode> visited, PrintStream out ) { visited.add( startNode ); out.println( prefix + startNode + ": " ); for ( PatternRelationship relationship : startNode.getAllRelationships() ) { out.print( prefix + "\t" + relationship ); out.println( ": " + relationship.getOtherNode( startNode ) ); if ( !visited.contains( relationship.getOtherNode( startNode ) ) ) { printGraph( relationship.getOtherNode( startNode ), prefix + "\t\t", visited, out ); } } } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternUtil.java
5,369
@Deprecated public class PatternRelationship extends AbstractPatternObject<Relationship> { private final RelationshipType type; private final boolean directed; private final boolean optional; private final boolean anyType; private final PatternNode firstNode; private final PatternNode secondNode; private boolean isMarked = false; PatternRelationship( PatternNode firstNode, PatternNode secondNode, boolean optional, boolean directed ) { this.directed = directed; this.anyType = true; this.firstNode = firstNode; this.secondNode = secondNode; this.optional = optional; this.type = null; } PatternRelationship( RelationshipType type, PatternNode firstNode, PatternNode secondNode, boolean optional, boolean directed ) { this.directed = directed; this.anyType = false; this.type = type; this.firstNode = firstNode; this.secondNode = secondNode; this.optional = optional; } boolean anyRelType() { return anyType; } /** * Get the {@link PatternNode} that this pattern relationship relates, that * is not the specified node. * * @param node one of the {@link PatternNode}s this pattern relationship * relates. * @return the other pattern node. */ public PatternNode getOtherNode( PatternNode node ) { if ( node == firstNode ) { return secondNode; } if ( node == secondNode ) { return firstNode; } throw new RuntimeException( "Node[" + node + "] not in this relationship" ); } /** * Get the first pattern node that this pattern relationship relates. * * @return the first pattern node. */ public PatternNode getFirstNode() { return firstNode; } /** * Get the second pattern node that this pattern relationship relates. * * @return the second pattern node. */ public PatternNode getSecondNode() { return secondNode; } /** * Does this pattern relationship represent a relationship that has to exist * in the subgraph to consider the subgraph a match of the pattern, or is it * an optional relationship. * * @return <code>true</code> if this pattern relationship represents an * optional relationship, <code>false</code> if it represents a * required relationship. */ public boolean isOptional() { return optional; } void mark() { isMarked = true; } void unMark() { isMarked = false; } boolean isMarked() { return isMarked; } /** * Get the {@link RelationshipType} a relationship must have in order to * match this pattern relationship. Will return <code>null</code> if a * relationship with any {@link RelationshipType} will match. * * @return the {@link RelationshipType} of this relationship pattern. */ public RelationshipType getType() { return type; } /** * Get the direction in which relationships are discovered using this * relationship pattern from the specified node. May be * {@link Direction#OUTGOING outgoing}, {@link Direction#INCOMING incoming}, * or {@link Direction#BOTH both}. * * @param fromNode the pattern node to find the direction of this pattern * relationship from. * @return the direction to discover relationships matching this pattern in. */ public Direction getDirectionFrom( PatternNode fromNode ) { if ( !directed ) { return Direction.BOTH; } if ( fromNode.equals( firstNode ) ) { return Direction.OUTGOING; } if ( fromNode.equals( secondNode ) ) { return Direction.INCOMING; } throw new RuntimeException( fromNode + " not in " + this ); } @Override public String toString() { return type + ":" + optional; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternRelationship.java
5,370
@Deprecated class PatternPosition { private Node currentNode; private PatternNode pNode; private Iterator<PatternRelationship> itr; private PatternRelationship nextPRel = null; private PatternRelationship previous = null; private PatternRelationship returnPrevious = null; private boolean optional = false; private PatternRelationship fromPRel = null; private Relationship fromRel = null; PatternPosition( Node currentNode, PatternNode pNode, boolean optional ) { this.currentNode = currentNode; this.pNode = pNode; itr = pNode.getRelationships( optional ).iterator(); this.optional = optional; } PatternPosition( Node currentNode, PatternNode pNode, PatternRelationship fromPRel, Relationship fromRel, boolean optional ) { this.currentNode = currentNode; this.pNode = pNode; itr = pNode.getRelationships( optional ).iterator(); this.optional = optional; this.fromPRel = fromPRel; this.fromRel = fromRel; } Node getCurrentNode() { return currentNode; } private void setNextQRel() { while ( itr.hasNext() ) { nextPRel = itr.next(); if ( !nextPRel.isMarked() ) { return; } nextPRel = null; } } PatternNode getPatternNode() { return pNode; } boolean hasNext() { if ( returnPrevious != null ) { return true; } if ( nextPRel == null ) { setNextQRel(); } return nextPRel != null; } PatternRelationship next() { if ( returnPrevious != null ) { PatternRelationship relToReturn = returnPrevious; returnPrevious = null; return relToReturn; } if ( nextPRel == null ) { setNextQRel(); } else { return resetNextPRel(); } if ( nextPRel == null ) { throw new NoSuchElementException(); } return resetNextPRel(); } private PatternRelationship resetNextPRel() { PatternRelationship relToReturn = nextPRel; previous = nextPRel; nextPRel = null; return relToReturn; } void reset() { returnPrevious = null; previous = null; nextPRel = null; itr = pNode.getRelationships( optional ).iterator(); } public void returnPreviousAgain() { returnPrevious = previous; } @Override public String toString() { return pNode.toString(); } public PatternRelationship fromPatternRel() { return fromPRel; } public Relationship fromRelationship() { return fromRel; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternPosition.java
5,371
@Deprecated public class PatternNode extends AbstractPatternObject<Node> { /** * The default {@link PatternGroup}. */ // Should this really EVER be used? - mutable global state!!!! public static final PatternGroup DEFAULT_PATTERN_GROUP = new PatternGroup() /*{ @Override public void addFilter( FilterExpression regexRepression ) { throw new UnsupportedOperationException( "Cannot add filter to default pattern group." ); }; }*/; private LinkedList<PatternRelationship> relationships = new LinkedList<PatternRelationship>(); private LinkedList<PatternRelationship> optionalRelationships = new LinkedList<PatternRelationship>(); private final PatternGroup group; /** * Create a new pattern node in the default {@link PatternGroup} with a * blank label. */ public PatternNode() { this( DEFAULT_PATTERN_GROUP, "" ); } /** * Create a new pattern node in the default {@link PatternGroup} with the * specified label. * * @param label the label of this pattern node. */ public PatternNode( String label ) { this( DEFAULT_PATTERN_GROUP, label ); } /** * Create a new pattern node in the specified {@link PatternGroup} with a * blank label. * * @param group the {@link PatternGroup} of this pattern node. */ public PatternNode( PatternGroup group ) { this( group, "" ); } /** * Create a new pattern node in the specified {@link PatternGroup} with the * specified label. * * @param group the {@link PatternGroup} of this pattern node. * @param label the label of this pattern node. */ public PatternNode( PatternGroup group, String label ) { this.group = group; this.label = label; } /** * Get the {@link PatternGroup} of this pattern node. * * @return the {@link PatternGroup} this pattern node belongs to. */ public PatternGroup getGroup() { return this.group; } /** * Get all {@link PatternRelationship}s associated with this pattern node. * This includes both the required and the optional * {@link PatternRelationship}s. * * @return the {@link PatternRelationship}s associated with this pattern * node. */ public Iterable<PatternRelationship> getAllRelationships() { LinkedList<PatternRelationship> allRelationships = new LinkedList<PatternRelationship>(); allRelationships.addAll( relationships ); allRelationships.addAll( optionalRelationships ); return allRelationships; } /** * Get the optional or the required {@link PatternRelationship}s associated * with this pattern node. * * @param optional if <code>true</code> return only the optional * {@link PatternRelationship}s, else return only the required. * @return the set of optional or required {@link PatternRelationship}s. */ public Iterable<PatternRelationship> getRelationships( boolean optional ) { return optional ? optionalRelationships : relationships; } void addRelationship( PatternRelationship relationship, boolean optional ) { if ( optional ) { optionalRelationships.add( relationship ); } else { relationships.add( relationship ); } } void removeRelationship( PatternRelationship relationship, boolean optional ) { if ( optional ) { optionalRelationships.remove( relationship ); } else { relationships.remove( relationship ); } } /** * Create a directed, required {@link PatternRelationship} from this node, * to the specified other node. * * @param otherNode the node at the other end of the relationship. * @return the newly created {@link PatternRelationship}. */ public PatternRelationship createRelationshipTo( PatternNode otherNode ) { return this.createRelationshipTo( otherNode, false, true ); } /** * Create a required {@link PatternRelationship} between this node and the * specified other node, with the specified direction. * * @param otherNode the node at the other end of the relationship. * @param dir the direction of the relationship. Use * {@link Direction#OUTGOING} to create a relationship from this * node to the other node. Use {@link Direction#INCOMING} to * create a relationship from the other node to this node. Use * {@link Direction#BOTH} to create a relationship where the * direction does not matter. * @return the newly created {@link PatternRelationship}. */ public PatternRelationship createRelationshipTo( PatternNode otherNode, Direction dir ) { if ( dir == Direction.INCOMING ) return otherNode.createRelationshipTo( this ); return this.createRelationshipTo( otherNode, false, dir == Direction.BOTH ? false : true ); } /** * Create a directed, required {@link PatternRelationship} of the specified * {@link RelationshipType} from this node to the specified other node. * * @param otherNode the node at the other end of the relationship. * @param type the {@link RelationshipType} of the relationship. * @return the newly created {@link PatternRelationship}. */ public PatternRelationship createRelationshipTo( PatternNode otherNode, RelationshipType type ) { return this.createRelationshipTo( otherNode, type, false, true ); } /** * Create a required {@link PatternRelationship} of the specified * {@link RelationshipType} between this node and the specified other node, * with the specified direction. * * @param otherNode the node at the other end of the relationship. * @param type the {@link RelationshipType} of the relationship. * @param dir the direction of the relationship. Use * {@link Direction#OUTGOING} to create a relationship from this * node to the other node. Use {@link Direction#INCOMING} to * create a relationship from the other node to this node. Use * {@link Direction#BOTH} to create a relationship where the * direction does not matter. * @return the newly created {@link PatternRelationship}. */ public PatternRelationship createRelationshipTo( PatternNode otherNode, RelationshipType type, Direction dir ) { if ( dir == Direction.INCOMING ) return otherNode.createRelationshipTo( this, type ); return this.createRelationshipTo( otherNode, type, false, dir == Direction.BOTH ? false : true ); } /** * Create a directed, optional {@link PatternRelationship} from this node, * to the specified other node. * * @param otherNode the node at the other end of the relationship. * @return the newly created {@link PatternRelationship}. */ public PatternRelationship createOptionalRelationshipTo( PatternNode otherNode ) { return this.createRelationshipTo( otherNode, true, true ); } /** * Create an optional {@link PatternRelationship} between this node and the * specified other node, with the specified direction. * * @param otherNode the node at the other end of the relationship. * @param dir the direction of the relationship. Use * {@link Direction#OUTGOING} to create a relationship from this * node to the other node. Use {@link Direction#INCOMING} to * create a relationship from the other node to this node. Use * {@link Direction#BOTH} to create a relationship where the * direction does not matter. * @return the newly created {@link PatternRelationship}. */ public PatternRelationship createOptionalRelationshipTo( PatternNode otherNode, Direction dir ) { return this.createRelationshipTo( otherNode, true, dir == Direction.BOTH ? false : true ); } /** * Create a directed, optional {@link PatternRelationship} of the specified * {@link RelationshipType} from this node to the specified other node. * * @param otherNode the node at the other end of the relationship. * @param type the {@link RelationshipType} of the relationship. * @return the newly created {@link PatternRelationship}. */ public PatternRelationship createOptionalRelationshipTo( PatternNode otherNode, RelationshipType type ) { return this.createRelationshipTo( otherNode, type, true, true ); } /** * Create an optional {@link PatternRelationship} of the specified * {@link RelationshipType} between this node and the specified other node, * with the specified direction. * * @param otherNode the node at the other end of the relationship. * @param type the {@link RelationshipType} of the relationship. * @param dir the direction of the relationship. Use * {@link Direction#OUTGOING} to create a relationship from this * node to the other node. Use {@link Direction#INCOMING} to * create a relationship from the other node to this node. Use * {@link Direction#BOTH} to create a relationship where the * direction does not matter. * @return the newly created {@link PatternRelationship}. */ public PatternRelationship createOptionalRelationshipTo( PatternNode otherNode, RelationshipType type, Direction dir ) { return this.createRelationshipTo( otherNode, type, true, dir == Direction.BOTH ? false : true ); } PatternRelationship createRelationshipTo( PatternNode otherNode, boolean optional, boolean directed ) { PatternRelationship relationship = new PatternRelationship( this, otherNode, optional, directed ); addRelationship( relationship, optional ); otherNode.addRelationship( relationship, optional ); return relationship; } PatternRelationship createRelationshipTo( PatternNode otherNode, RelationshipType type, boolean optional, boolean directed ) { PatternRelationship relationship = new PatternRelationship( type, this, otherNode, optional, directed ); addRelationship( relationship, optional ); otherNode.addRelationship( relationship, optional ); return relationship; } @Override public String toString() { return this.label; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternNode.java
5,372
@Ignore("Fails too often") public class MultipleClusterTest { @Rule public LoggerRule logging = new LoggerRule(); @Test public void runTwoClusters() throws Throwable { File root = TargetDirectory.forTest( getClass() ).cleanDirectory( "cluster" ); ClusterManager clusterManager = new ClusterManager( fromXml( getClass().getResource( "/twoclustertest.xml" ).toURI() ), root, MapUtil.stringMap() ); try { clusterManager.start(); ManagedCluster cluster1 = clusterManager.getCluster( "neo4j.ha" ); long cluster1NodeId; { GraphDatabaseService master = cluster1.getMaster(); logging.getLogger().info( "CREATE NODE" ); Transaction tx = master.beginTx(); Node node = master.createNode(); node.setProperty( "cluster", "neo4j.ha" ); cluster1NodeId = node.getId(); logging.getLogger().info( "CREATED NODE" ); tx.success(); tx.finish(); } ManagedCluster cluster2 = clusterManager.getCluster( "neo4j.ha2" ); long cluster2NodeId; { GraphDatabaseService master = cluster2.getMaster(); logging.getLogger().info( "CREATE NODE" ); Transaction tx = master.beginTx(); Node node = master.createNode(); node.setProperty( "cluster", "neo4j.ha2" ); cluster2NodeId = node.getId(); logging.getLogger().info( "CREATED NODE" ); tx.success(); tx.finish(); } // Verify properties in all cluster nodes for ( HighlyAvailableGraphDatabase highlyAvailableGraphDatabase : cluster1.getAllMembers() ) { highlyAvailableGraphDatabase.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates(); Transaction transaction = highlyAvailableGraphDatabase.beginTx(); assertEquals( "neo4j.ha", highlyAvailableGraphDatabase.getNodeById( cluster1NodeId ).getProperty( "cluster" ) ); transaction.finish(); } for ( HighlyAvailableGraphDatabase highlyAvailableGraphDatabase : cluster2.getAllMembers() ) { highlyAvailableGraphDatabase.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates(); Transaction transaction = highlyAvailableGraphDatabase.beginTx(); assertEquals( "neo4j.ha2", highlyAvailableGraphDatabase.getNodeById( cluster2NodeId ).getProperty( "cluster" ) ); transaction.finish(); } } finally { clusterManager.stop(); } } }
false
enterprise_ha_src_test_java_org_neo4j_ha_MultipleClusterTest.java
5,373
{ @Override public void run() { Transaction tx = master.beginTx(); master.createNode().setProperty( "foo", "bar" ); tx.success(); tx.finish(); // This should cause lots of concurrent calls to pullUpdate() } } );
false
enterprise_ha_src_test_java_org_neo4j_ha_PullStormIT.java
5,374
{ public boolean accept( PatternMatch item ) { Set<PatternGroup> calculatedGroups = new HashSet<PatternGroup>(); for ( PatternElement element : item.getElements() ) { PatternNode node = element.getPatternNode(); PatternGroup group = node.getGroup(); if ( calculatedGroups.add( group ) ) { FilterValueGetter valueGetter = new SimpleRegexValueGetter( objectVariables, item, group.getFilters() ); for ( FilterExpression expression : group.getFilters() ) { if ( !expression.matches( valueGetter ) ) { return false; } } } } return true; } } );
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternMatcher.java
5,375
@Ignore("To be rewritten") public class QuorumWritesIT { @Test public void testMasterStopsWritesWhenMajorityIsUnavailable() throws Throwable { File root = TargetDirectory.forTest( getClass() ).cleanDirectory( "testMasterStopsWritesWhenMajorityIsUnavailable" ); ClusterManager clusterManager = new ClusterManager( clusterOfSize( 3 ), root, MapUtil.stringMap( HaSettings.tx_push_factor.name(), "2", HaSettings.state_switch_timeout.name(), "5s" ) ); try { clusterManager.start(); ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster(); cluster.await( ClusterManager.masterAvailable( ) ); cluster.await( ClusterManager.masterSeesAllSlavesAsAvailable() ); HighlyAvailableGraphDatabase master = cluster.getMaster(); doTx( master ); final CountDownLatch latch1 = new CountDownLatch( 1 ); waitOnHeartbeatFail( master, latch1 ); HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave(); cluster.fail( slave1 ); latch1.await(); slave1.shutdown(); doTx( master ); final CountDownLatch latch2 = new CountDownLatch( 1 ); waitOnHeartbeatFail( master, latch2 ); HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( slave1 ); ClusterManager.RepairKit rk2 = cluster.fail( slave2 ); latch2.await(); // The master should stop saying that it's master assertFalse( master.isMaster() ); try { doTx( master ); fail( "After both slaves fail txs should not go through" ); } catch ( TransactionFailureException e ) { assertEquals( "Timeout waiting for cluster to elect master", e.getMessage() ); } // This is not a hack, this simulates a period of inactivity in the cluster. Thread.sleep( 120000 ); // TODO Define "inactivity" and await that condition instead of 120 seconds. final CountDownLatch latch3 = new CountDownLatch( 1 ); final CountDownLatch latch4 = new CountDownLatch( 1 ); final CountDownLatch latch5 = new CountDownLatch( 1 ); waitOnHeartbeatAlive( master, latch3 ); // waitOnRoleIsAvailable( master, latch4, HighAvailabilityModeSwitcher.MASTER ); waitOnRoleIsAvailable( master, latch5, HighAvailabilityModeSwitcher.SLAVE ); rk2.repair(); latch3.await(); cluster.await( ClusterManager.masterAvailable( slave1, slave2 ) ); // latch4.await(); latch5.await(); cluster.await( ClusterManager.masterAvailable( ) ); assertTrue( master.isMaster() ); assertFalse( slave2.isMaster() ); Node finalNode = doTx( master ); try ( Transaction transaction = slave2.beginTx() ) { slave2.getNodeById( finalNode.getId() ); transaction.success(); } } finally { clusterManager.stop(); } } @Test public void testInstanceCanBeReplacedToReestablishQuorum() throws Throwable { File root = TargetDirectory.forTest( getClass() ).cleanDirectory( "testInstanceCanBeReplacedToReestablishQuorum" ); ClusterManager clusterManager = new ClusterManager( clusterOfSize( 3 ), root, MapUtil.stringMap( HaSettings.tx_push_factor.name(), "2", HaSettings.state_switch_timeout.name(), "5s" ) ); clusterManager.start(); ClusterManager.ManagedCluster cluster = clusterManager.getDefaultCluster(); HighlyAvailableGraphDatabase master = cluster.getMaster(); cluster.await( ClusterManager.masterSeesAllSlavesAsAvailable() ); doTx( master ); final CountDownLatch latch1 = new CountDownLatch( 1 ); waitOnHeartbeatFail( master, latch1 ); HighlyAvailableGraphDatabase slave1 = cluster.getAnySlave(); cluster.fail( slave1 ); latch1.await(); slave1.shutdown(); doTx( master ); final CountDownLatch latch2 = new CountDownLatch( 1 ); waitOnHeartbeatFail( master, latch2 ); HighlyAvailableGraphDatabase slave2 = cluster.getAnySlave( slave1 ); cluster.fail( slave2 ); latch2.await(); // The master should stop saying that it's master assertFalse( master.isMaster() ); try { doTx( master ); fail( "After both slaves fail txs should not go through" ); } catch ( TransactionFailureException e ) { assertEquals( "Timeout waiting for cluster to elect master", e.getMessage() ); } // This is not a hack, this simulates a period of inactivity in the cluster. Thread.sleep( 120000 ); // TODO Define "inactivity" and await that condition instead of 120 seconds. final CountDownLatch latch3 = new CountDownLatch( 1 ); final CountDownLatch latch4 = new CountDownLatch( 1 ); final CountDownLatch latch5 = new CountDownLatch( 1 ); waitOnHeartbeatAlive( master, latch3 ); waitOnRoleIsAvailable( master, latch4, HighAvailabilityModeSwitcher.MASTER ); waitOnRoleIsAvailable( master, latch5, HighAvailabilityModeSwitcher.SLAVE ); HighlyAvailableGraphDatabase replacement = (HighlyAvailableGraphDatabase) new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( new File( root, "replacement" ).getAbsolutePath() ). setConfig( ClusterSettings.cluster_server, ":5010" ). setConfig( HaSettings.ha_server, ":6010" ). setConfig( ClusterSettings.server_id, "3" ). setConfig( ClusterSettings.initial_hosts, cluster.getInitialHostsConfigString() ). setConfig( HaSettings.tx_push_factor, "0" ). newGraphDatabase(); latch3.await(); latch4.await(); latch5.await(); assertTrue( master.isMaster() ); assertFalse( replacement.isMaster() ); Node finalNode = doTx( master ); Transaction transaction = replacement.beginTx(); try { replacement.getNodeById( finalNode.getId() ); } finally { transaction.finish(); } clusterManager.stop(); replacement.shutdown(); } private void waitOnHeartbeatFail( HighlyAvailableGraphDatabase master, final CountDownLatch latch ) { final ClusterClient clusterClient = master.getDependencyResolver().resolveDependency( ClusterClient.class ); clusterClient.addHeartbeatListener( new HeartbeatListener.Adapter() { @Override public void failed( InstanceId server ) { latch.countDown(); clusterClient.removeHeartbeatListener( this ); } } ); } private void waitOnHeartbeatAlive( HighlyAvailableGraphDatabase master, final CountDownLatch latch ) { final ClusterClient clusterClient = master.getDependencyResolver().resolveDependency( ClusterClient.class ); clusterClient.addHeartbeatListener( new HeartbeatListener.Adapter() { @Override public void alive( InstanceId server ) { latch.countDown(); clusterClient.removeHeartbeatListener( this ); } } ); } private void waitOnRoleIsAvailable( HighlyAvailableGraphDatabase master, final CountDownLatch latch, final String roleToWaitFor ) { final ClusterMemberEvents events = master.getDependencyResolver().resolveDependency( ClusterMemberEvents .class ); events.addClusterMemberListener( new ClusterMemberListener.Adapter() { @Override public void memberIsAvailable( String role, InstanceId availableId, URI atUri ) { if ( role.equals( roleToWaitFor ) ) { latch.countDown(); events.removeClusterMemberListener( this ); } } } ); } private Node doTx( HighlyAvailableGraphDatabase db ) { Transaction tx = db.beginTx(); Node node = db.createNode(); tx.success(); tx.finish(); return node; } }
false
enterprise_ha_src_test_java_org_neo4j_ha_QuorumWritesIT.java
5,376
public class TestPullUpdatesApplied { @Rule public RepeatRule repeatRule = new RepeatRule(); private final HighlyAvailableGraphDatabase[] dbs = new HighlyAvailableGraphDatabase[3]; private final TargetDirectory dir = forTest( getClass() ); @Before public void doBefore() throws Exception { for ( int i = 0; i < dbs.length; i++ ) { dbs[i] = newDb( i ); } // Wait for all db's to become available for ( HighlyAvailableGraphDatabase db : dbs ) { db.isAvailable( 5000 ); } } @After public void doAfter() throws Exception { for ( HighlyAvailableGraphDatabase db : dbs ) { if ( db != null ) { db.shutdown(); } } } @Test public void testUpdatesAreWrittenToLogBeforeBeingAppliedToStore() throws Exception { int master = getCurrentMaster(); addNode( master ); int toKill = (master + 1) % dbs.length; HighlyAvailableGraphDatabase dbToKill = dbs[toKill]; final CountDownLatch latch1 = new CountDownLatch( 1 ); final HighlyAvailableGraphDatabase masterDb = dbs[master]; masterDb.getDependencyResolver().resolveDependency( ClusterClient.class ).addClusterListener( new ClusterListener.Adapter() { @Override public void leftCluster( InstanceId member ) { latch1.countDown(); masterDb.getDependencyResolver().resolveDependency( ClusterClient.class ) .removeClusterListener( this ); } } ); dbToKill.shutdown(); if ( !latch1.await( 60, TimeUnit.SECONDS ) ) { throw new IllegalStateException( "Timeout waiting for instance to leave cluster" ); } addNode( master ); // this will be pulled by tne next start up, applied // but not written to log. File targetDirectory = dir.existingDirectory( "" + toKill ); // Setup to detect shutdown of separate JVM, required since we don't exit cleanly. That is also why we go // through the heartbeat and not through the cluster change as above. final CountDownLatch latch2 = new CountDownLatch( 1 ); masterDb.getDependencyResolver().resolveDependency( ClusterClient.class ).addHeartbeatListener( new HeartbeatListener.Adapter() { @Override public void failed( InstanceId server ) { latch2.countDown(); masterDb.getDependencyResolver().resolveDependency( ClusterClient.class ) .removeHeartbeatListener( this ); } } ); // Temporary debugging System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + " Starting instance " + toKill + " in separate process.."); runInOtherJvmToGetExitCode( targetDirectory.getAbsolutePath(), "" + toKill ); // Temporary debugging System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + " Waiting for instance to start.."); if ( !latch2.await( 60, TimeUnit.SECONDS ) ) { throw new IllegalStateException( "Timeout waiting for instance to fail" ); } // This is to allow other instances to mark the dead instance as failed, otherwise on startup it will be denied. Thread.sleep( 15000 ); restart( toKill ); // recovery and branching. boolean hasBranchedData = new File( targetDirectory, "branched" ).listFiles().length > 0; assertFalse( hasBranchedData ); } // For executing in a different process than the one running the test case. public static void main( String[] args ) throws Exception { String storePath = args[0]; int serverId = Integer.parseInt( args[1] ); System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + " Starting instance " + serverId); database( serverId, storePath ).getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates(); System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()) + " Done, commencing sepukku."); // this is the bug trigger // no shutdown, emulates a crash. } private HighlyAvailableGraphDatabase newDb( int serverId ) { return database( serverId, dir.cleanDirectory( Integer.toString( serverId ) ).getAbsolutePath() ); } private void restart( int serverId ) { dbs[serverId] = database( serverId, dir.existingDirectory( Integer.toString( serverId ) ).getAbsolutePath() ); } private static HighlyAvailableGraphDatabase database( int serverId, String path ) { return (HighlyAvailableGraphDatabase) new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( path ) .setConfig( ClusterSettings.cluster_server, "127.0.0.1:" + (5001 + serverId) ) .setConfig( ClusterSettings.initial_hosts, "127.0.0.1:5001" ) .setConfig( ClusterSettings.server_id, Integer.toString( serverId ) ) .setConfig( HaSettings.ha_server, "localhost:" + (6666 + serverId) ) .setConfig( HaSettings.pull_interval, "0ms" ) .newGraphDatabase(); } private static int runInOtherJvmToGetExitCode( String... args ) throws Exception { List<String> allArgs = new ArrayList<>( Arrays.asList( "java", "-cp", System.getProperty( "java.class.path" ), TestPullUpdatesApplied.class.getName() ) ); allArgs.addAll( Arrays.asList( args ) ); Process p = Runtime.getRuntime().exec( allArgs.toArray( new String[allArgs.size()] ) ); List<Thread> threads = new LinkedList<>(); launchStreamConsumers( threads, p ); /* * Yes, timeouts suck but HAGD does not terminate politely, since it still has * threads running after main() completes, so we need to kill it. When? 10 seconds * is good enough. */ Thread.sleep( 10000 ); p.destroy(); for ( Thread t : threads ) { t.join(); } return 0; } private static void launchStreamConsumers( List<Thread> join, Process p ) { InputStream outStr = p.getInputStream(); InputStream errStr = p.getErrorStream(); Thread out = new Thread( new StreamConsumer( outStr, System.out, false ) ); join.add( out ); Thread err = new Thread( new StreamConsumer( errStr, System.err, false ) ); join.add( err ); out.start(); err.start(); } private long addNode( int dbId ) { HighlyAvailableGraphDatabase db = dbs[dbId]; long result = -1; Transaction tx = db.beginTx(); try { result = db.createNode().getId(); tx.success(); } finally { tx.finish(); } return result; } private int getCurrentMaster() throws Exception { for ( int i = 0; i < dbs.length; i++ ) { HighlyAvailableGraphDatabase db = dbs[i]; if ( db.isMaster() ) { return i; } } return -1; } }
false
enterprise_ha_src_test_java_org_neo4j_ha_TestPullUpdatesApplied.java
5,377
{ @Override public void leftCluster( InstanceId instanceId ) { slaveLeftLatch.countDown(); masterClusterClient.removeClusterListener( this ); } } );
false
enterprise_ha_src_test_java_org_neo4j_ha_TestPullUpdates.java
5,378
public class TestPullUpdates { private ClusterManager.ManagedCluster cluster; private static final int PULL_INTERVAL = 100; private static final int SHELL_PORT = 6370; @After public void doAfter() throws Throwable { if ( cluster != null ) { cluster.stop(); } } @Test public void makeSureUpdatePullerGetsGoingAfterMasterSwitch() throws Throwable { File root = TargetDirectory.forTest( getClass() ).cleanDirectory( "makeSureUpdatePullerGetsGoingAfterMasterSwitch" ); ClusterManager clusterManager = new ClusterManager( clusterOfSize( 3 ), root, MapUtil.stringMap( HaSettings.pull_interval.name(), PULL_INTERVAL+"ms") ); clusterManager.start(); cluster = clusterManager.getDefaultCluster(); long commonNodeId = createNodeOnMaster(); HighlyAvailableGraphDatabase master = cluster.getMaster(); setProperty( master, commonNodeId, 1 ); awaitPropagation( 1, commonNodeId, cluster ); cluster.await( masterSeesSlavesAsAvailable( 2 ) ); ClusterManager.RepairKit masterShutdownRK = cluster.shutdown( master ); cluster.await( masterAvailable() ); cluster.await( masterSeesSlavesAsAvailable( 1 ) ); setProperty( cluster.getMaster(), commonNodeId, 2 ); masterShutdownRK.repair(); cluster.await( masterAvailable() ); cluster.await( masterSeesSlavesAsAvailable( 2 ) ); awaitPropagation( 2, commonNodeId, cluster ); } @Test public void pullUpdatesShellAppPullsUpdates() throws Throwable { File root = TargetDirectory.forTest( getClass() ).cleanDirectory( "pullUpdatesShellAppPullsUpdates" ); Map<Integer, Map<String, String>> instanceConfig = new HashMap<Integer, Map<String, String>>(); for (int i = 1; i <= 2; i++) { Map<String, String> thisInstance = MapUtil.stringMap( ShellSettings.remote_shell_port.name(), "" + (SHELL_PORT + i) ); instanceConfig.put( i, thisInstance ); } ClusterManager clusterManager = new ClusterManager( clusterOfSize( 2 ), root, MapUtil.stringMap( HaSettings.pull_interval.name(), "0", HaSettings.tx_push_factor.name(), "0" , ShellSettings.remote_shell_enabled.name(), "true" ), instanceConfig ); clusterManager.start(); cluster = clusterManager.getDefaultCluster(); long commonNodeId = createNodeOnMaster(); setProperty( cluster.getMaster(), commonNodeId, 1 ); callPullUpdatesViaShell( 2 ); HighlyAvailableGraphDatabase slave = cluster.getAnySlave(); Transaction transaction = slave.beginTx(); try { assertEquals( 1, slave.getNodeById(commonNodeId).getProperty( "i" ) ); } finally { transaction.finish(); } } private long createNodeOnMaster() { long commonNodeId; try( Transaction tx=cluster.getMaster().beginTx() ) { commonNodeId = cluster.getMaster().createNode().getId(); tx.success(); } return commonNodeId; } @Test public void shouldPullUpdatesOnStartupNoMatterWhat() throws Exception { GraphDatabaseService slave = null; GraphDatabaseService master = null; try { File masterDir = TargetDirectory.forTest( getClass() ).cleanDirectory( "master" ); master = new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( masterDir.getAbsolutePath() ) .setConfig( ClusterSettings.server_id, "1" ) .setConfig( ClusterSettings.initial_hosts, ":5001" ) .newGraphDatabase(); // Copy the store, then shutdown, so update pulling later makes sense File slaveDir = TargetDirectory.forTest( getClass() ).cleanDirectory( "slave" ); slave = new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( slaveDir.getAbsolutePath() ) .setConfig( ClusterSettings.server_id, "2" ) .setConfig( ClusterSettings.initial_hosts, ":5001" ) .newGraphDatabase(); // Required to block until the slave has left for sure final CountDownLatch slaveLeftLatch = new CountDownLatch( 1 ); final ClusterClient masterClusterClient = ( (HighlyAvailableGraphDatabase) master ).getDependencyResolver() .resolveDependency( ClusterClient.class ); masterClusterClient.addClusterListener( new ClusterListener.Adapter() { @Override public void leftCluster( InstanceId instanceId ) { slaveLeftLatch.countDown(); masterClusterClient.removeClusterListener( this ); } } ); System.out.println("MASTER:"+master.isAvailable( 60 )); System.out.println("SLAVE:"+slave.isAvailable( 60 )); ((GraphDatabaseAPI)master).getDependencyResolver().resolveDependency( StringLogger.class ).info( "SHUTTING DOWN SLAVE" ); slave.shutdown(); // Make sure that the slave has left, because shutdown() may return before the master knows if (!slaveLeftLatch.await(60, TimeUnit.SECONDS)) throw new IllegalStateException( "Timeout waiting for slave to leave" ); long nodeId; try ( Transaction tx = master.beginTx() ) { Node node = master.createNode(); node.setProperty( "from", "master" ); nodeId = node.getId(); tx.success(); } // Store is already in place, should pull updates slave = new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( slaveDir.getAbsolutePath() ) .setConfig( ClusterSettings.server_id, "2" ) .setConfig( ClusterSettings.initial_hosts, ":5001" ) .setConfig( HaSettings.pull_interval, "0" ) // no pull updates, should pull on startup .newGraphDatabase(); slave.beginTx().close(); // Make sure switch to slave completes and so does the update pulling on startup try ( Transaction tx = slave.beginTx() ) { assertEquals( "master", slave.getNodeById( nodeId ).getProperty( "from" ) ); tx.success(); } } finally { if ( slave != null) { slave.shutdown(); } if ( master != null ) { master.shutdown(); } } } private void callPullUpdatesViaShell( int i ) throws ShellException { ShellClient client = ShellLobby.newClient( SHELL_PORT + i ); client.evaluate( "pullupdates" ); } private void powerNap() throws InterruptedException { Thread.sleep( 50 ); } private void awaitPropagation( int i, long nodeId, ClusterManager.ManagedCluster cluster ) throws Exception { long endTime = currentTimeMillis() + PULL_INTERVAL * 20; boolean ok = false; while ( !ok && currentTimeMillis() < endTime ) { ok = true; for ( HighlyAvailableGraphDatabase db : cluster.getAllMembers() ) { try ( Transaction tx = db.beginTx() ) { Number value = (Number)db.getNodeById(nodeId).getProperty( "i", null ); if ( value == null || value.intValue() != i ) { ok = false; } } catch( NotFoundException e ) { ok=false; } } if ( !ok ) { powerNap(); } } assertTrue( "Change wasn't propagated by pulling updates", ok ); } private void setProperty( HighlyAvailableGraphDatabase db, long nodeId, int i ) throws Exception { Transaction tx = db.beginTx(); try { db.getNodeById( nodeId ).setProperty( "i", i ); tx.success(); } finally { tx.finish(); } } }
false
enterprise_ha_src_test_java_org_neo4j_ha_TestPullUpdates.java
5,379
{ public void run() { slave1.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates(); } } );
false
enterprise_ha_src_test_java_org_neo4j_ha_TestPartialPullUpdates.java
5,380
@ForeignBreakpoints({ @ForeignBreakpoints.BreakpointDef(type = "org.neo4j.kernel.impl.transaction.xaframework.XaResourceManager", method = "applyCommittedTransaction", on = BreakPoint.Event.ENTRY)}) @RunWith(SubProcessTestRunner.class) @Ignore("Never passed") public class TestPartialPullUpdates { private HighlyAvailableGraphDatabase master; private HighlyAvailableGraphDatabase slave1; @Before public void setup() throws Exception { master = (HighlyAvailableGraphDatabase) new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( TargetDirectory.forTest( TestPartialPullUpdates.class ).cleanDirectory( "master" ).getAbsolutePath() ). setConfig( ClusterSettings.cluster_server, "127.0.0.1:5001" ). setConfig( ClusterSettings.server_id, "1" ). setConfig( HaSettings.tx_push_factor, "0" ). newGraphDatabase(); Transaction tx = master.beginTx(); Node node = master.createNode(); node.setProperty( "uuid", "123" ); master.index().forNodes( "auto" ).add( node, "uuid", "123" ); tx.success(); tx.finish(); slave1 = (HighlyAvailableGraphDatabase) new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( TargetDirectory.forTest( TestPartialPullUpdates.class ).cleanDirectory( "slave1" ).getAbsolutePath() ). setConfig( ClusterSettings.cluster_server, "127.0.0.1:5002" ). setConfig( ClusterSettings.initial_hosts, "127.0.0.1:5001" ). setConfig( ClusterSettings.server_id, "2" ). setConfig( HaSettings.ha_server, "localhost:6362" ). setConfig( HaSettings.pull_interval, "0" ). newGraphDatabase(); } @After public void shutdown() { slave1.shutdown(); master.shutdown(); } @Test @EnabledBreakpoints({"applyCommittedTransaction"}) public void doTheDamnTest() throws Exception { // Ensure the slave has got the store - simple sanity check assertEquals( "123", slave1.getNodeById( 1 ).getProperty( "uuid" ) ); // Delete the node from the store and the index at the slave. No push factor. Transaction tx = master.beginTx(); Node toRemove = master.index().forNodes( "auto" ).get( "uuid", "123" ).next(); long nodeId = toRemove.getId(); master.index().forNodes( "auto" ).remove( toRemove ); toRemove.delete(); tx.success(); tx.finish(); // Do the update pulling in a different thread so we can kill it. Thread t = new Thread( new Runnable() { public void run() { slave1.getDependencyResolver().resolveDependency( UpdatePuller.class ).pullUpdates(); } } ); t.start(); t.join(); // It should either be in both the graph and the index or in neither. if ( slave1.index().forNodes( "auto" ).get( "uuid", "123" ).hasNext() ) { System.out.println( "it was in the index" ); assertEquals( "123", slave1.getNodeById( nodeId ).getProperty( "uuid" ) ); } else { System.out.println( "it was not in the index" ); try { slave1.getNodeById( nodeId ); fail( "Node should not be there" ); } catch ( NotFoundException e ) { // good } } } /* * The applyCommittedTransaction method is called from ServerUtil.applyReceivedTransactions(). In the test method * it is called twice, both from a single instance of the apply loop. We let the first one pass but we kill the * second. Since it is in a loop, we cannot build a stack that shows when to kill it. The counter solution is * relatively safe and very much simple. */ @BreakpointHandler("applyCommittedTransaction") public static void onApplyCommittedHandler( BreakPoint self, DebugInterface di ) { if ( self.invocationCount() < 2 ) { di.thread().resume(); } else { di.thread().stop(); } } }
false
enterprise_ha_src_test_java_org_neo4j_ha_TestPartialPullUpdates.java
5,381
public class TestClusterIndexDeletion { @Test public void givenClusterWithCreatedIndexWhenDeleteIndexOnMasterThenIndexIsDeletedOnSlave() throws Throwable { ClusterManager clusterManager = new ClusterManager( fromXml( getClass().getResource( "/threeinstances.xml" ).toURI() ), TargetDirectory.forTest( getClass() ).cleanDirectory( "testCluster" ), MapUtil.stringMap( HaSettings.ha_server.name(), ":6001-6005", HaSettings.tx_push_factor.name(), "2" )); try { // Given clusterManager.start(); clusterManager.getDefaultCluster().await( ClusterManager.allSeesAllAsAvailable() ); GraphDatabaseAPI master = clusterManager.getDefaultCluster().getMaster(); try ( Transaction tx = master.beginTx() ) { master.index().forNodes( "Test" ); tx.success(); } HighlyAvailableGraphDatabase aSlave = clusterManager.getDefaultCluster().getAnySlave(); try ( Transaction tx = aSlave.beginTx() ) { assertThat( aSlave.index().existsForNodes( "Test" ), equalTo( true ) ); tx.success(); } // When try ( Transaction tx = master.beginTx() ) { master.index().forNodes( "Test" ).delete(); tx.success(); } // Then HighlyAvailableGraphDatabase anotherSlave = clusterManager.getDefaultCluster().getAnySlave(); try ( Transaction tx = anotherSlave.beginTx() ) { assertThat( anotherSlave.index().existsForNodes( "Test" ), equalTo( false ) ); tx.success(); } } finally { clusterManager.stop(); } } }
false
enterprise_ha_src_test_java_org_neo4j_ha_TestClusterIndexDeletion.java
5,382
public class TestClusterClientPadding { private static TargetDirectory dir = TargetDirectory.forTest( TestClusterClientPadding.class ); private ClusterManager clusterManager; private ManagedCluster cluster; @Before public void before() throws Throwable { clusterManager = new ClusterManager( clusterWithAdditionalClients( 2, 1 ), dir.cleanDirectory( "dbs" ), stringMap() ); clusterManager.start(); cluster = clusterManager.getDefaultCluster(); cluster.await( masterAvailable() ); cluster.await( masterSeesMembers( 3 ) ); cluster.await( allSeesAllAsJoined() ); } @After public void after() throws Throwable { clusterManager.shutdown(); } @Test public void additionalClusterClientCanHelpBreakTiesWhenMasterIsShutDown() throws Throwable { HighlyAvailableGraphDatabase sittingMaster = cluster.getMaster(); cluster.shutdown( sittingMaster ); cluster.await( masterAvailable( sittingMaster ) ); } @Test public void additionalClusterClientCanHelpBreakTiesWhenMasterFails() throws Throwable { HighlyAvailableGraphDatabase sittingMaster = null; sittingMaster = cluster.getMaster(); cluster.fail( sittingMaster ); cluster.await( masterAvailable( sittingMaster ) ); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_TestClusterClientPadding.java
5,383
{ public void run() { /* * We have two operations since we need to make sure this test passes * before and after the proper channel releasing fix. The issue is * that we can't have only one channel since it will deadlock because * the txCopyingThread is suspended and won't release the channel * (after the fix). But the problem is that with two channels going * before the fix it won't break because the RR policy in * ResourcePool will give the unused channel to the new requesting thread, * thus not triggering the bug. The solution is to do two requests so * eventually get the released, half consumed channel. */ // TODO Figure out how to do this // try // { // waitTxCopyToStart(); // Master masterClient = slave1.getBroker().getMaster().first(); // SlaveContext ctx = slave1.getSlaveContext( 11 ); // Response<Integer> response = masterClient.createRelationshipType( // ctx, "name2" ); // slave1.receive( response ); // response.close(); // // // This will break before the fix // response = masterClient.createRelationshipType( // slave1.getSlaveContext( 12 ), "name3" ); // slave1.receive( response ); // response.close(); // // /* // * If the above fails, this won't happen. Used to fail the // * test gracefully // */ // Transaction masterTx = master.beginTx(); // master.getReferenceNode().createRelationshipTo( // master.createNode(), // DynamicRelationshipType.withName( "test" ) ); // masterTx.success(); // masterTx.finish(); // } // finally // { // finish(); // } } }, "thread 2" );
false
enterprise_ha_src_test_java_org_neo4j_ha_TestClientThreadIsolation.java
5,384
{ public void run() { // TODO Figure out how to do this // Master masterClient = slave1.getBroker().getMaster().first(); // Response<Integer> response = masterClient.createRelationshipType( // slave1.getSlaveContext( 10 ), "name" ); // slave1.receive( response ); // will be suspended here // response.close(); } }, "thread 1" );
false
enterprise_ha_src_test_java_org_neo4j_ha_TestClientThreadIsolation.java
5,385
@ForeignBreakpoints({@ForeignBreakpoints.BreakpointDef(type = "org.neo4j.com.Client", method = "makeSureNextTransactionIsFullyFetched", on = Event.ENTRY), @ForeignBreakpoints.BreakpointDef(type = "org.neo4j.com.DechunkingChannelBuffer", method = "readNextChunk", on = Event.EXIT)}) @RunWith(SubProcessTestRunner.class) @Ignore("This test depends on chuncked requests, otherwise it will hang. So either reduce the Protocol" + ".DEFAULT_FRAME_LENGTH to 1024" + "or create a huge difference in the stores between master and slave which will lead to a multichunk " + "response.") public class TestClientThreadIsolation { @Test @EnabledBreakpoints({"makeSureNextTransactionIsFullyFetched", "readNextChunk", "waitTxCopyToStart", "finish"}) public void testTransactionsPulled() throws Exception { final HighlyAvailableGraphDatabase master = (HighlyAvailableGraphDatabase) new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( TargetDirectory.forTest( TestClientThreadIsolation.class ).cleanDirectory( "master" ).getAbsolutePath() ). setConfig( ClusterSettings.server_id, "1" ). newGraphDatabase(); final HighlyAvailableGraphDatabase slave1 = (HighlyAvailableGraphDatabase) new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( TargetDirectory.forTest( TestClientThreadIsolation.class ).cleanDirectory( "slave1" ).getAbsolutePath() ). setConfig( ClusterSettings.cluster_server, "127.0.0.1:5002" ). setConfig( ClusterSettings.initial_hosts, "127.0.0.1:5001" ). setConfig( ClusterSettings.server_id, "2" ). setConfig( HaSettings.max_concurrent_channels_per_slave, "2" ). setConfig( HaSettings.ha_server, "127.0.0.1:8001" ). newGraphDatabase(); Transaction masterTx = master.beginTx(); master.createNode().createRelationshipTo( master.createNode(), DynamicRelationshipType.withName( "master" ) ).setProperty( "largeArray", new int[20000] ); masterTx.success(); masterTx.finish(); Thread thread1 = new Thread( new Runnable() { public void run() { // TODO Figure out how to do this // Master masterClient = slave1.getBroker().getMaster().first(); // Response<Integer> response = masterClient.createRelationshipType( // slave1.getSlaveContext( 10 ), "name" ); // slave1.receive( response ); // will be suspended here // response.close(); } }, "thread 1" ); Thread thread2 = new Thread( new Runnable() { public void run() { /* * We have two operations since we need to make sure this test passes * before and after the proper channel releasing fix. The issue is * that we can't have only one channel since it will deadlock because * the txCopyingThread is suspended and won't release the channel * (after the fix). But the problem is that with two channels going * before the fix it won't break because the RR policy in * ResourcePool will give the unused channel to the new requesting thread, * thus not triggering the bug. The solution is to do two requests so * eventually get the released, half consumed channel. */ // TODO Figure out how to do this // try // { // waitTxCopyToStart(); // Master masterClient = slave1.getBroker().getMaster().first(); // SlaveContext ctx = slave1.getSlaveContext( 11 ); // Response<Integer> response = masterClient.createRelationshipType( // ctx, "name2" ); // slave1.receive( response ); // response.close(); // // // This will break before the fix // response = masterClient.createRelationshipType( // slave1.getSlaveContext( 12 ), "name3" ); // slave1.receive( response ); // response.close(); // // /* // * If the above fails, this won't happen. Used to fail the // * test gracefully // */ // Transaction masterTx = master.beginTx(); // master.getReferenceNode().createRelationshipTo( // master.createNode(), // DynamicRelationshipType.withName( "test" ) ); // masterTx.success(); // masterTx.finish(); // } // finally // { // finish(); // } } }, "thread 2" ); thread1.start(); thread2.start(); thread1.join(); thread2.join(); // assertTrue( // master.getReferenceNode().getRelationships( // DynamicRelationshipType.withName( "test" ) ).iterator().hasNext() ); } private static DebuggedThread txCopyingThread; private static DebuggedThread interferingThread; /* * Blocks the txCopyingThread after reading the * first chunk but before moving on to the next one. */ private static CountDownLatch latch = new CountDownLatch( 1 ); @BreakpointTrigger("waitTxCopyToStart") private void waitTxCopyToStart() { // wait for the first thread to grab the updates } @BreakpointTrigger("finish") private void finish() { // resume the suspended thread } @BreakpointHandler("waitTxCopyToStart") public static void onWaitTxCopyToStart( BreakPoint self, DebugInterface di ) { interferingThread = di.thread().suspend( null ); latch.countDown(); } @BreakpointHandler("finish") public static void onFinish( BreakPoint self, DebugInterface di ) { txCopyingThread.resume(); } @BreakpointHandler("makeSureNextTransactionIsFullyFetched") public static void onStartingStoreCopy( BreakPoint self, DebugInterface di, @BreakpointHandler("readNextChunk") BreakPoint onReadNextChunk ) throws Exception { // Wait for the other thread to recycle the channel latch.await(); txCopyingThread = di.thread(); self.disable(); } @BreakpointHandler("readNextChunk") public static void onReadNextChunk( BreakPoint self, DebugInterface di ) throws Exception { // Check because the interfering thread will trigger this too if ( txCopyingThread != null && di.thread().name().equals( txCopyingThread.name() ) ) { txCopyingThread.suspend( null ); interferingThread.resume(); self.disable(); } } }
false
enterprise_ha_src_test_java_org_neo4j_ha_TestClientThreadIsolation.java
5,386
public class TestBranchedData { private final File dir = TargetDirectory.forTest( getClass() ).makeGraphDbDir(); @Test public void migrationOfBranchedDataDirectories() throws Exception { long[] timestamps = new long[3]; for ( int i = 0; i < timestamps.length; i++ ) { startDbAndCreateNode(); timestamps[i] = moveAwayToLookLikeOldBranchedDirectory(); Thread.sleep( 1 ); // To make sure we get different timestamps } new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( dir.getAbsolutePath() ) .setConfig( ClusterSettings.server_id, "1" ) .setConfig( ClusterSettings.initial_hosts, ":5001" ) .newGraphDatabase().shutdown(); // It should have migrated those to the new location. Verify that. for ( long timestamp : timestamps ) { assertFalse( "directory branched-" + timestamp + " still exists.", new File( dir, "branched-" + timestamp ).exists() ); assertTrue( "directory " + timestamp + " is not there", BranchedDataPolicy.getBranchedDataDirectory( dir, timestamp ).exists() ); } } @Test public void shouldCopyStoreFromMasterIfBranched() throws Throwable { // GIVEN ClusterManager clusterManager = life.add( new ClusterManager( clusterOfSize( 3 ), dir, stringMap() ) ); life.start(); ManagedCluster cluster = clusterManager.getDefaultCluster(); cluster.await( allSeesAllAsAvailable() ); createNode( cluster.getMaster(), "A" ); cluster.sync(); // WHEN HighlyAvailableGraphDatabase slave = cluster.getAnySlave(); String storeDir = slave.getStoreDir(); RepairKit starter = cluster.shutdown( slave ); HighlyAvailableGraphDatabase master = cluster.getMaster(); HighlyAvailableGraphDatabase otherSlave = cluster.getAnySlave(); createNode( master, "B1" ); createNode( master, "C" ); createTransaction( storeDir, "B2" ); starter.repair(); // THEN cluster.await( allSeesAllAsAvailable() ); slave = cluster.getAnySlave( otherSlave ); slave.beginTx().finish(); } private final LifeSupport life = new LifeSupport(); @After public void after() { life.shutdown(); } private void createTransaction( String storeDir, String name ) { GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir ); try { createNode( db, name ); } finally { db.shutdown(); } } private void createNode( GraphDatabaseService db, String name ) { Transaction tx = db.beginTx(); try { db.createNode().setProperty( "name", name ); tx.success(); } finally { tx.finish(); } } private long moveAwayToLookLikeOldBranchedDirectory() { long timestamp = System.currentTimeMillis(); File branchDir = new File( dir, "branched-" + timestamp ); assertTrue( "create directory: " + branchDir, branchDir.mkdirs() ); for ( File file : nonNull( dir.listFiles() ) ) { String fileName = file.getName(); if ( !fileName.equals( StringLogger.DEFAULT_NAME ) && !file.getName().startsWith( "branched-" ) ) { assertTrue( FileUtils.renameFile( file, new File( branchDir, file.getName() ) ) ); } } return timestamp; } private void startDbAndCreateNode() { GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( dir.getAbsolutePath() ); Transaction tx = db.beginTx(); db.createNode(); tx.success(); tx.finish(); db.shutdown(); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_TestBranchedData.java
5,387
private class ArrayMatches<T> extends BaseMatcher<T> { private final T expected; private Object actual; public ArrayMatches( T expected ) { this.expected = expected; } public boolean matches( Object actual ) { this.actual = actual; if ( expected instanceof byte[] && actual instanceof byte[] ) { return Arrays.equals( (byte[]) actual, (byte[]) expected ); } else if ( expected instanceof char[] && actual instanceof char[] ) { return Arrays.equals( (char[]) actual, (char[]) expected ); } return false; } public void describeTo( Description descr ) { descr.appendText( String.format( "expected %s, got %s", toString( expected ), toString( actual ) ) ); } private String toString( Object value ) { if ( value instanceof byte[] ) { return Arrays.toString( (byte[]) value ) + "; len=" + ( (byte[]) value ).length; } if ( value instanceof char[] ) { return Arrays.toString( (char[]) value ) + "; len=" + ( (char[]) value ).length; } return "" + value; } }
false
enterprise_ha_src_test_java_org_neo4j_ha_TestBlockLogBuffer.java
5,388
public class TestBlockLogBuffer { @Test public void onlyOneNonFullBlock() throws IOException { byte[] bytes = new byte[255]; ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes ); wrappedBuffer.resetWriterIndex(); BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) ); byte byteValue = 5; int intValue = 1234; long longValue = 574853; float floatValue = 304985.5f; double doubleValue = 48493.22d; final byte[] bytesValue = new byte[] { 1, 5, 2, 6, 3 }; final char[] charsValue = "This is chars".toCharArray(); buffer.put( byteValue ); buffer.putInt( intValue ); buffer.putLong( longValue ); buffer.putFloat( floatValue ); buffer.putDouble( doubleValue ); buffer.put( bytesValue ); buffer.put( charsValue ); buffer.done(); ByteBuffer verificationBuffer = ByteBuffer.wrap( bytes ); assertEquals( 56, verificationBuffer.get() ); assertEquals( byteValue, verificationBuffer.get() ); assertEquals( intValue, verificationBuffer.getInt() ); assertEquals( longValue, verificationBuffer.getLong() ); assertEquals( floatValue, verificationBuffer.getFloat(), 0.0 ); assertEquals( doubleValue, verificationBuffer.getDouble(), 0.0 ); byte[] actualBytes = new byte[bytesValue.length]; verificationBuffer.get( actualBytes ); assertThat( actualBytes, new ArrayMatches<byte[]>( bytesValue ) ); char[] actualChars = new char[charsValue.length]; verificationBuffer.asCharBuffer().get( actualChars ); assertThat( actualChars, new ArrayMatches<char[]>( charsValue ) ); } @Test public void readSmallPortions() throws IOException { byte[] bytes = new byte[255]; ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes ); wrappedBuffer.resetWriterIndex(); BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) ); byte byteValue = 5; int intValue = 1234; long longValue = 574853; buffer.put( byteValue ); buffer.putInt( intValue ); buffer.putLong( longValue ); buffer.done(); ReadableByteChannel reader = new BlockLogReader( wrappedBuffer ); ByteBuffer verificationBuffer = ByteBuffer.wrap( new byte[1] ); reader.read( verificationBuffer ); verificationBuffer.flip(); assertEquals( byteValue, verificationBuffer.get() ); verificationBuffer = ByteBuffer.wrap( new byte[4] ); reader.read( verificationBuffer ); verificationBuffer.flip(); assertEquals( intValue, verificationBuffer.getInt() ); verificationBuffer = ByteBuffer.wrap( new byte[8] ); reader.read( verificationBuffer ); verificationBuffer.flip(); assertEquals( longValue, verificationBuffer.getLong() ); } @Test public void readOnlyOneNonFullBlock() throws IOException { byte[] bytes = new byte[255]; ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes ); wrappedBuffer.resetWriterIndex(); BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) ); byte byteValue = 5; int intValue = 1234; long longValue = 574853; float floatValue = 304985.5f; double doubleValue = 48493.22d; final byte[] bytesValue = new byte[] { 1, 5, 2, 6, 3 }; final char[] charsValue = "This is chars".toCharArray(); buffer.put( byteValue ); buffer.putInt( intValue ); buffer.putLong( longValue ); buffer.putFloat( floatValue ); buffer.putDouble( doubleValue ); buffer.put( bytesValue ); buffer.put( charsValue ); buffer.done(); ReadableByteChannel reader = new BlockLogReader( wrappedBuffer ); ByteBuffer verificationBuffer = ByteBuffer.wrap( new byte[1000] ); reader.read( verificationBuffer ); verificationBuffer.flip(); assertEquals( byteValue, verificationBuffer.get() ); assertEquals( intValue, verificationBuffer.getInt() ); assertEquals( longValue, verificationBuffer.getLong() ); assertEquals( floatValue, verificationBuffer.getFloat(), 0.0 ); assertEquals( doubleValue, verificationBuffer.getDouble(), 0.0 ); byte[] actualBytes = new byte[bytesValue.length]; verificationBuffer.get( actualBytes ); assertThat( actualBytes, new ArrayMatches<byte[]>( bytesValue ) ); char[] actualChars = new char[charsValue.length]; verificationBuffer.asCharBuffer().get( actualChars ); assertThat( actualChars, new ArrayMatches<char[]>( charsValue ) ); } @Test public void onlyOneFullBlock() throws Exception { byte[] bytes = new byte[256]; ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes ); wrappedBuffer.resetWriterIndex(); BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) ); byte[] bytesValue = new byte[255]; bytesValue[0] = 1; bytesValue[254] = -1; buffer.put( bytesValue ); buffer.done(); ByteBuffer verificationBuffer = ByteBuffer.wrap( bytes ); assertEquals( (byte) 255, verificationBuffer.get() ); byte[] actualBytes = new byte[bytesValue.length]; verificationBuffer.get( actualBytes ); assertThat( actualBytes, new ArrayMatches<byte[]>( bytesValue ) ); } @Test public void readOnlyOneFullBlock() throws Exception { byte[] bytes = new byte[256]; ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes ); wrappedBuffer.resetWriterIndex(); BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) ); byte[] bytesValue = new byte[255]; bytesValue[0] = 1; bytesValue[254] = -1; buffer.put( bytesValue ); buffer.done(); ReadableByteChannel reader = new BlockLogReader( wrappedBuffer ); ByteBuffer verificationBuffer = ByteBuffer.wrap( new byte[1000] ); reader.read( verificationBuffer ); verificationBuffer.flip(); byte[] actualBytes = new byte[bytesValue.length]; verificationBuffer.get( actualBytes ); assertThat( actualBytes, new ArrayMatches<byte[]>( bytesValue ) ); } @Test public void canWriteLargestAtomAfterFillingBuffer() throws Exception { byte[] bytes = new byte[300]; ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes ); wrappedBuffer.resetWriterIndex(); BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) ); byte[] bytesValue = new byte[255]; bytesValue[0] = 1; bytesValue[254] = -1; long longValue = 123456; buffer.put( bytesValue ); buffer.putLong( longValue ); buffer.done(); ByteBuffer verificationBuffer = ByteBuffer.wrap( bytes ); assertEquals( (byte) 0, verificationBuffer.get() ); byte[] actualBytes = new byte[bytesValue.length]; verificationBuffer.get( actualBytes ); assertThat( actualBytes, new ArrayMatches<byte[]>( bytesValue ) ); assertEquals( (byte) 8, verificationBuffer.get() ); assertEquals( longValue, verificationBuffer.getLong() ); } @Test public void canWriteReallyLargeByteArray() throws Exception { byte[] bytes = new byte[650]; ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes ); wrappedBuffer.resetWriterIndex(); BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) ); byte[] bytesValue = new byte[600]; bytesValue[1] = 1; bytesValue[99] = 2; bytesValue[199] = 3; bytesValue[299] = 4; bytesValue[399] = 5; bytesValue[499] = 6; bytesValue[599] = 7; buffer.put( bytesValue ); buffer.done(); byte[] actual; ByteBuffer verificationBuffer = ByteBuffer.wrap( bytes ); assertEquals( (byte) 0, verificationBuffer.get() ); actual = new byte[255]; verificationBuffer.get( actual ); assertThat( actual, new ArrayMatches<byte[]>( Arrays.copyOfRange( bytesValue, 0, 255 ) ) ); assertEquals( (byte) 0, verificationBuffer.get() ); actual = new byte[255]; verificationBuffer.get( actual ); assertThat( actual, new ArrayMatches<byte[]>( Arrays.copyOfRange( bytesValue, 255, 510 ) ) ); assertEquals( (byte) 90, verificationBuffer.get() ); actual = new byte[90]; verificationBuffer.get( actual ); assertThat( actual, new ArrayMatches<byte[]>( Arrays.copyOfRange( bytesValue, 510, 600 ) ) ); } @Test public void canReaderReallyLargeByteArray() throws Exception { byte[] bytes = new byte[650]; ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer( bytes ); wrappedBuffer.resetWriterIndex(); BlockLogBuffer buffer = new BlockLogBuffer( wrappedBuffer, new Monitors().newMonitor( ByteCounterMonitor.class ) ); byte[] bytesValue = new byte[600]; bytesValue[1] = 1; bytesValue[99] = 2; bytesValue[199] = 3; bytesValue[299] = 4; bytesValue[399] = 5; bytesValue[499] = 6; bytesValue[599] = 7; buffer.put( bytesValue ); buffer.done(); byte[] actual; BlockLogReader reader = new BlockLogReader( wrappedBuffer ); ByteBuffer verificationBuffer = ByteBuffer.wrap( new byte[1000] ); reader.read( verificationBuffer ); verificationBuffer.flip(); actual = new byte[255]; verificationBuffer.get( actual ); assertThat( actual, new ArrayMatches<byte[]>( Arrays.copyOfRange( bytesValue, 0, 255 ) ) ); actual = new byte[255]; verificationBuffer.get( actual ); assertThat( actual, new ArrayMatches<byte[]>( Arrays.copyOfRange( bytesValue, 255, 510 ) ) ); actual = new byte[90]; verificationBuffer.get( actual ); assertThat( actual, new ArrayMatches<byte[]>( Arrays.copyOfRange( bytesValue, 510, 600 ) ) ); } private class ArrayMatches<T> extends BaseMatcher<T> { private final T expected; private Object actual; public ArrayMatches( T expected ) { this.expected = expected; } public boolean matches( Object actual ) { this.actual = actual; if ( expected instanceof byte[] && actual instanceof byte[] ) { return Arrays.equals( (byte[]) actual, (byte[]) expected ); } else if ( expected instanceof char[] && actual instanceof char[] ) { return Arrays.equals( (char[]) actual, (char[]) expected ); } return false; } public void describeTo( Description descr ) { descr.appendText( String.format( "expected %s, got %s", toString( expected ), toString( actual ) ) ); } private String toString( Object value ) { if ( value instanceof byte[] ) { return Arrays.toString( (byte[]) value ) + "; len=" + ( (byte[]) value ).length; } if ( value instanceof char[] ) { return Arrays.toString( (char[]) value ) + "; len=" + ( (char[]) value ).length; } return "" + value; } } }
false
enterprise_ha_src_test_java_org_neo4j_ha_TestBlockLogBuffer.java
5,389
{ @Override public void run() { graphDb.shutdown(); } } );
false
enterprise_ha_src_test_java_org_neo4j_ha_StartLocalHaDb.java
5,390
@Ignore("Not a test") public class StartLocalHaDb { public static void main( String[] args ) { String path = args[0]; String configFile = args[1]; final GraphDatabaseService graphDb = new HighlyAvailableGraphDatabaseFactory(). newHighlyAvailableDatabaseBuilder( path ). setConfig( ClusterSettings.server_id, "1"). loadPropertiesFromFile( configFile ). newGraphDatabase(); Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { graphDb.shutdown(); } } ); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_StartLocalHaDb.java
5,391
public class StartInstanceInAnotherJvm { public static void main( String[] args ) { String dir = args[0]; GraphDatabaseAPI newSlave = (GraphDatabaseAPI) new HighlyAvailableGraphDatabaseFactory() .newHighlyAvailableDatabaseBuilder( dir ) .setConfig( new Args( args ).asMap() ) .newGraphDatabase(); } public static Process start( String dir, Map<String, String> config ) throws Exception { List<String> args = new ArrayList<String>(); args.addAll( Arrays.asList( "java", "-cp", System.getProperty( "java.class.path" ), StartInstanceInAnotherJvm.class.getName(), dir ) ); for ( Map.Entry<String, String> property : config.entrySet() ) args.add( "-" + property.getKey() + "=" + property.getValue() ); return Runtime.getRuntime().exec( args.toArray( new String[ args.size() ] ) ); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_StartInstanceInAnotherJvm.java
5,392
{ @Override public void memberIsAvailable( String role, InstanceId availableId, URI atUri ) { if ( role.equals( roleToWaitFor ) ) { latch.countDown(); events.removeClusterMemberListener( this ); } } } );
false
enterprise_ha_src_test_java_org_neo4j_ha_QuorumWritesIT.java
5,393
{ @Override public void alive( InstanceId server ) { latch.countDown(); clusterClient.removeHeartbeatListener( this ); } } );
false
enterprise_ha_src_test_java_org_neo4j_ha_QuorumWritesIT.java
5,394
{ @Override public void failed( InstanceId server ) { latch.countDown(); clusterClient.removeHeartbeatListener( this ); } } );
false
enterprise_ha_src_test_java_org_neo4j_ha_QuorumWritesIT.java
5,395
private static class SimpleRegexValueGetter implements FilterValueGetter { private PatternMatch match; private Map<String, PatternNode> labelToNode = new HashMap<String, PatternNode>(); private Map<String, String> labelToProperty = new HashMap<String, String>(); SimpleRegexValueGetter( Map<String, PatternNode> objectVariables, PatternMatch match, FilterExpression[] expressions ) { this.match = match; for ( FilterExpression expression : expressions ) { mapFromExpression( expression ); } this.labelToNode = objectVariables; } private void mapFromExpression( FilterExpression expression ) { if ( expression instanceof FilterBinaryNode ) { FilterBinaryNode node = ( FilterBinaryNode ) expression; mapFromExpression( node.getLeftExpression() ); mapFromExpression( node.getRightExpression() ); } else { AbstractFilterExpression pattern = ( AbstractFilterExpression ) expression; labelToProperty.put( pattern.getLabel(), pattern.getProperty() ); } } public String[] getValues( String label ) { PatternNode pNode = labelToNode.get( label ); if ( pNode == null ) { throw new RuntimeException( "No node for label '" + label + "'" ); } Node node = this.match.getNodeFor( pNode ); String propertyKey = labelToProperty.get( label ); if ( propertyKey == null ) { throw new RuntimeException( "No property key for label '" + label + "'" ); } Object rawValue = node.getProperty( propertyKey, null ); if ( rawValue == null ) { return new String[ 0 ]; } Collection<Object> values = ArrayPropertyUtil.propertyValueToCollection( rawValue ); String[] result = new String[ values.size() ]; int counter = 0; for ( Object value : values ) { result[ counter++ ] = ( String ) value; } return result; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternMatcher.java
5,396
private static class FilteredPatternFinder extends FilteringIterable<PatternMatch> { public FilteredPatternFinder( Iterable<PatternMatch> source, final Map<String, PatternNode> objectVariables ) { super( source, new Predicate<PatternMatch>() { public boolean accept( PatternMatch item ) { Set<PatternGroup> calculatedGroups = new HashSet<PatternGroup>(); for ( PatternElement element : item.getElements() ) { PatternNode node = element.getPatternNode(); PatternGroup group = node.getGroup(); if ( calculatedGroups.add( group ) ) { FilterValueGetter valueGetter = new SimpleRegexValueGetter( objectVariables, item, group.getFilters() ); for ( FilterExpression expression : group.getFilters() ) { if ( !expression.matches( valueGetter ) ) { return false; } } } } return true; } } ); } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternMatcher.java
5,397
public abstract class Service { /** * Designates that a class implements the specified service and should be * added to the services listings file (META-INF/services/[service-name]). * <p/> * The annotation in itself does not provide any functionality for adding * the implementation class to the services listings file. But it serves as * a handle for an Annotation Processing Tool to utilize for performing that * task. * * @author Tobias Ivarsson */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface Implementation { /** * The service(s) this class implements. * * @return the services this class implements. */ Class<?>[] value(); } /** * A base class for services, similar to {@link Service}, that compares keys * using case insensitive comparison instead of exact comparison. * * @author Tobias Ivarsson */ public static abstract class CaseInsensitiveService extends Service { /** * Create a new instance of a service implementation identified with the * specified key(s). * * @param key the main key for identifying this service implementation * @param altKeys alternative spellings of the identifier of this * service implementation */ protected CaseInsensitiveService( String key, String... altKeys ) { super( key, altKeys ); } @Override final public boolean matches( String key ) { for ( String id : keys ) { if ( id.equalsIgnoreCase( key ) ) { return true; } } return false; } } /** * Load all implementations of a Service. * * @param <T> the type of the Service * @param type the type of the Service to load * @return all registered implementations of the Service */ public static <T> Iterable<T> load( Class<T> type ) { Iterable<T> loader; if ( null != (loader = java6Loader( type )) ) { return loader; } if ( null != (loader = sunJava5Loader( type )) ) { return loader; } if ( null != (loader = ourOwnLoader( type )) ) { return loader; } return Collections.emptyList(); } /** * Load the Service implementation with the specified key. This method should never return null. * * @param <T> the type of the Service * @param type the type of the Service to load * @param key the key that identifies the desired implementation * @return the matching Service implementation */ public static <T extends Service> T load( Class<T> type, String key ) { for ( T impl : load( type ) ) { if ( impl.matches( key ) ) { return impl; } } throw new NoSuchElementException( String.format( "Could not find any implementation of %s with a key=\"%s\"", type.getName(), key ) ); } final Set<String> keys; /** * Create a new instance of a service implementation identified with the * specified key(s). * * @param key the main key for identifying this service implementation * @param altKeys alternative spellings of the identifier of this service * implementation */ protected Service( String key, String... altKeys ) { if ( altKeys == null || altKeys.length == 0 ) { this.keys = Collections.singleton( key ); } else { this.keys = new HashSet<String>( Arrays.asList( altKeys ) ); this.keys.add( key ); } } @Override public String toString() { return getClass().getSuperclass().getName() + "" + keys; } public boolean matches( String key ) { return keys.contains( key ); } public Iterable<String> getKeys() { return keys; } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } Service service = (Service) o; if ( !keys.equals( service.keys ) ) { return false; } return true; } @Override public int hashCode() { return keys.hashCode(); } private static <T> Iterable<T> filterExceptions( final Iterable<T> iterable ) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new PrefetchingIterator<T>() { final Iterator<T> iterator = iterable.iterator(); @Override protected T fetchNextOrNull() { while ( iterator.hasNext() ) { try { return iterator.next(); } catch ( Throwable e ) { } } return null; } }; } }; } private static <T> Iterable<T> java6Loader( Class<T> type ) { try { Class<?> serviceLoaderClass = Class .forName( "java.util.ServiceLoader" ); Iterable<T> contextClassLoaderServices = (Iterable<T>) serviceLoaderClass .getMethod( "load", Class.class ).invoke( null, type ); // Jboss 7 does not export content of META-INF/services to context // class loader, // so this call adds implementations defined in Neo4j libraries from // the same module. Iterable<T> currentClassLoaderServices = (Iterable<T>) serviceLoaderClass .getMethod( "load", Class.class, ClassLoader.class ).invoke( null, type, Service.class.getClassLoader() ); // Combine services loaded by both context and module classloaders. // Service instances compared by full class name ( we cannot use // equals for instances or classes because they can came from // different classloaders ). HashMap<String, T> services = new HashMap<String, T>(); putAllInstancesToMap( currentClassLoaderServices, services ); // Services from context class loader have higher precedence putAllInstancesToMap( contextClassLoaderServices, services ); return services.values(); } catch ( Exception e ) { return null; } catch ( LinkageError e ) { return null; } } /** * @param services * @param servicesMap */ private static <T> void putAllInstancesToMap( Iterable<T> services, Map<String, T> servicesMap ) { for ( T instance : filterExceptions( services ) ) { if ( null != instance ) { servicesMap.put( instance.getClass().getName(), instance ); } } } private static <T> Iterable<T> sunJava5Loader( final Class<T> type ) { final Method providers; try { providers = Class.forName( "sun.misc.Service" ).getMethod( "providers", Class.class ); } catch ( Exception e ) { return null; } catch ( LinkageError e ) { return null; } return filterExceptions( new Iterable<T>() { @Override public Iterator<T> iterator() { try { @SuppressWarnings("unchecked") Iterator<T> result = (Iterator<T>) providers.invoke( null, type ); return result; } catch ( Exception e ) { throw new RuntimeException( "Failed to invoke sun.misc.Service.providers(forClass)", e ); } } } ); } private static <T> Iterable<T> ourOwnLoader( final Class<T> type ) { Collection<URL> urls = new HashSet<URL>(); try { Enumeration<URL> resources = Thread.currentThread().getContextClassLoader() .getResources( "META-INF/services/" + type.getName() ); while ( resources.hasMoreElements() ) { urls.add( resources.nextElement() ); } } catch ( IOException e ) { return null; } return new NestingIterable<T, BufferedReader>( FilteringIterable.notNull( new IterableWrapper<BufferedReader, URL>( urls ) { @Override protected BufferedReader underlyingObjectToObject( URL url ) { try { return new BufferedReader( new InputStreamReader( url.openStream(), "utf-8" ) ); } catch ( IOException e ) { return null; } } } ) ) { @Override protected Iterator<T> createNestedIterator( final BufferedReader input ) { return new PrefetchingIterator<T>() { @Override protected T fetchNextOrNull() { try { String line; while ( null != (line = input.readLine()) ) { try { return type.cast( Class.forName( line ).newInstance() ); } catch ( Exception e ) { } catch ( LinkageError e ) { } } input.close(); return null; } catch ( IOException e ) { return null; } } /* Finalizer - close the input stream. * Prevent leakage of open files. Finalizers impact GC performance, * but there are expected to be few of these objects. */ @Override protected void finalize() throws Throwable { input.close(); } }; } }; } }
false
community_kernel_src_main_java_org_neo4j_helpers_Service.java
5,398
NODE_GLOBAL { public UniquenessFilter create( Object optionalParameter ) { acceptNull( optionalParameter ); return new GloballyUnique( PrimitiveTypeFetcher.NODE ); } },
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Uniqueness.java
5,399
{ @Override protected int compareNodes( Node endNode1, Node endNode2 ) { Integer count1 = count( endNode1, expander ); Integer count2 = count( endNode2, expander ); return count1.compareTo( count2 ); } private Integer count( Node node, PathExpander expander ) { return IteratorUtil.count( expander.expand( new SingleNodePath( node ), BranchState.NO_STATE ) ); } };
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Sorting.java