Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
5,200
}){ protected Iterator exceptionOnIterator(Throwable t) { rethrow(new IllegalStateException()); return super.exceptionOnIterator(t); } });
false
community_kernel_src_test_java_org_neo4j_helpers_collection_ExceptionHandlingIterableTest.java
5,201
IteratorUtil.count(new ExceptionHandlingIterable(new Iterable() { public Iterator iterator() { throw new RuntimeException("exception on iterator"); } }){
false
community_kernel_src_test_java_org_neo4j_helpers_collection_ExceptionHandlingIterableTest.java
5,202
@SuppressWarnings("unchecked") public class ExceptionHandlingIterableTest { @Test(expected = IllegalStateException.class) public void testHandleExceptionOnIteratorCreation() { IteratorUtil.count(new ExceptionHandlingIterable(new Iterable() { public Iterator iterator() { throw new RuntimeException("exception on iterator"); } }){ protected Iterator exceptionOnIterator(Throwable t) { rethrow(new IllegalStateException()); return super.exceptionOnIterator(t); } }); } @Test(expected = IllegalStateException.class) public void testHandleExceptionOnNext() { IteratorUtil.count(new ExceptionHandlingIterable(new Iterable() { public Iterator iterator() { return new Iterator() { public boolean hasNext() { return true; } public Object next() { throw new RuntimeException("exception on next"); } public void remove() { } }; } }){ @Override protected Object exceptionOnNext(Throwable t) { rethrow(new IllegalStateException()); return super.exceptionOnNext(t); } }); } @Test(expected = IllegalStateException.class) public void testHandleExceptionOnHasNext() { IteratorUtil.count(new ExceptionHandlingIterable(new Iterable() { public Iterator iterator() { return new Iterator() { public boolean hasNext() { throw new RuntimeException("exception on next"); } public Object next() { return null; } public void remove() { } }; } }){ @Override protected boolean exceptionOnHasNext(Throwable t) { rethrow(new IllegalStateException()); return super.exceptionOnHasNext(t); } }); } }
false
community_kernel_src_test_java_org_neo4j_helpers_collection_ExceptionHandlingIterableTest.java
5,203
return new Iterator<T>() { @Override public boolean hasNext() { try { return it.hasNext(); } catch (Throwable t) { return exceptionOnHasNext(t); } } @Override public T next() { try { return it.next(); } catch (Throwable t) { return exceptionOnNext(t); } } @Override public void remove() { try { it.remove(); } catch (Throwable t) { exceptionOnRemove(t); } } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_ExceptionHandlingIterable.java
5,204
public class ExceptionHandlingIterable<T> implements Iterable<T> { private final Iterable<T> source; public ExceptionHandlingIterable(Iterable<T> source) { this.source = source; } @Override public Iterator<T> iterator() { try { final Iterator<T> it = source.iterator(); return new Iterator<T>() { @Override public boolean hasNext() { try { return it.hasNext(); } catch (Throwable t) { return exceptionOnHasNext(t); } } @Override public T next() { try { return it.next(); } catch (Throwable t) { return exceptionOnNext(t); } } @Override public void remove() { try { it.remove(); } catch (Throwable t) { exceptionOnRemove(t); } } }; } catch (Throwable t) { return exceptionOnIterator(t); } } protected void rethrow(Throwable t) { // TODO it's pretty bad that we have to do this. We should refactor our exception hierarchy // to eliminate the need for this hack. ExceptionHandlingIterable.<RuntimeException>sneakyThrow(t); } @SuppressWarnings("unchecked") private static <T extends Throwable> void sneakyThrow(Throwable throwable) throws T { throw (T) throwable; } protected boolean exceptionOnHasNext(Throwable t) { rethrow(t); return false; } protected void exceptionOnRemove(Throwable t) { } protected T exceptionOnNext(Throwable t) { rethrow(t); return null; } protected Iterator<T> exceptionOnIterator(Throwable t) { rethrow(t); return null; } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_ExceptionHandlingIterable.java
5,205
public class CombiningResourceIteratorTest { @Test public void shouldNotCloseDuringIteration() throws Exception { // Given ResourceIterator<Long> it1 = spy( asResourceIterator( iterator( 1l, 2l, 3l ) ) ); ResourceIterator<Long> it2 = spy( asResourceIterator( iterator( 5l, 6l, 7l ) ) ); CombiningResourceIterator<Long> combingIterator = new CombiningResourceIterator<>( iterator(it1, it2) ); // When I iterate through it, things come back in the right order assertThat( IteratorUtil.asList( combingIterator ), equalTo(asList(1l,2l,3l,5l,6l,7l)) ); // Then verify(it1, never()).close(); verify(it2, never()).close(); } @Test public void closesAllIteratorsOnShutdown() throws Exception { // Given ResourceIterator<Long> it1 = spy( asResourceIterator( iterator( 1l, 2l, 3l ) ) ); ResourceIterator<Long> it2 = spy( asResourceIterator( iterator( 5l, 6l, 7l ) ) ); CombiningResourceIterator<Long> combingIterator = new CombiningResourceIterator<>( iterator(it1, it2) ); // Given I iterate through half of it int iterations = 4; while( iterations --> 0 ) combingIterator.next(); // When combingIterator.close(); // Then verify(it1).close(); verify(it2).close(); } @Test public void shouldHandleSingleItemIterators() throws Exception { // Given ResourceIterator<Long> it1 = asResourceIterator( iterator( 1l) ); ResourceIterator<Long> it2 = asResourceIterator( iterator( 5l, 6l, 7l ) ); CombiningResourceIterator<Long> combingIterator = new CombiningResourceIterator<>( iterator(it1, it2) ); // When I iterate through it, things come back in the right order assertThat( IteratorUtil.asList( combingIterator ), equalTo(asList(1l,5l,6l,7l)) ); } }
false
community_kernel_src_test_java_org_neo4j_helpers_collection_CombiningResourceIteratorTest.java
5,206
public class CombiningResourceIterator<T> extends CombiningIterator<T> implements ResourceIterator<T> { private final Iterator<ResourceIterator<T>> iterators; private final Collection<ResourceIterator<T>> seenIterators = new ArrayList<>(); private ResourceIterator<T> currentIterator; public CombiningResourceIterator( Iterator<ResourceIterator<T>> iterators ) { super(iterators); this.iterators = iterators; } @Override protected Iterator<T> nextIteratorOrNull() { if(iterators.hasNext()) { currentIterator = iterators.next(); seenIterators.add( currentIterator ); return currentIterator; } return null; } @Override public void close() { for ( ResourceIterator<T> seenIterator : seenIterators ) { seenIterator.close(); } while(iterators.hasNext()) { iterators.next().close(); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_CombiningResourceIterator.java
5,207
public class CombiningIterator<T> extends PrefetchingIterator<T> { private Iterator<? extends Iterator<T>> iterators; private Iterator<T> currentIterator; public CombiningIterator( Iterable<? extends Iterator<T>> iterators ) { this( iterators.iterator() ); } public CombiningIterator( Iterator<? extends Iterator<T>> iterators ) { this.iterators = iterators; } public CombiningIterator( T first, Iterator<T> rest ) { this( Collections.<Iterator<T>>emptyList() ); this.hasFetchedNext = true; this.nextObject = first; this.currentIterator = rest; } @Override protected T fetchNextOrNull() { if ( currentIterator == null || !currentIterator.hasNext() ) { while ( (currentIterator = nextIteratorOrNull()) != null ) { if ( currentIterator.hasNext() ) { break; } } } return currentIterator != null && currentIterator.hasNext() ? currentIterator.next() : null; } protected Iterator<T> nextIteratorOrNull() { if(iterators.hasNext()) { return iterators.next(); } return null; } protected Iterator<T> currentIterator() { return currentIterator; } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_CombiningIterator.java
5,208
public class CombiningIterable<T> implements Iterable<T> { private Iterable<Iterable<T>> iterables; public CombiningIterable( Iterable<Iterable<T>> iterables ) { this.iterables = iterables; } public Iterator<T> iterator() { LinkedList<Iterator<T>> iterators = new LinkedList<Iterator<T>>(); for ( Iterable<T> iterable : iterables ) { iterators.add( iterable.iterator() ); } return new CombiningIterator<T>( iterators ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_CombiningIterable.java
5,209
private class WrappingIterator extends IteratorWrapper<T, U> { WrappingIterator( Iterator<U> iterator ) { super( iterator ); } @Override protected T underlyingObjectToObject( U object ) { return CollectionWrapper.this.underlyingObjectToObject( object ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_CollectionWrapper.java
5,210
public abstract class CollectionWrapper<T, U> implements Collection<T> { private Collection<U> collection; public CollectionWrapper( Collection<U> underlyingCollection ) { this.collection = underlyingCollection; } protected abstract U objectToUnderlyingObject( T object ); protected abstract T underlyingObjectToObject( U object ); public boolean add( T o ) { return collection.add( objectToUnderlyingObject( o ) ); } public void clear() { collection.clear(); } public boolean contains( Object o ) { return collection.contains( objectToUnderlyingObject( ( T ) o ) ); } public boolean isEmpty() { return collection.isEmpty(); } public Iterator<T> iterator() { return new WrappingIterator( collection.iterator() ); } public boolean remove( Object o ) { return collection.remove( objectToUnderlyingObject( ( T ) o ) ); } public int size() { return collection.size(); } protected Collection<U> convertCollection( Collection c ) { Collection<U> converted = new HashSet<U>(); for ( Object item : c ) { converted.add( objectToUnderlyingObject( ( T ) item ) ); } return converted; } public boolean retainAll( Collection c ) { return collection.retainAll( convertCollection( c ) ); } public boolean addAll( Collection c ) { return collection.addAll( convertCollection( c ) ); } public boolean removeAll( Collection c ) { return collection.removeAll( convertCollection( c ) ); } public boolean containsAll( Collection c ) { return collection.containsAll( convertCollection( c ) ); } public Object[] toArray() { Object[] array = collection.toArray(); Object[] result = new Object[ array.length ]; for ( int i = 0; i < array.length; i++ ) { result[ i ] = underlyingObjectToObject( ( U ) array[ i ] ); } return result; } public <R> R[] toArray( R[] a ) { Object[] array = collection.toArray(); ArrayList<R> result = new ArrayList<R>(); for ( int i = 0; i < array.length; i++ ) { result.add( ( R ) underlyingObjectToObject( ( U ) array[ i ] ) ); } return result.toArray( a ); } private class WrappingIterator extends IteratorWrapper<T, U> { WrappingIterator( Iterator<U> iterator ) { super( iterator ); } @Override protected T underlyingObjectToObject( U object ) { return CollectionWrapper.this.underlyingObjectToObject( object ); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_CollectionWrapper.java
5,211
public abstract class CatchingIteratorWrapper<T, U> extends PrefetchingIterator<T> { private final Iterator<U> source; public CatchingIteratorWrapper( Iterator<U> source ) { this.source = source; } @Override protected T fetchNextOrNull() { while ( source.hasNext() ) { U nextItem = null; try { nextItem = fetchNextOrNullFromSource( source ); if ( nextItem != null ) { return underlyingObjectToObject( nextItem ); } } catch ( Throwable t ) { if ( exceptionOk( t ) ) { itemDodged( nextItem ); continue; } if ( t instanceof RuntimeException ) { throw (RuntimeException) t; } else if ( t instanceof Error ) { throw (Error) t; } throw new RuntimeException( t ); } } return null; } protected U fetchNextOrNullFromSource( Iterator<U> source ) { return source.next(); } protected void itemDodged( U item ) { } protected boolean exceptionOk( Throwable t ) { return true; } protected abstract T underlyingObjectToObject( U object ); }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_CatchingIteratorWrapper.java
5,212
{ @Override public boolean accept( Throwable item ) { return !(item instanceof LevelThreeException) || !item.getMessage().contains( "include" ); } } );
false
community_kernel_src_test_java_org_neo4j_helpers_TestExceptions.java
5,213
public class TestArgs { @Test public void testInterleavedParametersWithValuesAndNot() { String[] line = { "-host", "machine.foo.com", "-port", "1234", "-v", "-name", "othershell" }; Args args = new Args( line ); assertEquals( "machine.foo.com", args.get( "host", null ) ); assertEquals( "1234", args.get( "port", null ) ); assertEquals( 1234, args.getNumber( "port", null ).intValue() ); assertEquals( "othershell", args.get( "name", null ) ); assertTrue( args.has( "v" ) ); assertTrue( args.orphans().isEmpty() ); } @Test public void testInterleavedEqualsArgsAndSplitKeyValue() { String[] line = { "-host=localhost", "-v", "--port", "1234", "param1", "-name=Something", "param2" }; Args args = new Args( line ); assertEquals( "localhost", args.get( "host", null ) ); assertTrue( args.has( "v" ) ); assertEquals( 1234, args.getNumber( "port", null ).intValue() ); assertEquals( "Something", args.get( "name", null ) ); assertEquals( 2, args.orphans().size() ); assertEquals( "param1", args.orphans().get( 0 ) ); assertEquals( "param2", args.orphans().get( 1 ) ); } @Test public void testParameterWithDashValue() { String [] line = { "-file", "-" }; Args args = new Args ( line ); assertEquals( 1, args.asMap().size() ); assertEquals( "-", args.get ( "file", null ) ); assertTrue( args.orphans().isEmpty() ); } @Test public void testEnum() { String[] line = { "--enum=" + MyEnum.second.name() }; Args args = new Args( line ); Enum<MyEnum> result = args.getEnum( MyEnum.class, "enum", MyEnum.first ); assertEquals( MyEnum.second, result ); } @Test public void testEnumWithDefault() { String[] line = {}; Args args = new Args( line ); MyEnum result = args.getEnum( MyEnum.class, "enum", MyEnum.third ); assertEquals( MyEnum.third, result ); } @Test( expected = IllegalArgumentException.class ) public void testEnumWithInvalidValue() throws Exception { String[] line = { "--myenum=something" }; Args args = new Args( line ); args.getEnum( MyEnum.class, "myenum", MyEnum.third ); } private static enum MyEnum { first, second, third; } }
false
community_kernel_src_test_java_org_neo4j_helpers_TestArgs.java
5,214
{ 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,215
{ @Override public T apply( T from1, Function<String, String> from2 ) { try { return valueFunction.apply( from1, from2 ); } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException( message ); } } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,216
{ @Override public T apply( T value, Function<String, String> settings ) { if ( value != null && value.compareTo( max ) > 0 ) { throw new IllegalArgumentException( String.format( "maximum allowed value is: %s", max ) ); } return value; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,217
{ @Override public T apply( T value, Function<String, String> settings ) { if ( value != null && value.compareTo( min ) < 0 ) { throw new IllegalArgumentException( String.format( "minimum allowed value is: %s", min ) ); } return value; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,218
{ @Override public String apply( String value, Function<String, String> settings ) { if ( !pattern.matcher( value ).matches() ) { throw new IllegalArgumentException( "value does not match expression:" + regex ); } return value; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,219
{ @Override public List<T> apply( String value ) { String[] parts = value.split( separator ); List<T> list = new ArrayList<T>(); for ( String part : parts ) { list.add( itemParser.apply( part ) ); } return list; } @Override public String toString() { return "a list separated by '"+separator+"' where items are "+itemParser.toString(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,220
{ @Override public T apply( String value ) { for ( T optionValue : optionValues ) { if ( optionValue.toString().equals( value ) ) { return optionValue; } } throw new IllegalArgumentException( "must be one of " + Iterables.toList( optionValues ).toString() ); } @Override public String toString() { StringBuilder builder = new StringBuilder( ); builder.append( "one of " ); String comma = ""; for ( T optionValue : optionValues ) { builder.append( comma ).append( optionValue.toString() ); comma = ", "; } return builder.toString(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,221
{ @Override public Long apply( String from ) { return Config.parseLongWithUnit( from ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,222
{ @Override public File apply( String setting ) { setting = FileUtils.fixSeparatorsInPath( setting ); return new File( setting ); } @Override public String toString() { return "a path"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,223
{ @Override public URI apply( String value ) { try { return new URI( value ); } catch ( URISyntaxException e ) { throw new IllegalArgumentException( "not a valid URI" ); } } @Override public String toString() { return "a URI"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,224
{ @Override public Long apply( String value ) { try { String mem = value.toLowerCase(); long multiplier = 1; if ( mem.endsWith( "k" ) ) { multiplier = 1024; mem = mem.substring( 0, mem.length() - 1 ); } else if ( mem.endsWith( "m" ) ) { multiplier = 1024 * 1024; mem = mem.substring( 0, mem.length() - 1 ); } else if ( mem.endsWith( "g" ) ) { multiplier = 1024 * 1024 * 1024; mem = mem.substring( 0, mem.length() - 1 ); } return Long.parseLong( mem.trim() ) * multiplier; } catch ( NumberFormatException e ) { throw new IllegalArgumentException( String.format( "%s is not a valid size, must be e.g. 10, 5K, 1M, " + "11G", value ) ); } } @Override public String toString() { return "a byte size"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,225
{ @Override public Long apply( String value ) { return TimeUtil.parseTimeMillis.apply( value ); } @Override public String toString() { return "a duration"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,226
{ @Override public String apply( Function<String, String> settings ) { String value = lookup.apply( settings ); if ( value == null ) { value = ((SettingHelper<T>) inheritedSetting).lookup( settings ); } return value; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,227
public final class Settings { private interface SettingHelper<T> extends Setting<T> { String lookup( Function<String, String> settings ); String defaultLookup( Function<String, String> settings ); } // Set default value to this if user HAS to set a value @SuppressWarnings("RedundantStringConstructorCall") // It's an explicitly allocated string so identity equality checks work public static final String MANDATORY = new String( "mandatory" ); public static final String NO_DEFAULT = null; public static final String TRUE = "true"; public static final String FALSE = "false"; public static final String DURATION_FORMAT = "\\d+(ms|s|m)"; public static final String SIZE_FORMAT = "\\d+[kmgKMG]?"; public static final String ANY = ".+"; @SuppressWarnings("unchecked") public static <T> Setting<T> setting( final String name, final Function<String, T> parser, final String defaultValue ) { return setting( name, parser, defaultValue, (Setting<T>) null ); } public static <T> Setting<T> setting( final String name, final Function<String, T> parser, final String defaultValue, final Function2<T, Function<String, String>, T>... valueConverters ) { return setting( name, parser, defaultValue, null, valueConverters ); } @SuppressWarnings("unchecked") public static <T> Setting<T> setting( final String name, final Function<String, T> parser, final Setting<T> inheritedSetting ) { return setting( name, parser, null, inheritedSetting ); } public static <T> Setting<T> setting( final String name, final Function<String, T> parser, final String defaultValue, final Setting<T> inheritedSetting, final Function2<T, Function<String, String>, T>... valueConverters ) { Function<Function<String, String>, String> valueLookup = named( name ); Function<Function<String, String>, String> defaultLookup; if ( defaultValue != null ) { //noinspection StringEquality if ( defaultValue.equals( MANDATORY ) ) { defaultLookup = mandatory( valueLookup ); } else { defaultLookup = withDefault( defaultValue, valueLookup ); } } else { defaultLookup = Functions.nullFunction(); } if ( inheritedSetting != null ) { valueLookup = inheritedValue( valueLookup, inheritedSetting ); defaultLookup = inheritedDefault( defaultLookup, inheritedSetting ); } return new DefaultSetting<T>( name, parser, valueLookup, defaultLookup, valueConverters ); } private static <T> Function<Function<String, String>, String> inheritedValue( final Function<Function<String, String>, String> lookup, final Setting<T> inheritedSetting ) { return new Function<Function<String, String>, String>() { @Override public String apply( Function<String, String> settings ) { String value = lookup.apply( settings ); if ( value == null ) { value = ((SettingHelper<T>) inheritedSetting).lookup( settings ); } return value; } }; } private static <T> Function<Function<String, String>, String> inheritedDefault( final Function<Function<String, String>, String> lookup, final Setting<T> inheritedSetting ) { return new Function<Function<String, String>, String>() { @Override public String apply( Function<String, String> settings ) { String value = lookup.apply( settings ); if ( value == null ) { value = ((SettingHelper<T>) inheritedSetting).defaultLookup( settings ); } return value; } }; } public static final Function<String, Integer> INTEGER = new Function<String, Integer>() { @Override public Integer apply( String value ) { try { return Integer.parseInt( value ); } catch ( NumberFormatException e ) { throw new IllegalArgumentException( "not a valid integer value" ); } } @Override public String toString() { return "an integer"; } }; public static final Function<String, Long> LONG = new Function<String, Long>() { @Override public Long apply( String value ) { try { return Long.parseLong( value ); } catch ( NumberFormatException e ) { throw new IllegalArgumentException( "not a valid long value" ); } } @Override public String toString() { return "a long"; } }; public static final Function<String, Boolean> BOOLEAN = new Function<String, Boolean>() { @Override public Boolean apply( String value ) { if ( value.equalsIgnoreCase( "true" ) ) { return true; } else if ( value.equalsIgnoreCase( "false" ) ) { return false; } else { throw new IllegalArgumentException( "must be 'true' or 'false'" ); } } @Override public String toString() { return "a boolean"; } }; public static final Function<String, Float> FLOAT = new Function<String, Float>() { @Override public Float apply( String value ) { try { return Float.parseFloat( value ); } catch ( NumberFormatException e ) { throw new IllegalArgumentException( "not a valid float value" ); } } @Override public String toString() { return "a float"; } }; public static final Function<String, Double> DOUBLE = new Function<String, Double>() { @Override public Double apply( String value ) { try { return Double.parseDouble( value ); } catch ( NumberFormatException e ) { throw new IllegalArgumentException( "not a valid double value" ); } } @Override public String toString() { return "a double"; } }; public static final Function<String, String> STRING = new Function<String, String>() { @Override public String apply( String value ) { return value.trim(); } @Override public String toString() { return "a string"; } }; public static final Function<String, HostnamePort> HOSTNAME_PORT = new Function<String, HostnamePort>() { @Override public HostnamePort apply( String value ) { return new HostnamePort( value ); } @Override public String toString() { return "a hostname and port"; } }; public static final Function<String, Long> DURATION = new Function<String, Long>() { @Override public Long apply( String value ) { return TimeUtil.parseTimeMillis.apply( value ); } @Override public String toString() { return "a duration"; } }; public static final Function<String, Long> BYTES = new Function<String, Long>() { @Override public Long apply( String value ) { try { String mem = value.toLowerCase(); long multiplier = 1; if ( mem.endsWith( "k" ) ) { multiplier = 1024; mem = mem.substring( 0, mem.length() - 1 ); } else if ( mem.endsWith( "m" ) ) { multiplier = 1024 * 1024; mem = mem.substring( 0, mem.length() - 1 ); } else if ( mem.endsWith( "g" ) ) { multiplier = 1024 * 1024 * 1024; mem = mem.substring( 0, mem.length() - 1 ); } return Long.parseLong( mem.trim() ) * multiplier; } catch ( NumberFormatException e ) { throw new IllegalArgumentException( String.format( "%s is not a valid size, must be e.g. 10, 5K, 1M, " + "11G", value ) ); } } @Override public String toString() { return "a byte size"; } }; public static final Function<String, URI> URI = new Function<String, URI>() { @Override public URI apply( String value ) { try { return new URI( value ); } catch ( URISyntaxException e ) { throw new IllegalArgumentException( "not a valid URI" ); } } @Override public String toString() { return "a URI"; } }; public static final Function<String, File> PATH = new Function<String, File>() { @Override public File apply( String setting ) { setting = FileUtils.fixSeparatorsInPath( setting ); return new File( setting ); } @Override public String toString() { return "a path"; } }; /** * For values such as: * <ul> * <li>100M</li> ==> 100 * 1024 * 1024 * <li>37261</li> ==> 37261 * <li>2g</li> ==> 2 * 1024 * 1024 * 1024 * <li>50m</li> ==> 50 * 1024 * 1024 * <li>10k</li> ==> 10 * 1024 * </ul> */ public static final Function<String, Long> LONG_WITH_OPTIONAL_UNIT = new Function<String, Long>() { @Override public Long apply( String from ) { return Config.parseLongWithUnit( from ); } }; public static <T extends Enum> Function<String, T> options( final Class<T> enumClass ) { return options( EnumSet.allOf( enumClass ) ); } public static <T> Function<String, T> options( T... optionValues ) { return Settings.<T>options( Iterables.<T,T>iterable( optionValues ) ); } public static <T> Function<String, T> options( final Iterable<T> optionValues ) { return new Function<String, T>() { @Override public T apply( String value ) { for ( T optionValue : optionValues ) { if ( optionValue.toString().equals( value ) ) { return optionValue; } } throw new IllegalArgumentException( "must be one of " + Iterables.toList( optionValues ).toString() ); } @Override public String toString() { StringBuilder builder = new StringBuilder( ); builder.append( "one of " ); String comma = ""; for ( T optionValue : optionValues ) { builder.append( comma ).append( optionValue.toString() ); comma = ", "; } return builder.toString(); } }; } public static <T> Function<String, List<T>> list( final String separator, final Function<String, T> itemParser ) { return new Function<String, List<T>>() { @Override public List<T> apply( String value ) { String[] parts = value.split( separator ); List<T> list = new ArrayList<T>(); for ( String part : parts ) { list.add( itemParser.apply( part ) ); } return list; } @Override public String toString() { return "a list separated by '"+separator+"' where items are "+itemParser.toString(); } }; } // Modifiers public static Function2<String, Function<String, String>, String> matches( final String regex ) { final Pattern pattern = Pattern.compile( regex ); return new Function2<String, Function<String, String>, String>() { @Override public String apply( String value, Function<String, String> settings ) { if ( !pattern.matcher( value ).matches() ) { throw new IllegalArgumentException( "value does not match expression:" + regex ); } return value; } }; } public static <T extends Comparable<T>> Function2<T, Function<String, String>, T> min( final T min ) { return new Function2<T, Function<String, String>, T>() { @Override public T apply( T value, Function<String, String> settings ) { if ( value != null && value.compareTo( min ) < 0 ) { throw new IllegalArgumentException( String.format( "minimum allowed value is: %s", min ) ); } return value; } }; } public static <T extends Comparable<T>> Function2<T, Function<String, String>, T> max( final T max ) { return new Function2<T, Function<String, String>, T>() { @Override public T apply( T value, Function<String, String> settings ) { if ( value != null && value.compareTo( max ) > 0 ) { throw new IllegalArgumentException( String.format( "maximum allowed value is: %s", max ) ); } return value; } }; } public static <T extends Comparable<T>> Function2<T, Function<String, String>, T> range( final T min, final T max ) { return Functions.<T, Function<String, String>>compose2().apply( min( min ), max( max ) ); } public static final Function2<Integer, Function<String, String>, Integer> port = illegalValueMessage( "must be a valid port number(1-65535)", range( 1, 65535 ) ); public static <T> Function2<T, Function<String, String>, T> illegalValueMessage( final String message, final Function2<T, Function<String, String>, T> valueFunction ) { return new Function2<T, Function<String, String>, T>() { @Override public T apply( T from1, Function<String, String> from2 ) { try { return valueFunction.apply( from1, from2 ); } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException( message ); } } }; } public static Function2<String, Function<String, String>, String> toLowerCase = new Function2<String, Function<String, String>, String>() { @Override public String apply( String value, Function<String, String> settings ) { return value.toLowerCase(); } }; public static Function2<URI, Function<String, String>, URI> normalize = new Function2<URI, Function<String, String>, URI>() { @Override public URI apply( URI value, Function<String, String> settings ) { String resultStr = value.normalize().toString(); if ( resultStr.endsWith( "/" ) ) { value = java.net.URI.create( resultStr.substring( 0, resultStr.length() - 1 ) ); } return value; } }; // Setting converters and constraints public static Function2<File, Function<String, String>, File> basePath( final Setting<File> baseSetting ) { return new Function2<File, Function<String, String>, File>() { @Override public File apply( File path, Function<String, String> settings ) { File parent = baseSetting.apply( settings ); return path.isAbsolute() ? path : new File( parent, path.getPath() ); } @Override public String toString() { return "relative to '"+baseSetting.name()+"'"; } }; } public static Function2<File, Function<String, String>, File> isFile = new Function2<File, Function<String, String>, File>() { @Override public File apply( File path, Function<String, String> settings ) { if ( path.exists() && !path.isFile() ) { throw new IllegalArgumentException( String.format( "%s must point to a file, not a directory", path.toString() ) ); } return path; } }; public static Function2<File, Function<String, String>, File> isDirectory = new Function2<File, Function<String, String>, File>() { @Override public File apply( File path, Function<String, String> settings ) { if ( path.exists() && !path.isDirectory() ) { throw new IllegalArgumentException( String.format( "%s must point to a file, not a directory", path.toString() ) ); } return path; } }; // Setting helpers private static Function<Function<String, String>, String> named( final String name ) { return new Function<Function<String, String>, String>() { @Override public String apply( Function<String, String> settings ) { return settings.apply( name ); } }; } private static Function<Function<String, String>, String> withDefault( final String defaultValue, final Function<Function<String, String>, String> lookup ) { return new Function<Function<String, String>, String>() { @Override public String apply( Function<String, String> settings ) { String value = lookup.apply( settings ); if ( value == null ) { return defaultValue; } else { return value; } } }; } private static Function<Function<String, String>, String> mandatory( final Function<Function<String, String>, String> lookup ) { return new Function<Function<String, String>, String>() { @Override public String apply( Function<String, String> settings ) { String value = lookup.apply( settings ); if ( value == null ) { throw new IllegalArgumentException( "mandatory setting is missing" ); } return value; } }; } public static boolean osIsWindows() { String nameOs = System.getProperty( "os.name" ); return nameOs.startsWith( "Windows" ); } public static boolean osIsMacOS() { String nameOs = System.getProperty( "os.name" ); return nameOs.equalsIgnoreCase( "Mac OS X" ); } private Settings() { } public static class DefaultSetting<T> implements SettingHelper<T> { private final String name; private final Function<String, T> parser; private final Function<Function<String, String>, String> valueLookup; private final Function<Function<String, String>, String> defaultLookup; private Function2<T, Function<String, String>, T>[] valueConverters; public DefaultSetting( String name, Function<String, T> parser, Function<Function<String, String>, String> valueLookup, Function<Function<String, String>, String> defaultLookup, Function2<T, Function<String, String>, T>... valueConverters ) { this.name = name; this.parser = parser; this.valueLookup = valueLookup; this.defaultLookup = defaultLookup; this.valueConverters = valueConverters; } @Override public String name() { return name; } @Override public String getDefaultValue() { return defaultLookup( Functions.<String, String>nullFunction() ); } public String lookup( Function<String, String> settings ) { return valueLookup.apply( settings ); } public String defaultLookup( Function<String, String> settings ) { return defaultLookup.apply( settings ); } @Override public T apply( Function<String, String> settings ) { // Lookup value as string String value = lookup( settings ); // Try defaults if ( value == null ) { try { value = defaultLookup( settings ); } catch ( Exception e ) { throw new IllegalArgumentException( String.format( "Missing mandatory setting '%s'", name() ) ); } } // If still null, return null if ( value == null ) { return null; } // Parse value T result; try { result = parser.apply( value ); // Apply converters and constraints for ( Function2<T, Function<String, String>, T> valueConverter : valueConverters ) { result = valueConverter.apply( result, settings ); } } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException( String.format( "Bad value '%s' for setting '%s': %s", value, name(), e.getMessage() ) ); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder( ); builder.append( name ).append( " is " ).append( parser.toString() ); if (valueConverters.length > 0) { builder.append( " which " ); for ( int i = 0; i < valueConverters.length; i++ ) { Function2<T, Function<String, String>, T> valueConverter = valueConverters[i]; if (i > 0) builder.append( ", and " ); builder.append( valueConverter ); } } return builder.toString(); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,228
private static final class ServiceRedirectClassLoader extends ClassLoader { public ServiceRedirectClassLoader(ClassLoader parent) { super(parent); } @Override public URL getResource(String name) { return name.startsWith("META-INF/services") ? super.getResource("test/"+name):super.getResource(name); } @Override public Enumeration<URL> getResources(String name) throws IOException { return name.startsWith("META-INF/services") ? super.getResources("test/"+name): super.getResources(name); } @Override public InputStream getResourceAsStream(String name) { return name.startsWith("META-INF/services") ? super.getResourceAsStream("test/"+name):super.getResourceAsStream(name); } }
false
community_kernel_src_test_java_org_neo4j_helpers_ServiceTest.java
5,229
private static final class ServiceBlockClassLoader extends ClassLoader { public ServiceBlockClassLoader(ClassLoader parent) { super(parent); } @Override public URL getResource(String name) { return name.startsWith("META-INF/services") ? null:super.getResource(name); } @Override public Enumeration<URL> getResources(String name) throws IOException { return name.startsWith("META-INF/services") ? Collections.enumeration(Collections.<URL>emptySet()): super.getResources(name); } @Override public InputStream getResourceAsStream(String name) { return name.startsWith("META-INF/services") ? null:super.getResourceAsStream(name); } }
false
community_kernel_src_test_java_org_neo4j_helpers_ServiceTest.java
5,230
public class ServiceTest { @Test public void shouldLoadServiceInDefaultEnvironment() throws Exception { FooService fooService = Service.load(FooService.class,"foo"); assertTrue( fooService instanceof BarService); } @Test public void whenContextCallsLoaderBlocksServicesFolderShouldLoadClassFromKernelClassloader() { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(new ServiceBlockClassLoader(contextClassLoader)); FooService fooService = Service.load(FooService.class,"foo"); assertTrue( fooService instanceof BarService); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } @Test public void whenContextClassLoaderOverridesServiceShouldLoadThatClass() throws Exception { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(new ServiceRedirectClassLoader(contextClassLoader)); FooService fooService = Service.load(FooService.class,"foo"); assertTrue( fooService instanceof BazService); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } @Test public void whenContextClassLoaderDuplicatesServiceShouldLoadItOnce() throws Exception { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(Service.class.getClassLoader()); Iterable<FooService> services = Service.load(FooService.class); int size = 0; for (FooService fooService : services) { size ++; } assertEquals(1,size); } finally { Thread.currentThread().setContextClassLoader(contextClassLoader); } } private static final class ServiceBlockClassLoader extends ClassLoader { public ServiceBlockClassLoader(ClassLoader parent) { super(parent); } @Override public URL getResource(String name) { return name.startsWith("META-INF/services") ? null:super.getResource(name); } @Override public Enumeration<URL> getResources(String name) throws IOException { return name.startsWith("META-INF/services") ? Collections.enumeration(Collections.<URL>emptySet()): super.getResources(name); } @Override public InputStream getResourceAsStream(String name) { return name.startsWith("META-INF/services") ? null:super.getResourceAsStream(name); } } private static final class ServiceRedirectClassLoader extends ClassLoader { public ServiceRedirectClassLoader(ClassLoader parent) { super(parent); } @Override public URL getResource(String name) { return name.startsWith("META-INF/services") ? super.getResource("test/"+name):super.getResource(name); } @Override public Enumeration<URL> getResources(String name) throws IOException { return name.startsWith("META-INF/services") ? super.getResources("test/"+name): super.getResources(name); } @Override public InputStream getResourceAsStream(String name) { return name.startsWith("META-INF/services") ? super.getResourceAsStream("test/"+name):super.getResourceAsStream(name); } } }
false
community_kernel_src_test_java_org_neo4j_helpers_ServiceTest.java
5,231
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; } }
false
community_kernel_src_main_java_org_neo4j_helpers_Service.java
5,232
{ @Override protected BufferedReader underlyingObjectToObject( URL url ) { try { return new BufferedReader( new InputStreamReader( url.openStream(), "utf-8" ) ); } catch ( IOException e ) { return null; } } } ) )
false
community_kernel_src_main_java_org_neo4j_helpers_Service.java
5,233
{ @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,234
{ @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,235
{ @Override public String apply( Function<String, String> settings ) { String value = lookup.apply( settings ); if ( value == null ) { value = ((SettingHelper<T>) inheritedSetting).defaultLookup( settings ); } return value; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,236
{ @Override public String apply( String value, Function<String, String> settings ) { return value.toLowerCase(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,237
public class StringsTest { @Test public void testDecamelize() { assertEquals( "foo", decamelize.apply( "foo" ) ); assertEquals( "foo", decamelize.apply( "Foo" ) ); assertEquals( "foo_bar", decamelize.apply( "FooBar" ) ); assertEquals( "f_b", decamelize.apply( "FB" ) ); assertEquals("_", decamelize.apply( "_" ) ); // What is expected behaviour here? // assertEquals( "f_b", decamelize.apply( "F_B" ) ); } }
false
community_kernel_src_test_java_org_neo4j_helpers_StringsTest.java
5,238
{ @Override public URI apply( URI value, Function<String, String> settings ) { String resultStr = value.normalize().toString(); if ( resultStr.endsWith( "/" ) ) { value = java.net.URI.create( resultStr.substring( 0, resultStr.length() - 1 ) ); } return value; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,239
{ @Override public String apply( String name ) { StringBuilder result = new StringBuilder(); for ( int i = 0; i < name.length(); i++ ) { char c = name.charAt( i ); if ( Character.isUpperCase( c ) ) { if ( i > 0 ) { result.append( '_' ); } result.append( Character.toLowerCase( c ) ); } else { result.append( c ); } } return result.toString(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Strings.java
5,240
public final class Strings { private Strings() { } public static final Function<String, String> decamelize = new Function<String, String>() { @Override public String apply( String name ) { StringBuilder result = new StringBuilder(); for ( int i = 0; i < name.length(); i++ ) { char c = name.charAt( i ); if ( Character.isUpperCase( c ) ) { if ( i > 0 ) { result.append( '_' ); } result.append( Character.toLowerCase( c ) ); } else { result.append( c ); } } return result.toString(); } }; }
false
community_kernel_src_main_java_org_neo4j_helpers_Strings.java
5,241
public class Stats { private final String name; protected int count; protected long total; protected long high; protected long low; public Stats( String name ) { this.name = name; } public int add( long value ) { total += value; if ( value < low ) low = value; if ( value > high ) high = value; return ++count; } public long high() { return high; } public long low() { return low; } public long average() { return total/count; } public double preciseAverage() { return (double)total/(double)count; } @Override public String toString() { StringBuilder builder = new StringBuilder( "Stats(" + name + ", " + count + "):" ); builder.append( "\n total: " + total ); builder.append( "\n avg: " + average() ); builder.append( "\n high: " + high ); builder.append( "\n low: " + low ); return builder.toString(); } }
false
community_kernel_src_main_java_org_neo4j_helpers_Stats.java
5,242
public class SillyUtils { public static void ignore( @SuppressWarnings("unused") Object value ) { // do nothing } public static <T> T nonNull( T value ) { if ( value == null ) { throw new AssertionError( "expected value to not be null" ); } return value; } }
false
community_kernel_src_main_java_org_neo4j_helpers_SillyUtils.java
5,243
public class SettingsTest { @Test public void testInteger() { Setting<Integer> setting = setting( "foo", INTEGER, "3" ); // Ok assertThat( setting.apply( map( stringMap( "foo", "4" ) ) ), equalTo( 4 ) ); // Bad try { setting.apply( map( stringMap( "foo", "bar" ) ) ); fail(); } catch ( IllegalArgumentException e ) { // Ok } } @Test public void testList() { Setting<List<Integer>> setting = setting( "foo", list( ",", INTEGER ), "1,2,3,4" ); assertThat( setting.apply( map( stringMap() ) ).toString(), equalTo( "[1, 2, 3, 4]" ) ); Setting<List<Integer>> setting2 = setting( "foo", list( ",", INTEGER ), "1,2,3,4," ); assertThat( setting2.apply( map( stringMap() ) ).toString(), equalTo( "[1, 2, 3, 4]" ) ); } @Test public void testMin() { Setting<Integer> setting = setting( "foo", INTEGER, "3", min( 2 ) ); // Ok assertThat( setting.apply( map( stringMap( "foo", "4" ) ) ), equalTo( 4 ) ); // Bad try { setting.apply( map( stringMap( "foo", "1" ) ) ); fail(); } catch ( IllegalArgumentException e ) { // Ok } } @Test public void testMax() { Setting<Integer> setting = setting( "foo", INTEGER, "3", max( 5 ) ); // Ok assertThat( setting.apply( map( stringMap( "foo", "4" ) ) ), equalTo( 4 ) ); // Bad try { setting.apply( map( stringMap( "foo", "7" ) ) ); fail(); } catch ( IllegalArgumentException e ) { // Ok } } @Test public void testRange() { Setting<Integer> setting = setting( "foo", INTEGER, "3", range( 2, 5 ) ); // Ok assertThat( setting.apply( map( stringMap( "foo", "4" ) ) ), equalTo( 4 ) ); // Bad try { setting.apply( map( stringMap( "foo", "1" ) ) ); fail(); } catch ( IllegalArgumentException e ) { // Ok } try { setting.apply( map( stringMap( "foo", "6" ) ) ); fail(); } catch ( IllegalArgumentException e ) { // Ok } } @Test public void testMatches() { Setting<String> setting = setting( "foo", STRING, "abc", matches( "a*b*c*" ) ); // Ok assertThat( setting.apply( map( stringMap( "foo", "aaabbbccc" ) ) ), equalTo( "aaabbbccc" ) ); // Bad try { setting.apply( map( stringMap( "foo", "cba" ) ) ); fail(); } catch ( IllegalArgumentException e ) { // Ok } } @Test( expected = IllegalArgumentException.class ) public void testDurationWithBrokenDefault() { // Notice that the default value is less that the minimum Setting<Long> setting = setting( "foo.bar", DURATION, "1s", min( DURATION.apply( "3s" ) ) ); setting.apply( map( stringMap() ) ); } @Test( expected = IllegalArgumentException.class ) public void testDurationWithValueNotWithinConstraint() { Setting<Long> setting = setting( "foo.bar", DURATION, "3s", min( DURATION.apply( "3s" ) ) ); setting.apply( map( stringMap( "foo.bar", "2s" ) ) ); } @Test public void testDuration() { Setting<Long> setting = setting( "foo.bar", DURATION, "3s", min( DURATION.apply( "3s" ) ) ); assertThat( setting.apply( map( stringMap( "foo.bar", "4s" ) ) ), equalTo( 4000L ) ); } @Test public void testDefault() { Setting<Integer> setting = setting( "foo", INTEGER, "3" ); // Ok assertThat( setting.apply( map( stringMap() ) ), equalTo( 3 ) ); } @Test public void testMandatory() { Setting<Integer> setting = setting( "foo", INTEGER, MANDATORY ); // Check that missing mandatory setting throws exception try { setting.apply( map( stringMap() ) ); fail(); } catch ( Exception e ) { // Ok } } @Test public void testPaths() { Setting<File> home = setting( "home", PATH, "." ); Setting<File> config = setting( "config", PATH, "config.properties", basePath( home ), isFile ); assertThat( config.apply( map( stringMap() ) ).getAbsolutePath(), equalTo( new File( ".", "config.properties" ).getAbsolutePath() ) ); } @Test public void testInheritOneLevel() { Setting<Integer> root = setting( "root", INTEGER, "4" ); Setting<Integer> setting = setting( "foo", INTEGER, root ); // Ok assertThat( setting.apply( map( stringMap( "foo", "1" ) ) ), equalTo( 1 ) ); assertThat( setting.apply( map( stringMap() ) ), equalTo( 4 ) ); } @Test public void testInheritHierarchy() { // Test hierarchies Setting<String> a = setting( "A", STRING, "A" ); // A defaults to A Setting<String> b = setting( "B", STRING, "B", a ); // B defaults to B unless A is defined Setting<String> c = setting( "C", STRING, "C", b ); // C defaults to C unless B is defined Setting<String> d = setting( "D", STRING, b ); // D defaults to B Setting<String> e = setting( "E", STRING, d ); // E defaults to D (hence B) assertThat( c.apply( map( stringMap( "C", "X" ) ) ), equalTo( "X" ) ); assertThat( c.apply( map( stringMap( "B", "X" ) ) ), equalTo( "X" ) ); assertThat( c.apply( map( stringMap( "A", "X" ) ) ), equalTo( "X" ) ); assertThat( c.apply( map( stringMap( "A", "Y", "B", "X" ) ) ), equalTo( "X" ) ); assertThat( d.apply( map( stringMap() ) ), equalTo( "B" ) ); assertThat( e.apply( map( stringMap() ) ), equalTo( "B" ) ); } @Test( expected = IllegalArgumentException.class ) public void testMandatoryApplyToInherited() { // Check that mandatory settings fail even in inherited cases Setting<String> x = setting( "X", STRING, NO_DEFAULT ); Setting<String> y = setting( "Y", STRING, MANDATORY, x ); y.apply( Functions.<String, String>nullFunction() ); } @Test public void testLogicalLogRotationThreshold() throws Exception { // WHEN Setting<Long> setting = GraphDatabaseSettings.logical_log_rotation_threshold; long defaultValue = setting.apply( map( stringMap() ) ); long kiloValue = setting.apply( map( stringMap( setting.name(), "10k" ) ) ); long megaValue = setting.apply( map( stringMap( setting.name(), "10M" ) ) ); long gigaValue = setting.apply( map( stringMap( setting.name(), "10g" ) ) ); // THEN assertThat( defaultValue, greaterThan( 0L ) ); assertEquals( 10 * 1024, kiloValue ); assertEquals( 10 * 1024 * 1024, megaValue ); assertEquals( 10L * 1024 * 1024 * 1024, gigaValue ); } }
false
community_kernel_src_test_java_org_neo4j_helpers_SettingsTest.java
5,244
public static class DefaultSetting<T> implements SettingHelper<T> { private final String name; private final Function<String, T> parser; private final Function<Function<String, String>, String> valueLookup; private final Function<Function<String, String>, String> defaultLookup; private Function2<T, Function<String, String>, T>[] valueConverters; public DefaultSetting( String name, Function<String, T> parser, Function<Function<String, String>, String> valueLookup, Function<Function<String, String>, String> defaultLookup, Function2<T, Function<String, String>, T>... valueConverters ) { this.name = name; this.parser = parser; this.valueLookup = valueLookup; this.defaultLookup = defaultLookup; this.valueConverters = valueConverters; } @Override public String name() { return name; } @Override public String getDefaultValue() { return defaultLookup( Functions.<String, String>nullFunction() ); } public String lookup( Function<String, String> settings ) { return valueLookup.apply( settings ); } public String defaultLookup( Function<String, String> settings ) { return defaultLookup.apply( settings ); } @Override public T apply( Function<String, String> settings ) { // Lookup value as string String value = lookup( settings ); // Try defaults if ( value == null ) { try { value = defaultLookup( settings ); } catch ( Exception e ) { throw new IllegalArgumentException( String.format( "Missing mandatory setting '%s'", name() ) ); } } // If still null, return null if ( value == null ) { return null; } // Parse value T result; try { result = parser.apply( value ); // Apply converters and constraints for ( Function2<T, Function<String, String>, T> valueConverter : valueConverters ) { result = valueConverter.apply( result, settings ); } } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException( String.format( "Bad value '%s' for setting '%s': %s", value, name(), e.getMessage() ) ); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder( ); builder.append( name ).append( " is " ).append( parser.toString() ); if (valueConverters.length > 0) { builder.append( " which " ); for ( int i = 0; i < valueConverters.length; i++ ) { Function2<T, Function<String, String>, T> valueConverter = valueConverters[i]; if (i > 0) builder.append( ", and " ); builder.append( valueConverter ); } } return builder.toString(); } }
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,245
{ @Override public HostnamePort apply( String value ) { return new HostnamePort( value ); } @Override public String toString() { return "a hostname and port"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,246
{ @Override public String apply( String value ) { return value.trim(); } @Override public String toString() { return "a string"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,247
{ @Override public Double apply( String value ) { try { return Double.parseDouble( value ); } catch ( NumberFormatException e ) { throw new IllegalArgumentException( "not a valid double value" ); } } @Override public String toString() { return "a double"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,248
{ @Override public Float apply( String value ) { try { return Float.parseFloat( value ); } catch ( NumberFormatException e ) { throw new IllegalArgumentException( "not a valid float value" ); } } @Override public String toString() { return "a float"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,249
{ @Override public Boolean apply( String value ) { if ( value.equalsIgnoreCase( "true" ) ) { return true; } else if ( value.equalsIgnoreCase( "false" ) ) { return false; } else { throw new IllegalArgumentException( "must be 'true' or 'false'" ); } } @Override public String toString() { return "a boolean"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,250
{ @Override public Long apply( String value ) { try { return Long.parseLong( value ); } catch ( NumberFormatException e ) { throw new IllegalArgumentException( "not a valid long value" ); } } @Override public String toString() { return "a long"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,251
{ @Override public Integer apply( String value ) { try { return Integer.parseInt( value ); } catch ( NumberFormatException e ) { throw new IllegalArgumentException( "not a valid integer value" ); } } @Override public String toString() { return "an integer"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,252
{ @Override public String apply( Function<String, String> settings ) { String value = lookup.apply( settings ); if ( value == null ) { throw new IllegalArgumentException( "mandatory setting is missing" ); } return value; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,253
{ @Override public String apply( Function<String, String> settings ) { String value = lookup.apply( settings ); if ( value == null ) { return defaultValue; } else { return value; } } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,254
{ @Override public String apply( Function<String, String> settings ) { return settings.apply( name ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,255
{ @Override public File apply( File path, Function<String, String> settings ) { if ( path.exists() && !path.isDirectory() ) { throw new IllegalArgumentException( String.format( "%s must point to a file, not a directory", path.toString() ) ); } return path; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,256
{ @Override public File apply( File path, Function<String, String> settings ) { if ( path.exists() && !path.isFile() ) { throw new IllegalArgumentException( String.format( "%s must point to a file, not a directory", path.toString() ) ); } return path; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,257
{ @Override public File apply( File path, Function<String, String> settings ) { File parent = baseSetting.apply( settings ); return path.isAbsolute() ? path : new File( parent, path.getPath() ); } @Override public String toString() { return "relative to '"+baseSetting.name()+"'"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Settings.java
5,258
{ private final Set<T> visitedItems = new HashSet<T>(); public boolean accept( T item ) { return visitedItems.add( item ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_FilteringIterable.java
5,259
{ public boolean accept( Object item ) { return item != null; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_FilteringIterable.java
5,260
public class FilteringIterator<T> extends PrefetchingIterator<T> { private final Iterator<T> source; private final Predicate<T> predicate; public FilteringIterator( Iterator<T> source, Predicate<T> predicate ) { this.source = source; this.predicate = predicate; } @Override protected T fetchNextOrNull() { while ( source.hasNext() ) { T testItem = source.next(); if ( predicate.accept( testItem ) ) { return testItem; } } return null; } public static <T> Iterator<T> notNull( Iterator<T> source ) { return new FilteringIterator<T>( source, FilteringIterable.<T>notNullPredicate() ); } public static <T> Iterator<T> noDuplicates( Iterator<T> source ) { return new FilteringIterator<T>( source, FilteringIterable.<T>noDuplicatesPredicate() ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_FilteringIterator.java
5,261
public class PositionedIterator<T> implements Iterator<T> { private Iterator<? extends T> inner; private T current; private Boolean initiated = false; /** * Creates an instance of the class, wrapping iterator * @param iterator The iterator to wrap */ public PositionedIterator(Iterator<? extends T> iterator) { inner = iterator; } public boolean hasNext() { return inner.hasNext(); } public T next() { initiated = true; current = inner.next(); return current; } public void remove() { inner.remove(); } /** * Returns the current node. Any subsequent calls to current will return the same object, * unless the next() method has been called. * @return The current node. */ public T current() { if(!initiated) return next(); return current; } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_PositionedIterator.java
5,262
public class PagingIterator<T> extends CachingIterator<T> { private final int pageSize; /** * Creates a new paging iterator with {@code source} as its underlying * {@link Iterator} to lazily get items from. * * @param source the underlying {@link Iterator} to lazily get items from. * @param pageSize the max number of items in each page. */ public PagingIterator( Iterator<T> source, int pageSize ) { super( source ); this.pageSize = pageSize; } /** * @return the page the iterator is currently at, starting a {@code 0}. * This value is based on the {@link #position()} and the page size. */ public int page() { return position()/pageSize; } /** * Sets the current page of the iterator. {@code 0} means the first page. * @param newPage the current page to set for the iterator, must be * non-negative. The next item returned by the iterator will be the first * item in that page. * @return the page before changing to the new page. */ public int page( int newPage ) { int previousPage = page(); position( newPage*pageSize ); return previousPage; } /** * Returns a new {@link Iterator} instance which exposes the current page * as its own iterator, which fetches items lazily from the underlying * iterator. It is discouraged to use an {@link Iterator} returned from * this method at the same time as using methods like {@link #next()} or * {@link #previous()}, where the results may be unpredictable. So either * use only {@link #nextPage()} (in conjunction with {@link #page(int)} if * necessary) or go with regular {@link #next()}/{@link #previous()}. * * @return the next page as an {@link Iterator}. */ public Iterator<T> nextPage() { page( page() ); return new PrefetchingIterator<T>() { private final int end = position()+pageSize; @Override protected T fetchNextOrNull() { if ( position() >= end ) { return null; } return PagingIterator.this.hasNext() ? PagingIterator.this.next() : null; } }; } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_PagingIterator.java
5,263
public abstract class NestingIterator<T, U> extends PrefetchingIterator<T> { private final Iterator<U> source; private Iterator<T> currentNestedIterator; private U currentSurfaceItem; public NestingIterator( Iterator<U> source ) { this.source = source; } protected abstract Iterator<T> createNestedIterator( U item ); public U getCurrentSurfaceItem() { if ( this.currentSurfaceItem == null ) { throw new IllegalStateException( "Has no surface item right now," + " you must do at least one next() first" ); } return this.currentSurfaceItem; } @Override protected T fetchNextOrNull() { if ( currentNestedIterator == null || !currentNestedIterator.hasNext() ) { while ( source.hasNext() ) { currentSurfaceItem = source.next(); currentNestedIterator = createNestedIterator( currentSurfaceItem ); if ( currentNestedIterator.hasNext() ) { break; } } } return currentNestedIterator != null && currentNestedIterator.hasNext() ? currentNestedIterator.next() : null; } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_NestingIterator.java
5,264
{ @Override protected Iterator<T> createNestedIterator( U item ) { return NestingIterable.this.createNestedIterator( item ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_NestingIterable.java
5,265
public abstract class NestingIterable<T, U> implements Iterable<T> { private final Iterable<U> source; public NestingIterable( Iterable<U> source ) { this.source = source; } public Iterator<T> iterator() { return new NestingIterator<T, U>( source.iterator() ) { @Override protected Iterator<T> createNestedIterator( U item ) { return NestingIterable.this.createNestedIterator( item ); } }; } protected abstract Iterator<T> createNestedIterator( U item ); }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_NestingIterable.java
5,266
public abstract class MapUtil { /** * A short-hand method for creating a {@link Map} of key/value pairs. * * @param objects alternating key and value. * @param <K> type of keys * @param <V> type of values * @return a Map with the entries supplied by {@code objects}. */ public static <K, V> Map<K, V> genericMap( Object... objects ) { return genericMap( new HashMap<K, V>(), objects ); } /** * A short-hand method for adding key/value pairs into a {@link Map}. * * @param targetMap the {@link Map} to put the objects into. * @param objects alternating key and value. * @param <K> type of keys * @param <V> type of values * @return a Map with the entries supplied by {@code objects}. */ @SuppressWarnings("unchecked") public static <K, V> Map<K, V> genericMap( Map<K, V> targetMap, Object... objects ) { int i = 0; while ( i < objects.length ) { targetMap.put( (K) objects[i++], (V) objects[i++] ); } return targetMap; } /** * A short-hand method for creating a {@link Map} of key/value pairs where * both keys and values are {@link String}s. * * @param strings alternating key and value. * @return a Map with the entries supplied by {@code strings}. */ public static Map<String, String> stringMap( String... strings ) { return genericMap( (Object[]) strings ); } /** * A short-hand method for creating a {@link Map} of key/value pairs where * both keys and values are {@link String}s. * * @param targetMap the {@link Map} to put the objects into. * @param strings alternating key and value. * @return a Map with the entries supplied by {@code strings}. */ public static Map<String, String> stringMap( Map<String, String> targetMap, String... strings ) { return genericMap( targetMap, (Object[]) strings ); } /** * A short-hand method for creating a {@link Map} of key/value pairs where * keys are {@link String}s and values are {@link Object}s. * * @param objects alternating key and value. * @return a Map with the entries supplied by {@code objects}. */ public static Map<String, Object> map( Object... objects ) { return genericMap( objects ); } /** * A short-hand method for creating a {@link Map} of key/value pairs where * keys are {@link String}s and values are {@link Object}s. * * @param targetMap the {@link Map} to put the objects into. * @param objects alternating key and value. * @return a Map with the entries supplied by {@code objects}. */ public static Map<String, Object> map( Map<String, Object> targetMap, Object... objects ) { return genericMap( targetMap, objects ); } /** * Loads a {@link Map} from a {@link Reader} assuming strings as keys * and values. * * @param reader the {@link Reader} containing a {@link Properties}-like * layout of keys and values. * @return the read data as a {@link Map}. * @throws IOException if the {@code reader} throws {@link IOException}. */ public static Map<String, String> load( Reader reader ) throws IOException { Properties props = new Properties(); props.load( reader ); return new HashMap<String, String>( (Map) props ); } /** * Loads a {@link Map} from a {@link Reader} assuming strings as keys * and values. Any {@link IOException} is wrapped and thrown as a * {@link RuntimeException} instead. * * @param reader the {@link Reader} containing a {@link Properties}-like * layout of keys and values. * @return the read data as a {@link Map}. */ public static Map<String, String> loadStrictly( Reader reader ) { try { return load( reader ); } catch ( IOException e ) { throw new RuntimeException( e ); } } /** * Loads a {@link Map} from an {@link InputStream} assuming strings as keys * and values. * * @param stream the {@link InputStream} containing a * {@link Properties}-like layout of keys and values. * @return the read data as a {@link Map}. * @throws IOException if the {@code stream} throws {@link IOException}. */ public static Map<String, String> load( InputStream stream ) throws IOException { Properties props = new Properties(); props.load( stream ); return new HashMap<String, String>( (Map) props ); } /** * Loads a {@link Map} from an {@link InputStream} assuming strings as keys * and values. Any {@link IOException} is wrapped and thrown as a * {@link RuntimeException} instead. * * @param stream the {@link InputStream} containing a * {@link Properties}-like layout of keys and values. * @return the read data as a {@link Map}. */ public static Map<String, String> loadStrictly( InputStream stream ) { try { return load( stream ); } catch ( IOException e ) { throw new RuntimeException( e ); } } /** * Loads a {@link Map} from a {@link File} assuming strings as keys * and values. * * @param file the {@link File} containing a {@link Properties}-like * layout of keys and values. * @return the read data as a {@link Map}. * @throws IOException if the file reader throws {@link IOException}. */ public static Map<String, String> load( File file ) throws IOException { FileInputStream stream = null; try { stream = new FileInputStream( file ); return load( stream ); } finally { closeIfNotNull( stream ); } } private static void closeIfNotNull( Closeable closeable ) throws IOException { if ( closeable != null ) closeable.close(); } /** * Loads a {@link Map} from a {@link File} assuming strings as keys * and values. Any {@link IOException} is wrapped and thrown as a * {@link RuntimeException} instead. * * @param file the {@link File} containing a {@link Properties}-like * layout of keys and values. * @return the read data as a {@link Map}. */ public static Map<String, String> loadStrictly( File file ) { try { return load( file ); } catch ( IOException e ) { throw new RuntimeException( e ); } } /** * Stores the data in {@code config} into {@code file} in a standard java * {@link Properties} format. * @param config the data to store in the properties file. * @param file the file to store the properties in. * @throws IOException IO error. */ public static void store( Map<String, String> config, File file ) throws IOException { OutputStream stream = null; try { stream = new BufferedOutputStream( new FileOutputStream( file ) ); store( config, stream ); } finally { closeIfNotNull( stream ); } } /** * Stores the data in {@code config} into {@code file} in a standard java * {@link Properties} format. Any {@link IOException} is wrapped and thrown as a * {@link RuntimeException} instead. * @param config the data to store in the properties file. * @param file the file to store the properties in. */ public static void storeStrictly( Map<String, String> config, File file ) { try { store( config, file ); } catch ( IOException e ) { throw new RuntimeException( e ); } } /** * Stores the data in {@code config} into {@code stream} in a standard java * {@link Properties} format. * @param config the data to store in the properties file. * @param stream the {@link OutputStream} to store the properties in. * @throws IOException IO error. */ public static void store( Map<String, String> config, OutputStream stream ) throws IOException { Properties properties = new Properties(); for ( Map.Entry<String, String> property : config.entrySet() ) { properties.setProperty( property.getKey(), property.getValue() ); } properties.store( stream, null ); } /** * Stores the data in {@code config} into {@code stream} in a standard java * {@link Properties} format. Any {@link IOException} is wrapped and thrown as a * {@link RuntimeException} instead. * @param config the data to store in the properties file. * @param stream the {@link OutputStream} to store the properties in. * @throws IOException IO error. */ public static void storeStrictly( Map<String, String> config, OutputStream stream ) { try { store( config, stream ); } catch ( IOException e ) { throw new RuntimeException( e ); } } /** * Stores the data in {@code config} into {@code writer} in a standard java * {@link Properties} format. * * @param config the data to store in the properties file. * @param writer the {@link Writer} to store the properties in. * @throws IOException IO error. */ public static void store( Map<String, String> config, Writer writer ) throws IOException { Properties properties = new Properties(); properties.putAll( config ); properties.store( writer, null ); } /** * Stores the data in {@code config} into {@code writer} in a standard java * {@link Properties} format. Any {@link IOException} is wrapped and thrown * as a {@link RuntimeException} instead. * * @param config the data to store in the properties file. * @param writer the {@link Writer} to store the properties in. * @throws IOException IO error. */ public static void storeStrictly( Map<String, String> config, Writer writer ) { try { store( config, writer ); } catch ( IOException e ) { throw new RuntimeException( e ); } } /** * Reversed a map, making the key value and the value key. * @param <K> the type of key in the map to reverse. These will be the * values in the returned map. * @param <V> the type of values in the map to revert. These will be the * keys in the returned map. * @param map the {@link Map} to reverse. * @return the reverse of {@code map}. A new {@link Map} will be returned * where the keys from {@code map} will be the values and the values will * be the keys. */ public static <K, V> Map<V, K> reverse( Map<K, V> map ) { Map<V, K> reversedMap = new HashMap<V, K>(); for ( Map.Entry<K, V> entry : map.entrySet() ) { reversedMap.put( entry.getValue(), entry.getKey() ); } return reversedMap; } public static <K, V> Map<K, V> copyAndPut(Map<K, V> map, K key, V value) { Map<K, V> copy = new HashMap<K, V>( map ); copy.put( key, value); return copy; } public static <K, V> Map<K, V> copyAndRemove(Map<K, V> map, K key) { Map<K, V> copy = new HashMap<K, V>( map ); copy.remove( key ); return copy; } public static <K,V> Map<K, V> toMap( Iterable<Pair<K, V>> pairs ) { return toMap( pairs.iterator() ); } public static <K,V> Map<K, V> toMap( Iterator<Pair<K, V>> pairs ) { Map<K,V> result = new HashMap<K,V>(); while(pairs.hasNext()) { Pair<K,V> pair = pairs.next(); result.put(pair.first(), pair.other()); } return result; } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_MapUtil.java
5,267
public class LruMap<K, V> extends LinkedHashMap<K,V > { private final int maxEntries; public LruMap( int maxEntries ) { super( maxEntries, 1.0f, true ); this.maxEntries = maxEntries; } @Override protected boolean removeEldestEntry(final Map.Entry<K, V> eldest) { return super.size() > maxEntries; } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_LruMap.java
5,268
public class LinesOfFileIterator extends PrefetchingIterator<String> implements ClosableIterator<String> { private final BufferedReader reader; private boolean closed; public LinesOfFileIterator( File file, String encoding ) throws IOException { try { reader = new BufferedReader( new InputStreamReader(new FileInputStream(file), encoding) ); } catch ( FileNotFoundException e ) { throw new RuntimeException( e ); } } @Override protected String fetchNextOrNull() { if ( closed ) return null; try { String line = reader.readLine(); if ( line == null ) close(); return line; } catch ( IOException e ) { close(); throw new RuntimeException( e ); } } public void close() { if ( closed ) return; try { reader.close(); } catch ( IOException e ) { // Couldn't close e.printStackTrace(); } finally { closed = true; } } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_LinesOfFileIterator.java
5,269
public class LimitingIterator<T> extends PrefetchingIterator<T> { private int returned; private final Iterator<T> source; private final int limit; /** * Instantiates a new limiting iterator which iterates over {@code source} * and if {@code limit} items have been returned the next {@link #hasNext()} * will return {@code false}. * * @param source the source of items. * @param limit the limit, i.e. the max number of items to return. */ public LimitingIterator( Iterator<T> source, int limit ) { this.source = source; this.limit = limit; } @Override protected T fetchNextOrNull() { if ( !source.hasNext() || returned >= limit ) return null; try { return source.next(); } finally { returned++; } } /** * @return {@code true} if the number of items returned up to this point * is equal to the limit given in the constructor, otherwise {@code false}. */ public boolean limitReached() { return returned == limit; } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_LimitingIterator.java
5,270
public class LimitingIterable<T> implements Iterable<T> { private final Iterable<T> source; private final int limit; /** * Instantiates a new limiting {@link Iterable} which can limit the number * of items returned from iterators it spawns. * * @param source the source of items. * @param limit the limit, i.e. the max number of items to return. */ public LimitingIterable( Iterable<T> source, int limit ) { this.source = source; this.limit = limit; } @Override public Iterator<T> iterator() { return new LimitingIterator<T>( source.iterator(), limit ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_LimitingIterable.java
5,271
public abstract class IteratorWrapper<T, U> implements Iterator<T> { private Iterator<U> source; public IteratorWrapper( Iterator<U> iteratorToWrap ) { this.source = iteratorToWrap; } public boolean hasNext() { return this.source.hasNext(); } public T next() { return underlyingObjectToObject( this.source.next() ); } public void remove() { this.source.remove(); } protected abstract T underlyingObjectToObject( U object ); }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorWrapper.java
5,272
{ { next( item ); } @Override protected void computeNext() { endReached(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,273
{ private int index; @Override protected T fetchNextOrNull() { try { return index < array.length && index < maxItems ? array[index] : null; } finally { index++; } } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,274
{ private int index; @Override protected Long fetchNextOrNull() { try { return index < array.length ? array[index] : null; } finally { index++; } } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,275
{ @Override public Iterator<T> iterator() { return IteratorUtil.iterator( array ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,276
{ @Override public Iterator<Long> iterator() { return asIterator( array ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,277
{ 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(); } } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,278
{ @Override public String apply( Enum from ) { return from.name(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,279
{ @Override public Iterator<T> iterator() { return iterator; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_IteratorUtil.java
5,280
{ @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,281
{ private final int end = position()+pageSize; @Override protected T fetchNextOrNull() { if ( position() >= end ) { return null; } return PagingIterator.this.hasNext() ? PagingIterator.this.next() : null; } };
false
community_kernel_src_main_java_org_neo4j_helpers_collection_PagingIterator.java
5,282
public abstract class PrefetchingIterator<T> implements Iterator<T> { boolean hasFetchedNext; T nextObject; /** * Tries to fetch the next item and caches it so that consecutive calls * (w/o an intermediate call to {@link #next()} will remember it and won't * try to fetch it again. * * @return {@code true} if there was a next item to return in the next * call to {@link #next()}. */ public boolean hasNext() { if ( hasFetchedNext ) { return getPrefetchedNextOrNull() != null; } T nextOrNull = fetchNextOrNull(); hasFetchedNext = true; if ( nextOrNull != null ) { setPrefetchedNext( nextOrNull ); } return nextOrNull != null; } /** * Uses {@link #hasNext()} to try to fetch the next item and returns it * if found, otherwise it throws a {@link NoSuchElementException}. * * @return the next item in the iteration, or throws * {@link NoSuchElementException} if there's no more items to return. */ public T next() { if ( !hasNext() ) { throw new NoSuchElementException(); } T result = getPrefetchedNextOrNull(); setPrefetchedNext( null ); hasFetchedNext = false; return result; } protected abstract T fetchNextOrNull(); protected void setPrefetchedNext( T nextOrNull ) { this.nextObject = nextOrNull; } protected T getPrefetchedNextOrNull() { return nextObject; } public void remove() { throw new UnsupportedOperationException(); } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_PrefetchingIterator.java
5,283
public class FirstItemIterable<T> implements Iterable<T> { private final T first; private final Iterator<T> iterator; private int pos = -1; public FirstItemIterable(Iterable<T> data) { this(data.iterator()); } public FirstItemIterable(Iterator<T> iterator) { this.iterator = iterator; if (iterator.hasNext()) { this.first = iterator.next(); this.pos = 0; } else { this.first = null; } } @Override public Iterator<T> iterator() { 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() { } }; } public T getFirst() { return first; } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_FirstItemIterable.java
5,284
public abstract class PrefetchingResourceIterator<T> extends PrefetchingIterator<T> implements ResourceIterator<T> { }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_PrefetchingResourceIterator.java
5,285
static final class MultiPartProgressListener extends ProgressListener { private final Aggregator aggregator; final String part; boolean started = false; private long value = 0, lastReported = 0; final long totalCount; MultiPartProgressListener( Aggregator aggregator, String part, long totalCount ) { this.aggregator = aggregator; this.part = part; this.totalCount = totalCount; } @Override public void started() { if ( !started ) { aggregator.start( this ); started = true; } } @Override public void set( long progress ) { update( value = progress ); } @Override public void add( long progress ) { update( value += progress ); } @Override public void done() { set( totalCount ); aggregator.complete( this ); } @Override public void failed( Throwable e ) { aggregator.signalFailure( part, e ); } private void update( long progress ) { started(); if ( progress > lastReported ) { aggregator.update( progress - lastReported ); lastReported = progress; } } enum State { INIT, LIVE } }
false
community_kernel_src_main_java_org_neo4j_helpers_progress_ProgressListener.java
5,286
{ @Override public void started() { // do nothing } @Override public void set( long progress ) { // do nothing } @Override public void add( long progress ) { // do nothing } @Override public void done() { // do nothing } @Override public void failed( Throwable e ) { // do nothing } };
false
community_kernel_src_main_java_org_neo4j_helpers_progress_ProgressListener.java
5,287
public abstract class ProgressListener { public abstract void started(); public abstract void set( long progress ); public abstract void add( long progress ); public abstract void done(); public abstract void failed( Throwable e ); public static final ProgressListener NONE = new ProgressListener() { @Override public void started() { // do nothing } @Override public void set( long progress ) { // do nothing } @Override public void add( long progress ) { // do nothing } @Override public void done() { // do nothing } @Override public void failed( Throwable e ) { // do nothing } }; 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; } } } static final class OpenEndedProgressListener extends SinglePartProgressListener { private int lastReported = 0; OpenEndedProgressListener( Indicator indicator ) { super( indicator, 0 ); } @Override public void done() { indicator.completeProcess(); } @Override void update( long progress ) { started(); int current = (int) (progress / indicator.reportResolution()); if ( current > lastReported ) { indicator.progress( lastReported, current ); lastReported = current; } } } static final class MultiPartProgressListener extends ProgressListener { private final Aggregator aggregator; final String part; boolean started = false; private long value = 0, lastReported = 0; final long totalCount; MultiPartProgressListener( Aggregator aggregator, String part, long totalCount ) { this.aggregator = aggregator; this.part = part; this.totalCount = totalCount; } @Override public void started() { if ( !started ) { aggregator.start( this ); started = true; } } @Override public void set( long progress ) { update( value = progress ); } @Override public void add( long progress ) { update( value += progress ); } @Override public void done() { set( totalCount ); aggregator.complete( this ); } @Override public void failed( Throwable e ) { aggregator.signalFailure( part, e ); } private void update( long progress ) { started(); if ( progress > lastReported ) { aggregator.update( progress - lastReported ); lastReported = progress; } } enum State { INIT, LIVE } } private ProgressListener() { // only internal implementations } }
false
community_kernel_src_main_java_org_neo4j_helpers_progress_ProgressListener.java
5,288
static class Textual extends Indicator { private final String process; private final PrintWriter out; Textual( String process, PrintWriter out ) { super( 200 ); this.process = process; this.out = out; } @Override public void startProcess( long totalCount ) { out.println( process ); out.flush(); } @Override protected void progress( int from, int to ) { for ( int i = from; i < to; ) { printProgress( ++i ); } out.flush(); } @Override public void failure( Throwable cause ) { cause.printStackTrace( out ); } private void printProgress( int progress ) { out.print( '.' ); if ( progress % 20 == 0 ) { out.printf( " %3d%%%n", progress / 2 ); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_progress_Indicator.java
5,289
static class OpenEndedTextual extends OpenEnded { private final String process; private final PrintWriter out; private int dots; OpenEndedTextual( String process, PrintWriter out, int reportResolution ) { super( reportResolution ); this.process = process; this.out = out; } @Override public void startProcess( long totalCount ) { out.println( process ); out.flush(); } @Override public void completeProcess() { for ( int i = dots; i < 20; i++ ) { out.print( " " ); } out.println( " done" ); out.flush(); } @Override protected void progress( int from, int to ) { for ( int i = from; i < to; ) { printProgress( ++i ); } out.flush(); } @Override public void failure( Throwable cause ) { cause.printStackTrace( out ); } private void printProgress( int progress ) { out.print( '.' ); dots++; if ( progress % 20 == 0 ) { out.printf( " %7d%n", ((long) progress) * reportResolution() ); dots = 0; } } }
false
community_kernel_src_main_java_org_neo4j_helpers_progress_Indicator.java
5,290
public static abstract class OpenEnded extends Indicator { public OpenEnded( int reportResolution ) { super( reportResolution ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_progress_Indicator.java
5,291
public static abstract class Decorator extends Indicator.OpenEnded { private final Indicator indicator; /** Constructor for regular indicators. */ public Decorator( ProgressMonitorFactory factory, String process ) { this( factory.newIndicator( process ) ); } /** Constructor for open ended indicators. */ public Decorator( ProgressMonitorFactory factory, String process, int resolution ) { this( factory.newOpenEndedIndicator( process, resolution ) ); } public Decorator( Indicator indicator ) { super( indicator.reportResolution() ); this.indicator = indicator; } @Override public void startProcess( long totalCount ) { indicator.startProcess( totalCount ); } @Override public void startPart( String part, long totalCount ) { indicator.startPart( part, totalCount ); } @Override public void completePart( String part ) { indicator.completePart( part ); } @Override public void completeProcess() { indicator.completeProcess(); } @Override protected void progress( int from, int to ) { indicator.progress( from, to ); } @Override public void failure( Throwable cause ) { indicator.failure( cause ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_progress_Indicator.java
5,292
{ @Override protected void progress( int from, int to ) { // do nothing } };
false
community_kernel_src_main_java_org_neo4j_helpers_progress_Indicator.java
5,293
public abstract class Indicator { static final Indicator.OpenEnded NONE = new Indicator.OpenEnded( 1 ) { @Override protected void progress( int from, int to ) { // do nothing } }; public static abstract class OpenEnded extends Indicator { public OpenEnded( int reportResolution ) { super( reportResolution ); } } private final int reportResolution; public Indicator( int reportResolution ) { this.reportResolution = reportResolution; } protected abstract void progress( int from, int to ); int reportResolution() { return reportResolution; } public void startProcess( long totalCount ) { // default: do nothing } public void startPart( String part, long totalCount ) { // default: do nothing } public void completePart( String part ) { // default: do nothing } public void completeProcess() { // default: do nothing } public void failure( Throwable cause ) { // default: do nothing } public static abstract class Decorator extends Indicator.OpenEnded { private final Indicator indicator; /** Constructor for regular indicators. */ public Decorator( ProgressMonitorFactory factory, String process ) { this( factory.newIndicator( process ) ); } /** Constructor for open ended indicators. */ public Decorator( ProgressMonitorFactory factory, String process, int resolution ) { this( factory.newOpenEndedIndicator( process, resolution ) ); } public Decorator( Indicator indicator ) { super( indicator.reportResolution() ); this.indicator = indicator; } @Override public void startProcess( long totalCount ) { indicator.startProcess( totalCount ); } @Override public void startPart( String part, long totalCount ) { indicator.startPart( part, totalCount ); } @Override public void completePart( String part ) { indicator.completePart( part ); } @Override public void completeProcess() { indicator.completeProcess(); } @Override protected void progress( int from, int to ) { indicator.progress( from, to ); } @Override public void failure( Throwable cause ) { indicator.failure( cause ); } } static class Textual extends Indicator { private final String process; private final PrintWriter out; Textual( String process, PrintWriter out ) { super( 200 ); this.process = process; this.out = out; } @Override public void startProcess( long totalCount ) { out.println( process ); out.flush(); } @Override protected void progress( int from, int to ) { for ( int i = from; i < to; ) { printProgress( ++i ); } out.flush(); } @Override public void failure( Throwable cause ) { cause.printStackTrace( out ); } private void printProgress( int progress ) { out.print( '.' ); if ( progress % 20 == 0 ) { out.printf( " %3d%%%n", progress / 2 ); } } } static class OpenEndedTextual extends OpenEnded { private final String process; private final PrintWriter out; private int dots; OpenEndedTextual( String process, PrintWriter out, int reportResolution ) { super( reportResolution ); this.process = process; this.out = out; } @Override public void startProcess( long totalCount ) { out.println( process ); out.flush(); } @Override public void completeProcess() { for ( int i = dots; i < 20; i++ ) { out.print( " " ); } out.println( " done" ); out.flush(); } @Override protected void progress( int from, int to ) { for ( int i = from; i < to; ) { printProgress( ++i ); } out.flush(); } @Override public void failure( Throwable cause ) { cause.printStackTrace( out ); } private void printProgress( int progress ) { out.print( '.' ); dots++; if ( progress % 20 == 0 ) { out.printf( " %7d%n", ((long) progress) * reportResolution() ); dots = 0; } } } }
false
community_kernel_src_main_java_org_neo4j_helpers_progress_Indicator.java
5,294
private static final class CountDown implements Runnable { private final CountDownLatch latch; CountDown( CountDownLatch latch ) { this.latch = latch; } @Override public void run() { latch.countDown(); } }
false
community_kernel_src_main_java_org_neo4j_helpers_progress_Completion.java
5,295
public final class Completion { private volatile Collection<Runnable> callbacks = new ArrayList<>(); private final List<ProcessFailureException.Entry> processFailureCauses = new ArrayList<>(); @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") void complete() { Collection<Runnable> callbacks = this.callbacks; if ( callbacks != null ) { Runnable[] targets; synchronized ( callbacks ) { targets = callbacks.toArray( new Runnable[callbacks.size()] ); this.callbacks = null; } for ( Runnable target : targets ) { try { target.run(); } catch ( Exception e ) { e.printStackTrace(); } } } } void signalFailure( String part, Throwable e ) { processFailureCauses.add( new ProcessFailureException.Entry( part, e ) ); complete(); } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") void notify( Runnable callback ) { if ( callback == null ) { throw new IllegalArgumentException( "callback may not be null" ); } Collection<Runnable> callbacks = this.callbacks; if ( callbacks != null ) { synchronized ( callbacks ) { if ( this.callbacks == callbacks ) { // double checked locking callbacks.add( callback ); callback = null; // we have not reached completion } } } if ( callback != null ) { // we have already reached completion callback.run(); } } @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") public void await( long timeout, TimeUnit unit ) throws InterruptedException, TimeoutException, ProcessFailureException { CountDownLatch latch = null; Collection<Runnable> callbacks = this.callbacks; if ( callbacks != null ) { synchronized ( callbacks ) { if ( this.callbacks == callbacks ) { // double checked locking callbacks.add( new CountDown( latch = new CountDownLatch( 1 ) ) ); } } } if ( latch != null ) { // await completion if ( !latch.await( timeout, unit ) ) { throw new TimeoutException( String.format( "Process did not complete within %d %s.", timeout, unit.name() ) ); } } if ( !processFailureCauses.isEmpty() ) { throw new ProcessFailureException( processFailureCauses ); } } private static final class CountDown implements Runnable { private final CountDownLatch latch; CountDown( CountDownLatch latch ) { this.latch = latch; } @Override public void run() { latch.countDown(); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_progress_Completion.java
5,296
final class Aggregator { private final Map<ProgressListener.MultiPartProgressListener, ProgressListener.MultiPartProgressListener.State> states = new ConcurrentHashMap<>(); private Indicator indicator; @SuppressWarnings("unused"/*accessed through updater*/) private volatile long progress; @SuppressWarnings("unused"/*accessed through updater*/) private volatile int last; private static final AtomicLongFieldUpdater<Aggregator> PROGRESS = newUpdater( Aggregator.class, "progress" ); private static final AtomicIntegerFieldUpdater<Aggregator> LAST = AtomicIntegerFieldUpdater.newUpdater( Aggregator.class, "last" ); private long totalCount = 0; private final Completion completion = new Completion(); public Aggregator( Indicator indicator ) { this.indicator = indicator; } synchronized void add( ProgressListener.MultiPartProgressListener progress ) { states.put( progress, ProgressListener.MultiPartProgressListener.State.INIT ); this.totalCount += progress.totalCount; } synchronized Completion initialize() { indicator.startProcess( totalCount ); if ( states.isEmpty() ) { indicator.progress( 0, indicator.reportResolution() ); indicator.completeProcess(); } return completion; } void update( long delta ) { long progress = PROGRESS.addAndGet( this, delta ); int current = (int) ((progress * indicator.reportResolution()) / totalCount); for ( int last = this.last; current > last; last = this.last ) { if ( LAST.compareAndSet( this, last, current ) ) { synchronized ( this ) { indicator.progress( last, current ); } } } } void start( ProgressListener.MultiPartProgressListener part ) { if ( states.put( part, ProgressListener.MultiPartProgressListener.State.LIVE ) == ProgressListener .MultiPartProgressListener.State.INIT ) { indicator.startPart( part.part, part.totalCount ); } } void complete( ProgressListener.MultiPartProgressListener part ) { if ( states.remove( part ) != null ) { indicator.completePart( part.part ); if ( states.isEmpty() ) { indicator.completeProcess(); completion.complete(); } } } public void signalFailure( String part, Throwable e ) { completion.signalFailure( part, e ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_progress_Aggregator.java
5,297
class WrappingResourceIterator<T> implements ResourceIterator<T> { private final Iterator<T> iterator; boolean hasNext; public WrappingResourceIterator( Iterator<T> iterator ) { this.iterator = iterator; hasNext = iterator.hasNext(); } @Override public void close() { hasNext = false; } @Override public boolean hasNext() { return hasNext; } @Override public T next() { assertHasNext(); T result = iterator.next(); hasNext = iterator.hasNext(); return result; } @Override public void remove() { assertHasNext(); try { iterator.remove(); } finally { hasNext = iterator.hasNext(); } } private void assertHasNext() { if ( ! hasNext ) { throw new IllegalArgumentException( "Iterator already closed" ); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_WrappingResourceIterator.java
5,298
final class SafeGenerics { /** * Useful for determining "is this an object that can visit the things I can provide?" * * Checks if the passed in object is a {@link Visitor} and if the objects it can * {@link Visitor#visit(Object) visit} is compatible (super type of) with the provided type. Returns the * visitor cast to compatible type parameters. If the passed in object is not an instance of {@link Visitor}, * or if it is a {@link Visitor} but one that {@link Visitor#visit(Object) visits} another type of object, this * method returns {@code null}. */ @SuppressWarnings("unchecked"/*checked through reflection*/) public static <T, F extends Exception> Visitor<? super T, ? extends F> castOrNull( Class<T> eType, Class<F> fType, Object visitor ) { if ( visitor instanceof Visitor<?, ?> ) { for ( Type iface : visitor.getClass().getGenericInterfaces() ) { if ( iface instanceof ParameterizedType ) { ParameterizedType paramType = (ParameterizedType) iface; if ( paramType.getRawType() == Visitor.class ) { Type arg = paramType.getActualTypeArguments()[0]; if ( arg instanceof ParameterizedType ) { arg = ((ParameterizedType) arg).getRawType(); } if ( (arg instanceof Class<?>) && ((Class<?>) arg).isAssignableFrom( eType ) ) { return (Visitor<? super T, ? extends F>) visitor; } } } } } return null; } private SafeGenerics() { } }
false
community_kernel_src_main_java_org_neo4j_helpers_collection_Visitor.java
5,299
public class TestCommonIterators { @Test public void testNoDuplicatesFilteringIterator() { List<Integer> ints = Arrays.asList( 1, 2, 2, 40, 100, 40, 101, 2, 3 ); Iterator<Integer> iterator = FilteringIterator.noDuplicates( ints.iterator() ); assertEquals( (Integer) 1, iterator.next() ); assertEquals( (Integer) 2, iterator.next() ); assertEquals( (Integer) 40, iterator.next() ); assertEquals( (Integer) 100, iterator.next() ); assertEquals( (Integer) 101, iterator.next() ); assertEquals( (Integer) 3, iterator.next() ); } @Test public void testCachingIterator() { Iterator<Integer> source = new RangeIterator( 8 ); CachingIterator<Integer> caching = new CachingIterator<Integer>( source ); try { caching.previous(); fail( "Should throw exception" ); } catch ( NoSuchElementException e ) { /* Good */ } try { caching.current(); fail( "Should throw exception" ); } catch ( NoSuchElementException e ) { /* Good */ } // Next and previous assertEquals( 0, caching.position() ); assertTrue( caching.hasNext() ); assertEquals( 0, caching.position() ); assertFalse( caching.hasPrevious() ); assertEquals( (Integer) 0, caching.next() ); assertTrue( caching.hasNext() ); assertTrue( caching.hasPrevious() ); assertEquals( (Integer) 1, caching.next() ); assertTrue( caching.hasPrevious() ); assertEquals( (Integer) 1, caching.current() ); assertEquals( (Integer) 2, caching.next() ); assertEquals( (Integer) 2, caching.current() ); assertEquals( (Integer) 3, (Integer) caching.position() ); assertEquals( (Integer) 2, caching.current() ); assertTrue( caching.hasPrevious() ); assertEquals( (Integer) 2, caching.previous() ); assertEquals( (Integer) 2, caching.current() ); assertEquals( (Integer) 2, (Integer) caching.position() ); assertEquals( (Integer) 1, caching.previous() ); assertEquals( (Integer) 1, caching.current() ); assertEquals( (Integer) 1, (Integer) caching.position() ); assertEquals( (Integer) 0, caching.previous() ); assertEquals( (Integer) 0, (Integer) caching.position() ); assertFalse( caching.hasPrevious() ); // Positioning try { caching.position( -1 ); fail( "Shouldn't be able to set a lower value than 0" ); } catch ( IllegalArgumentException e ) { /* Good */ } assertEquals( (Integer) 0, caching.current() ); assertEquals( 0, caching.position( 3 ) ); try { caching.current(); fail( "Shouldn't be able to call current() after a call to position(int)" ); } catch ( NoSuchElementException e ) { /* Good */ } assertTrue( caching.hasNext() ); assertEquals( (Integer) 3, caching.next() ); assertEquals( (Integer) 3, caching.current() ); assertTrue( caching.hasPrevious() ); assertEquals( (Integer) 4, caching.next() ); assertEquals( 5, caching.position() ); assertEquals( (Integer) 4, caching.previous() ); assertEquals( (Integer) 4, caching.current() ); assertEquals( (Integer) 4, caching.current() ); assertEquals( 4, caching.position() ); assertEquals( (Integer) 3, caching.previous() ); assertEquals( 3, caching.position() ); try { caching.position( 9 ); fail( "Shouldn't be able to set a position which is too big" ); } catch ( NoSuchElementException e ) { /* Good */ } assertEquals( 3, caching.position( 8 ) ); assertTrue( caching.hasPrevious() ); assertFalse( caching.hasNext() ); try { caching.next(); fail( "Shouldn't be able to go beyond last item" ); } catch ( NoSuchElementException e ) { /* Good */ } assertEquals( 8, caching.position() ); assertEquals( (Integer) 7, caching.previous() ); assertEquals( (Integer) 6, caching.previous() ); assertEquals( 6, caching.position( 0 ) ); assertEquals( (Integer) 0, caching.next() ); } @Test public void testPagingIterator() { Iterator<Integer> source = new RangeIterator( 24 ); PagingIterator<Integer> pager = new PagingIterator<Integer>( source, 10 ); assertEquals( 0, pager.page() ); assertTrue( pager.hasNext() ); assertPage( pager.nextPage(), 10, 0 ); assertTrue( pager.hasNext() ); assertEquals( 1, pager.page() ); assertTrue( pager.hasNext() ); assertPage( pager.nextPage(), 10, 10 ); assertTrue( pager.hasNext() ); assertEquals( 2, pager.page() ); assertTrue( pager.hasNext() ); assertPage( pager.nextPage(), 4, 20 ); assertFalse( pager.hasNext() ); pager.page( 1 ); assertEquals( 1, pager.page() ); assertTrue( pager.hasNext() ); assertPage( pager.nextPage(), 10, 10 ); assertTrue( pager.hasNext() ); } private void assertPage( Iterator<Integer> page, int size, int plus ) { for ( int i = 0; i < size; i++ ) { assertTrue( page.hasNext() ); assertEquals( (Integer) (i+plus), page.next() ); } assertFalse( page.hasNext() ); } @Test public void testFirstElement() { Object object = new Object(); Object object2 = new Object(); // first Iterable assertEquals( object, IteratorUtil.first( Arrays.asList( object, object2 ) ) ); assertEquals( object, IteratorUtil.first( Arrays.asList( object ) ) ); try { IteratorUtil.first( Arrays.asList() ); fail( "Should fail" ); } catch ( NoSuchElementException e ) { /* Good */ } // first Iterator assertEquals( object, IteratorUtil.first( Arrays.asList( object, object2 ).iterator() ) ); assertEquals( object, IteratorUtil.first( Arrays.asList( object ).iterator() ) ); try { IteratorUtil.first( Arrays.asList().iterator() ); fail( "Should fail" ); } catch ( NoSuchElementException e ) { /* Good */ } // firstOrNull Iterable assertEquals( object, IteratorUtil.firstOrNull( Arrays.asList( object, object2 ) ) ); assertEquals( object, IteratorUtil.firstOrNull( Arrays.asList( object ) ) ); assertNull( IteratorUtil.firstOrNull( Arrays.asList() ) ); // firstOrNull Iterator assertEquals( object, IteratorUtil.firstOrNull( Arrays.asList( object, object2 ).iterator() ) ); assertEquals( object, IteratorUtil.firstOrNull( Arrays.asList( object ).iterator() ) ); assertNull( IteratorUtil.firstOrNull( Arrays.asList().iterator() ) ); } @Test public void testLastElement() { Object object = new Object(); Object object2 = new Object(); // last Iterable assertEquals( object2, IteratorUtil.last( Arrays.asList( object, object2 ) ) ); assertEquals( object, IteratorUtil.last( Arrays.asList( object ) ) ); try { IteratorUtil.last( Arrays.asList() ); fail( "Should fail" ); } catch ( NoSuchElementException e ) { /* Good */ } // last Iterator assertEquals( object2, IteratorUtil.last( Arrays.asList( object, object2 ).iterator() ) ); assertEquals( object, IteratorUtil.last( Arrays.asList( object ).iterator() ) ); try { IteratorUtil.last( Arrays.asList().iterator() ); fail( "Should fail" ); } catch ( NoSuchElementException e ) { /* Good */ } // lastOrNull Iterable assertEquals( object2, IteratorUtil.lastOrNull( Arrays.asList( object, object2 ) ) ); assertEquals( object, IteratorUtil.lastOrNull( Arrays.asList( object ) ) ); assertNull( IteratorUtil.lastOrNull( Arrays.asList() ) ); // lastOrNull Iterator assertEquals( object2, IteratorUtil.lastOrNull( Arrays.asList( object, object2 ).iterator() ) ); assertEquals( object, IteratorUtil.lastOrNull( Arrays.asList( object ).iterator() ) ); assertNull( IteratorUtil.lastOrNull( Arrays.asList().iterator() ) ); } @Test public void testSingleElement() { Object object = new Object(); Object object2 = new Object(); // single Iterable assertEquals( object, IteratorUtil.single( Arrays.asList( object ) ) ); try { IteratorUtil.single( Arrays.asList() ); fail( "Should fail" ); } catch ( Exception e ) { /* Good */ } try { IteratorUtil.single( Arrays.asList( object, object2 ) ); fail( "Should fail" ); } catch ( Exception e ) { /* Good */ } // single Iterator assertEquals( object, IteratorUtil.single( Arrays.asList( object ).iterator() ) ); try { IteratorUtil.single( Arrays.asList().iterator() ); fail( "Should fail" ); } catch ( Exception e ) { /* Good */ } try { IteratorUtil.single( Arrays.asList( object, object2 ).iterator() ); fail( "Should fail" ); } catch ( Exception e ) { /* Good */ } // singleOrNull Iterable assertEquals( object, IteratorUtil.singleOrNull( Arrays.asList( object ) ) ); assertNull( IteratorUtil.singleOrNull( Arrays.asList() ) ); try { IteratorUtil.singleOrNull( Arrays.asList( object, object2 ) ); fail( "Should fail" ); } catch ( Exception e ) { /* Good */ } // singleOrNull Iterator assertEquals( object, IteratorUtil.singleOrNull( Arrays.asList( object ).iterator() ) ); assertNull( IteratorUtil.singleOrNull( Arrays.asList().iterator() ) ); try { IteratorUtil.singleOrNull( Arrays.asList( object, object2 ).iterator() ); fail( "Should fail" ); } catch ( Exception e ) { /* Good */ } } @Test public void getItemFromEnd() { Iterable<Integer> ints = Arrays.asList( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ); assertEquals( (Integer) 9, IteratorUtil.fromEnd( ints, 0 ) ); assertEquals( (Integer) 8, IteratorUtil.fromEnd( ints, 1 ) ); assertEquals( (Integer) 7, IteratorUtil.fromEnd( ints, 2 ) ); } @Test public void fileAsIterator() throws Exception { String[] lines = new String[] { "first line", "second line and we're still good", "", "last line" }; File file = createTextFileWithLines( lines ); try { Iterable<String> iterable = IteratorUtil.asIterable( file, "UTF-8" ); assertEquals( Arrays.asList( lines ), IteratorUtil.asCollection( iterable ) ); } finally { file.delete(); } } private File createTextFileWithLines( String[] lines ) throws IOException { File file = File.createTempFile( "lines", "neo4j" ); PrintStream out = new PrintStream( file ); for ( String line : lines ) { out.println( line ); } out.close(); return file; } }
false
community_kernel_src_test_java_org_neo4j_helpers_collection_TestCommonIterators.java