Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
5,400
{ @SuppressWarnings( { "rawtypes", "unchecked" } ) @Override protected int compareNodes( Node endNode1, Node endNode2 ) { Comparable p1 = (Comparable) endNode1.getProperty( propertyKey ); Comparable p2 = (Comparable) endNode2.getProperty( propertyKey ); if ( p1 == p2 ) { return 0; } else if ( p1 == null ) { return Integer.MIN_VALUE; } else if ( p2 == null ) { return Integer.MAX_VALUE; } else { return p1.compareTo( p2 ); } } };
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Sorting.java
5,401
public abstract class Sorting { // No instances private Sorting() { } /** * Sorts {@link Path}s by the property value of each path's end node. * * @param propertyKey the property key of the values to sort on. * @return a {@link Comparator} suitable for sorting traversal results. */ public static Comparator<? super Path> endNodeProperty( final String propertyKey ) { return new EndNodeComparator() { @SuppressWarnings( { "rawtypes", "unchecked" } ) @Override protected int compareNodes( Node endNode1, Node endNode2 ) { Comparable p1 = (Comparable) endNode1.getProperty( propertyKey ); Comparable p2 = (Comparable) endNode2.getProperty( propertyKey ); if ( p1 == p2 ) { return 0; } else if ( p1 == null ) { return Integer.MIN_VALUE; } else if ( p2 == null ) { return Integer.MAX_VALUE; } else { return p1.compareTo( p2 ); } } }; } /** * Sorts {@link Path}s by the relationship count returned for its end node * by the supplied {@code expander}. * * @param expander the {@link PathExpander} to use for getting relationships * off of each {@link Path}'s end node. * @return a {@link Comparator} suitable for sorting traversal results. */ public static Comparator<? super Path> endNodeRelationshipCount( final PathExpander expander ) { return new EndNodeComparator() { @Override protected int compareNodes( Node endNode1, Node endNode2 ) { Integer count1 = count( endNode1, expander ); Integer count2 = count( endNode2, expander ); return count1.compareTo( count2 ); } private Integer count( Node node, PathExpander expander ) { return IteratorUtil.count( expander.expand( new SingleNodePath( node ), BranchState.NO_STATE ) ); } }; } private static abstract class EndNodeComparator implements Comparator<Path> { @Override public int compare( Path p1, Path p2 ) { return compareNodes( p1.endNode(), p2.endNode() ); } protected abstract int compareNodes( Node endNode1, Node endNode2 ); } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Sorting.java
5,402
ALTERNATING { @Override public SideSelector create( BranchSelector start, BranchSelector end, int maxDepth ) { return new AlternatingSelectorOrderer( start, end ); } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_SideSelectorPolicies.java
5,403
LEVEL_STOP_DESCENT_ON_RESULT { @Override public SideSelector create( BranchSelector start, BranchSelector end, int maxDepth ) { return new LevelSelectorOrderer( start, end, true, maxDepth ); } },
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_SideSelectorPolicies.java
5,404
LEVEL { @Override public SideSelector create( BranchSelector start, BranchSelector end, int maxDepth ) { return new LevelSelectorOrderer( start, end, false, maxDepth ); } },
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_SideSelectorPolicies.java
5,405
class RecentlyUnique extends AbstractUniquenessFilter { private static final Object PLACE_HOLDER = new Object(); private static final int DEFAULT_RECENT_SIZE = 10000; private final LruCache<Long, Object> recentlyVisited; RecentlyUnique( PrimitiveTypeFetcher type, Object parameter ) { super( type ); parameter = parameter != null ? parameter : DEFAULT_RECENT_SIZE; recentlyVisited = new LruCache<Long, Object>( "Recently visited", ((Number) parameter).intValue() ); } public boolean check( TraversalBranch branch ) { long id = type.getId( branch ); boolean add = recentlyVisited.get( id ) == null; if ( add ) { recentlyVisited.put( id, PLACE_HOLDER ); } return add; } @Override public boolean checkFull( Path path ) { // See GloballyUnique for comments. return true; } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_RecentlyUnique.java
5,406
{ public boolean pruneAfter( Path position ) { return false; } };
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_PruneEvaluator.java
5,407
RELATIONSHIP { @Override long getId( Path source ) { return source.lastRelationship().getId(); } @Override boolean idEquals( Path source, long idToCompare ) { Relationship relationship = source.lastRelationship(); return relationship != null && relationship.getId() == idToCompare; } @Override boolean containsDuplicates( Path source ) { Set<Relationship> relationships = new HashSet<Relationship>(); for ( Relationship relationship : source.reverseRelationships() ) if ( !relationships.add( relationship ) ) return true; return false; } };
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_PrimitiveTypeFetcher.java
5,408
NODE { @Override long getId( Path source ) { return source.endNode().getId(); } @Override boolean idEquals( Path source, long idToCompare ) { return getId( source ) == idToCompare; } @Override boolean containsDuplicates( Path source ) { Set<Node> nodes = new HashSet<Node>(); for ( Node node : source.reverseNodes() ) if ( !nodes.add( node ) ) return true; return false; } },
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_PrimitiveTypeFetcher.java
5,409
class PreorderDepthFirstSelector implements BranchSelector { private TraversalBranch current; private final PathExpander expander; PreorderDepthFirstSelector( TraversalBranch startSource, PathExpander expander ) { this.current = startSource; this.expander = expander; } public TraversalBranch next( TraversalContext metadata ) { TraversalBranch result = null; while ( result == null ) { if ( current == null ) { return null; } TraversalBranch next = current.next( expander, metadata ); if ( next == null ) { current = current.parent(); continue; } else { current = next; } if ( current != null ) { result = current; } } return result; } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_PreorderDepthFirstSelector.java
5,410
class PreorderBreadthFirstSelector implements BranchSelector { private final Queue<TraversalBranch> queue = new LinkedList<TraversalBranch>(); private TraversalBranch current; private final PathExpander expander; public PreorderBreadthFirstSelector( TraversalBranch startSource, PathExpander expander ) { this.current = startSource; this.expander = expander; } public TraversalBranch next( TraversalContext metadata ) { TraversalBranch result = null; while ( result == null ) { TraversalBranch next = current.next( expander, metadata ); if ( next != null ) { queue.add( next ); result = next; } else { current = queue.poll(); if ( current == null ) { return null; } } } return result; } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_PreorderBreadthFirstSelector.java
5,411
class PostorderDepthFirstSelector implements BranchSelector { private TraversalBranch current; private final PathExpander expander; PostorderDepthFirstSelector( TraversalBranch startSource, PathExpander expander ) { this.current = startSource; this.expander = expander; } public TraversalBranch next( TraversalContext metadata ) { TraversalBranch result = null; while ( result == null ) { if ( current == null ) { return null; } TraversalBranch next = current.next( expander, metadata ); if ( next != null ) { current = next; } else { result = current; current = current.parent(); } } return result; } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_PostorderDepthFirstSelector.java
5,412
class PostorderBreadthFirstSelector implements BranchSelector { private Iterator<TraversalBranch> sourceIterator; private TraversalBranch current; private final PathExpander expander; PostorderBreadthFirstSelector( TraversalBranch startSource, PathExpander expander ) { this.current = startSource; this.expander = expander; } public TraversalBranch next( TraversalContext metadata ) { if ( sourceIterator == null ) { sourceIterator = gatherSourceIterator( metadata ); } return sourceIterator.hasNext() ? sourceIterator.next() : null; } private Iterator<TraversalBranch> gatherSourceIterator( TraversalContext metadata ) { LinkedList<TraversalBranch> queue = new LinkedList<TraversalBranch>(); queue.add( current.next( expander, metadata ) ); while ( true ) { List<TraversalBranch> level = gatherOneLevel( queue, metadata ); if ( level.isEmpty() ) { break; } queue.addAll( 0, level ); } return queue.iterator(); } private List<TraversalBranch> gatherOneLevel( List<TraversalBranch> queue, TraversalContext metadata ) { List<TraversalBranch> level = new LinkedList<TraversalBranch>(); Integer depth = null; for ( TraversalBranch source : queue ) { if ( depth == null ) { depth = source.length(); } else if ( source.length() != depth ) { break; } while ( true ) { TraversalBranch next = source.next( expander, metadata ); if ( next == null ) { break; } level.add( next ); } } return level; } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_PostorderBreadthFirstSelector.java
5,413
class PathUnique extends AbstractUniquenessFilter { PathUnique( PrimitiveTypeFetcher type ) { super( type ); } public boolean check( TraversalBranch source ) { long idToCompare = type.getId( source ); while ( source.length() > 0 ) { source = source.parent(); if (type.idEquals(source, idToCompare)) { return false; } } return true; } @Override public boolean checkFull( Path path ) { return !type.containsDuplicates( path ); } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_PathUnique.java
5,414
abstract class Adapter<STATE> implements PathEvaluator<STATE> { @Override @SuppressWarnings("unchecked") public Evaluation evaluate( Path path ) { return evaluate( path, BranchState.NO_STATE ); } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_PathEvaluator.java
5,415
class NotUnique extends AbstractUniquenessFilter { NotUnique() { super( null ); } public boolean check( TraversalBranch source ) { return true; } @Override public boolean checkFull( Path path ) { // Where we have no uniqueness, everything is unique. return true; } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_NotUnique.java
5,416
class LevelUnique extends AbstractUniquenessFilter { private final Map<Integer, Set<Long>> idsPerLevel = new HashMap<Integer, Set<Long>>(); LevelUnique( PrimitiveTypeFetcher type ) { super( type ); } @Override public boolean check( TraversalBranch branch ) { Integer level = branch.length(); Set<Long> levelIds = idsPerLevel.get( level ); if ( levelIds == null ) { levelIds = new HashSet<Long>(); idsPerLevel.put( level, levelIds ); } return levelIds.add( type.getId( branch ) ); } @Override public boolean checkFull( Path path ) { throw new UnsupportedOperationException( "Not implemented yet" ); } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_LevelUnique.java
5,417
class AsInitialBranchState<STATE> implements InitialBranchState<STATE> { private final InitialStateFactory<STATE> factory; public AsInitialBranchState( InitialStateFactory<STATE> factory ) { this.factory = factory; } @Override public InitialBranchState<STATE> reverse() { return this; } @Override public STATE initialState( Path path ) { return factory.initialState( path ); } }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_InitialStateFactory.java
5,418
private static abstract class EndNodeComparator implements Comparator<Path> { @Override public int compare( Path p1, Path p2 ) { return compareNodes( p1.endNode(), p2.endNode() ); } protected abstract int compareNodes( Node endNode1, Node endNode2 ); }
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Sorting.java
5,419
NODE_PATH { public UniquenessFilter create( Object optionalParameter ) { acceptNull( optionalParameter ); return new PathUnique( PrimitiveTypeFetcher.NODE ); } },
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Uniqueness.java
5,420
@Deprecated public class PatternMatcher { private static PatternMatcher matcher = new PatternMatcher(); private PatternMatcher() { } /** * Get the sole instance of the {@link PatternMatcher}. * * @return the instance of {@link PatternMatcher}. */ public static PatternMatcher getMatcher() { return matcher; } /** * Find occurrences of the pattern defined by the given {@link PatternNode} * where the given {@link PatternNode} starts matching at the given * {@link Node}. * * @param start the {@link PatternNode} to start matching at. * @param startNode the {@link Node} to start matching at. * @return all matching instances of the pattern. */ public Iterable<PatternMatch> match( PatternNode start, Node startNode ) { return match( start, startNode, null ); } /** * Find occurrences of the pattern defined by the given {@link PatternNode} * where the given {@link PatternNode} starts matching at the given * {@link Node}. * * @param start the {@link PatternNode} to start matching at. * @param startNode the {@link Node} to start matching at. * @param objectVariables mapping from names to {@link PatternNode}s. * @return all matching instances of the pattern. */ public Iterable<PatternMatch> match( PatternNode start, Node startNode, Map<String, PatternNode> objectVariables ) { return match( start, startNode, objectVariables, ( Collection<PatternNode> ) null ); } /** * Find occurrences of the pattern defined by the given {@link PatternNode} * where the given {@link PatternNode} starts matching at the given * {@link Node}. * * @param start the {@link PatternNode} to start matching at. * @param objectVariables mapping from names to {@link PatternNode}s. * @param optional nodes that form sub-patterns connected to this pattern. * @return all matching instances of the pattern. */ public Iterable<PatternMatch> match( PatternNode start, Map<String, PatternNode> objectVariables, PatternNode... optional ) { return match( start, objectVariables, Arrays.asList( optional ) ); } /** * Find occurrences of the pattern defined by the given {@link PatternNode} * where the given {@link PatternNode} starts matching at the given * {@link Node}. * * @param start the {@link PatternNode} to start matching at. * @param objectVariables mapping from names to {@link PatternNode}s. * @param optional nodes that form sub-patterns connected to this pattern. * @return all matching instances of the pattern. */ public Iterable<PatternMatch> match( PatternNode start, Map<String, PatternNode> objectVariables, Collection<PatternNode> optional ) { Node startNode = start.getAssociation(); if ( startNode == null ) { throw new IllegalStateException( "Associating node for start pattern node is null" ); } return match( start, startNode, objectVariables, optional ); } /** * Find occurrences of the pattern defined by the given {@link PatternNode} * where the given {@link PatternNode} starts matching at the given * {@link Node}. * * @param start the {@link PatternNode} to start matching at. * @param startNode the {@link Node} to start matching at. * @param objectVariables mapping from names to {@link PatternNode}s. * @param optional nodes that form sub-patterns connected to this pattern. * @return all matching instances of the pattern. */ public Iterable<PatternMatch> match( PatternNode start, Node startNode, Map<String, PatternNode> objectVariables, Collection<PatternNode> optional ) { Node currentStartNode = start.getAssociation(); if ( currentStartNode != null && !currentStartNode.equals( startNode ) ) { throw new IllegalStateException( "Start patter node already has associated " + currentStartNode + ", can not start with " + startNode ); } Iterable<PatternMatch> result = null; if ( optional == null || optional.size() < 1 ) { result = new PatternFinder( this, start, startNode ); } else { result = new PatternFinder( this, start, startNode, false, optional ); } if ( objectVariables != null ) { // Uses the FILTER expressions result = new FilteredPatternFinder( result, objectVariables ); } return result; } /** * Find occurrences of the pattern defined by the given {@link PatternNode} * where the given {@link PatternNode} starts matching at the given * {@link Node}. * * @param start the {@link PatternNode} to start matching at. * @param startNode the {@link Node} to start matching at. * @param objectVariables mapping from names to {@link PatternNode}s. * @param optional nodes that form sub-patterns connected to this pattern. * @return all matching instances of the pattern. */ public Iterable<PatternMatch> match( PatternNode start, Node startNode, Map<String, PatternNode> objectVariables, PatternNode... optional ) { return match( start, startNode, objectVariables, Arrays.asList( optional ) ); } private static class SimpleRegexValueGetter implements FilterValueGetter { private PatternMatch match; private Map<String, PatternNode> labelToNode = new HashMap<String, PatternNode>(); private Map<String, String> labelToProperty = new HashMap<String, String>(); SimpleRegexValueGetter( Map<String, PatternNode> objectVariables, PatternMatch match, FilterExpression[] expressions ) { this.match = match; for ( FilterExpression expression : expressions ) { mapFromExpression( expression ); } this.labelToNode = objectVariables; } private void mapFromExpression( FilterExpression expression ) { if ( expression instanceof FilterBinaryNode ) { FilterBinaryNode node = ( FilterBinaryNode ) expression; mapFromExpression( node.getLeftExpression() ); mapFromExpression( node.getRightExpression() ); } else { AbstractFilterExpression pattern = ( AbstractFilterExpression ) expression; labelToProperty.put( pattern.getLabel(), pattern.getProperty() ); } } public String[] getValues( String label ) { PatternNode pNode = labelToNode.get( label ); if ( pNode == null ) { throw new RuntimeException( "No node for label '" + label + "'" ); } Node node = this.match.getNodeFor( pNode ); String propertyKey = labelToProperty.get( label ); if ( propertyKey == null ) { throw new RuntimeException( "No property key for label '" + label + "'" ); } Object rawValue = node.getProperty( propertyKey, null ); if ( rawValue == null ) { return new String[ 0 ]; } Collection<Object> values = ArrayPropertyUtil.propertyValueToCollection( rawValue ); String[] result = new String[ values.size() ]; int counter = 0; for ( Object value : values ) { result[ counter++ ] = ( String ) value; } return result; } } private static class FilteredPatternFinder extends FilteringIterable<PatternMatch> { public FilteredPatternFinder( Iterable<PatternMatch> source, final Map<String, PatternNode> objectVariables ) { super( source, new Predicate<PatternMatch>() { public boolean accept( PatternMatch item ) { Set<PatternGroup> calculatedGroups = new HashSet<PatternGroup>(); for ( PatternElement element : item.getElements() ) { PatternNode node = element.getPatternNode(); PatternGroup group = node.getGroup(); if ( calculatedGroups.add( group ) ) { FilterValueGetter valueGetter = new SimpleRegexValueGetter( objectVariables, item, group.getFilters() ); for ( FilterExpression expression : group.getFilters() ) { if ( !expression.matches( valueGetter ) ) { return false; } } } } return true; } } ); } } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternMatcher.java
5,421
NODE_RECENT { public UniquenessFilter create( Object optionalParameter ) { acceptIntegerOrNull( optionalParameter ); return new RecentlyUnique( PrimitiveTypeFetcher.NODE, optionalParameter ); } },
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Uniqueness.java
5,422
@Deprecated public class PatternMatch { private Map<PatternNode,PatternElement> elements = new HashMap<PatternNode, PatternElement>(); private Map<PatternRelationship,Relationship> relElements = new HashMap<PatternRelationship,Relationship>(); PatternMatch( Map<PatternNode,PatternElement> elements, Map<PatternRelationship,Relationship> relElements ) { this.elements = elements; this.relElements = relElements; } /** * @param node the {@link PatternNode} to get the {@link Node} for. * @return the actual {@link Node} for this particular match, represented * by {@code node} in the pattern */ public Node getNodeFor( PatternNode node ) { return elements.containsKey( node ) ? elements.get( node ).getNode() : null; } /** * @param rel the {@link PatternRelationship} to get the * {@link Relationship} for. * @return the actual {@link Relationship} for this particular match, * represented by {@code rel} in the pattern */ public Relationship getRelationshipFor( PatternRelationship rel ) { return relElements.containsKey( rel ) ? relElements.get( rel ) : null; } /** * Get the matched elements in this match. * * @return an iterable over the matched elements in this match instance. */ public Iterable<PatternElement> getElements() { return elements.values(); } /** * Used to merge two matches. An example is to merge in an "optional" * subgraph match into a match. * @param matches the matches to merge together. * @return the merged matches as one match. */ public static PatternMatch merge( Iterable<PatternMatch> matches ) { Map<PatternNode, PatternElement> matchMap = new HashMap<PatternNode, PatternElement>(); Map<PatternRelationship, Relationship> relElements = new HashMap<PatternRelationship, Relationship>(); for ( PatternMatch match : matches ) { for ( PatternNode node : match.elements.keySet() ) { boolean exists = false; for ( PatternNode existingNode : matchMap.keySet() ) { if ( node.getLabel().equals( existingNode.getLabel() ) ) { exists = true; break; } } if ( !exists ) { matchMap.put( node, match.elements.get( node ) ); relElements.put( match.elements.get( node ).getFromPatternRelationship(), match.elements.get( node ).getFromRelationship() ); } } } PatternMatch mergedMatch = new PatternMatch( matchMap, relElements ); return mergedMatch; } /** * Used to merge matches. An example is to merge in an "optional" subgraph * match into a match. * * @param matches the matches to merge together. * @return the merged matches as one match. */ public static PatternMatch merge( PatternMatch... matches ) { return merge( Arrays.asList( matches ) ); } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternMatch.java
5,423
@Deprecated public class PatternGroup { private Collection<FilterExpression> regexExpression = new ArrayList<FilterExpression>(); /** * Adds a filter expression to the list of filters for this group. * @param regexRepression the {@link FilterExpression} to add to this * group. */ public void addFilter( FilterExpression regexRepression ) { this.regexExpression.add( regexRepression ); } /** * Returns the filter expressions which has been added for this group with * {@link #addFilter(FilterExpression)}. * @return the filters for this group. */ public FilterExpression[] getFilters() { return this.regexExpression.toArray( new FilterExpression[ this.regexExpression.size() ] ); } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternGroup.java
5,424
private static class CallPosition { private PatternPosition patternPosition; private Iterator<Relationship> relItr; private Relationship lastRel; private PatternRelationship currentPRel; private boolean popUncompleted; CallPosition( PatternPosition patternPosition, Relationship lastRel, Iterator<Relationship> relItr, PatternRelationship currentPRel, boolean popUncompleted ) { this.patternPosition = patternPosition; this.relItr = relItr; this.lastRel = lastRel; this.currentPRel = currentPRel; this.popUncompleted = popUncompleted; } public void setLastVisitedRelationship( Relationship rel ) { this.lastRel = rel; } public Relationship getLastVisitedRelationship() { return lastRel; } public boolean shouldPopUncompleted() { return popUncompleted; } public PatternPosition getPatternPosition() { return patternPosition; } public PatternRelationship getPatternRelationship() { return currentPRel; } public Iterator<Relationship> getRelationshipIterator() { return relItr; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternFinder.java
5,425
@Deprecated class PatternFinder implements Iterable<PatternMatch>, Iterator<PatternMatch> { private Set<Relationship> visitedRels = new HashSet<Relationship>(); private PatternPosition currentPosition; private OptionalPatternFinder optionalFinder; private PatternNode startPatternNode; private Node startNode; private Collection<PatternNode> optionalNodes; private boolean optional; private final PatternMatcher matcher; PatternFinder( PatternMatcher matcher, PatternNode start, Node startNode ) { this( matcher, start, startNode, false ); } PatternFinder( PatternMatcher matcher, PatternNode start, Node startNode, boolean optional ) { this.matcher = matcher; this.startPatternNode = start; this.startNode = startNode; currentPosition = new PatternPosition( startNode, start, optional ); this.optional = optional; } PatternFinder( PatternMatcher matcher, PatternNode start, Node startNode, boolean optional, Collection<PatternNode> optionalNodes ) { this( matcher, start, startNode, optional ); this.optionalNodes = optionalNodes; } PatternNode getStartPatternNode() { return startPatternNode; } Node getStartNode() { return startNode; } /** * Represents a traversal state so that we can go back to it when we've * descended the graph and comes back up to continue matching on a * higher level. */ private static class CallPosition { private PatternPosition patternPosition; private Iterator<Relationship> relItr; private Relationship lastRel; private PatternRelationship currentPRel; private boolean popUncompleted; CallPosition( PatternPosition patternPosition, Relationship lastRel, Iterator<Relationship> relItr, PatternRelationship currentPRel, boolean popUncompleted ) { this.patternPosition = patternPosition; this.relItr = relItr; this.lastRel = lastRel; this.currentPRel = currentPRel; this.popUncompleted = popUncompleted; } public void setLastVisitedRelationship( Relationship rel ) { this.lastRel = rel; } public Relationship getLastVisitedRelationship() { return lastRel; } public boolean shouldPopUncompleted() { return popUncompleted; } public PatternPosition getPatternPosition() { return patternPosition; } public PatternRelationship getPatternRelationship() { return currentPRel; } public Iterator<Relationship> getRelationshipIterator() { return relItr; } } private Stack<CallPosition> callStack = new Stack<CallPosition>(); private Stack<PatternPosition> uncompletedPositions = new Stack<PatternPosition>(); private Stack<PatternElement> foundElements = new Stack<PatternElement>(); private PatternMatch findNextMatch() { if ( callStack.isEmpty() && currentPosition != null ) { // Try to find a first indication of a match, i.e. find some part // of the pattern in the graph. if ( traverse( currentPosition, true ) ) { // found first match, return it currentPosition = null; return extractPotentialResult(); } currentPosition = null; } else { return traverseFromCallStack(); } return null; } private PatternMatch extractPotentialResult() { HashMap<PatternNode, PatternElement> filteredElements = new HashMap<PatternNode, PatternElement>(); HashMap<PatternRelationship, Relationship> relElements = new HashMap<PatternRelationship, Relationship>(); boolean patternValid = true; for ( PatternElement element : foundElements ) { PatternElement other = filteredElements.get( element.getPatternNode() ); if ( other != null && !other.getNode().equals( element.getNode() ) ) { patternValid = false; break; } filteredElements.put( element.getPatternNode(), element ); relElements.put( element.getFromPatternRelationship(), element.getFromRelationship() ); } PatternMatch patternMatch = new PatternMatch( filteredElements, relElements ); foundElements.pop(); if ( patternValid ) { return patternMatch; } return traverseFromCallStack(); } private PatternMatch traverseFromCallStack() { if ( callStack.isEmpty() ) { return null; } boolean matchFound = false; do { CallPosition callStackInformation = callStack.peek(); matchFound = traverse( callStackInformation ); } while ( !callStack.isEmpty() && !matchFound ); if ( matchFound ) { return extractPotentialResult(); } return null; } private boolean traverse( CallPosition callPos ) { // make everything like it was before we returned previous match PatternPosition currentPos = callPos.getPatternPosition(); PatternRelationship pRel = callPos.getPatternRelationship(); pRel.mark(); visitedRels.remove( callPos.getLastVisitedRelationship() ); Node currentNode = currentPos.getCurrentNode(); Iterator<Relationship> relItr = callPos.getRelationshipIterator(); while ( relItr.hasNext() ) { Relationship rel = relItr.next(); if ( visitedRels.contains( rel ) ) { continue; } if ( !checkProperties( pRel, rel ) ) { continue; } Node otherNode = rel.getOtherNode( currentNode ); PatternNode otherPosition = pRel.getOtherNode( currentPos .getPatternNode() ); pRel.mark(); visitedRels.add( rel ); if ( traverse( new PatternPosition( otherNode, otherPosition, pRel, rel, optional ), true ) ) { callPos.setLastVisitedRelationship( rel ); return true; } visitedRels.remove( rel ); pRel.unMark(); } pRel.unMark(); if ( callPos.shouldPopUncompleted() ) { uncompletedPositions.pop(); } callStack.pop(); foundElements.pop(); return false; } private boolean traverse( PatternPosition currentPos, boolean pushElement ) { PatternNode pNode = currentPos.getPatternNode(); Node currentNode = currentPos.getCurrentNode(); if ( !checkProperties( pNode, currentNode ) ) { return false; } if ( pushElement ) { foundElements.push( new PatternElement( pNode, currentPos.fromPatternRel(), currentNode, currentPos.fromRelationship() ) ); } if ( currentPos.hasNext() ) { boolean popUncompleted = false; PatternRelationship pRel = currentPos.next(); if ( currentPos.hasNext() ) { uncompletedPositions.push( currentPos ); popUncompleted = true; } assert !pRel.isMarked(); Iterator<Relationship> relItr = getRelationshipIterator( currentPos .getPatternNode(), currentNode, pRel ); pRel.mark(); while ( relItr.hasNext() ) { Relationship rel = relItr.next(); if ( visitedRels.contains( rel ) ) { continue; } if ( !checkProperties( pRel, rel ) ) { continue; } Node otherNode = rel.getOtherNode( currentNode ); PatternNode otherPosition = pRel.getOtherNode( currentPos .getPatternNode() ); visitedRels.add( rel ); CallPosition callPos = new CallPosition( currentPos, rel, relItr, pRel, popUncompleted ); callStack.push( callPos ); if ( traverse( new PatternPosition( otherNode, otherPosition, pRel, rel, optional ), true ) ) { return true; } callStack.pop(); visitedRels.remove( rel ); } pRel.unMark(); if ( popUncompleted ) { uncompletedPositions.pop(); } foundElements.pop(); return false; } boolean matchFound = true; if ( !uncompletedPositions.isEmpty() ) { PatternPosition digPos = uncompletedPositions.pop(); digPos.reset(); matchFound = traverse( digPos, false ); uncompletedPositions.push( digPos ); return matchFound; } return true; } private Iterator<Relationship> getRelationshipIterator( PatternNode fromNode, Node currentNode, PatternRelationship pRel ) { Iterator<Relationship> relItr = null; if ( pRel.anyRelType() ) { relItr = currentNode.getRelationships( pRel.getDirectionFrom( fromNode ) ).iterator(); } else { relItr = currentNode.getRelationships( pRel.getType(), pRel.getDirectionFrom( fromNode ) ).iterator(); } return relItr; } private boolean checkProperties( AbstractPatternObject<? extends PropertyContainer> patternObject, PropertyContainer object ) { PropertyContainer associatedObject = patternObject.getAssociation(); if ( associatedObject != null && !object.equals( associatedObject ) ) { return false; } for ( Map.Entry<String, Collection<ValueMatcher>> matchers : patternObject.getPropertyConstraints() ) { String key = matchers.getKey(); Object propertyValue = object.getProperty( key, null ); for (ValueMatcher matcher : matchers.getValue() ) { if ( !matcher.matches( propertyValue ) ) { return false; } } } return true; } public Iterator<PatternMatch> iterator() { return this; } private PatternMatch match = null; private PatternMatch optionalMatch = null; public boolean hasNext() { if ( match == null ) { match = findNextMatch(); optionalFinder = null; } else if ( optionalNodes != null ) { if ( optionalFinder == null ) { optionalFinder = new OptionalPatternFinder( matcher, match, optionalNodes ); } if ( optionalMatch == null ) { optionalMatch = optionalFinder.findNextOptionalPatterns(); } if ( optionalMatch == null && optionalFinder.anyMatchFound() ) { match = null; return hasNext(); } } return match != null; } public PatternMatch next() { if ( match == null ) { match = findNextMatch(); optionalFinder = null; } PatternMatch matchToReturn = match; PatternMatch optionalMatchToReturn = null; if ( match != null && optionalNodes != null ) { if ( optionalFinder == null ) { optionalFinder = new OptionalPatternFinder( matcher, match, optionalNodes ); } if ( optionalMatch == null ) { optionalMatch = optionalFinder.findNextOptionalPatterns(); } optionalMatchToReturn = optionalMatch; optionalMatch = null; if ( optionalMatchToReturn == null ) { match = null; if ( optionalFinder.anyMatchFound() ) { return next(); } } } else { match = null; } if ( matchToReturn == null ) { throw new NoSuchElementException(); } return optionalMatchToReturn != null ? PatternMatch.merge( matchToReturn, optionalMatchToReturn ) : matchToReturn; } public void remove() { throw new UnsupportedOperationException(); } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternFinder.java
5,426
@Deprecated public class PatternElement { private PatternNode pNode; private Node node; private PatternRelationship prevPatternRel = null; private Relationship prevRel = null; PatternElement( PatternNode pNode, PatternRelationship pRel, Node node, Relationship rel ) { this.pNode = pNode; this.node = node; this.prevPatternRel = pRel; this.prevRel = rel; } /** * Returns the {@link PatternNode} corresponding to the matching * {@link Node}. * @return the {@link PatternNode} corresponsing to matching {@link Node}. */ public PatternNode getPatternNode() { return pNode; } /** * Returns the matching {@link Node} which is just one part of the whole * match. * @return the matching {@link Node} which is just one part of the whole * match. */ public Node getNode() { return node; } @Override public String toString() { return pNode.toString(); } /** * Returns the {@link PatternRelationship} corresponding to the matching * {@link Relationship}. * @return the {@link PatternRelationship} corresponsing to matching * {@link Relationship}. */ public PatternRelationship getFromPatternRelationship() { return prevPatternRel; } /** * Returns the {@link Relationship} traversed to get to the {@link Node} * returned from {@link #getNode()}. * @return the {@link Relationship} traversed to get to this node. */ public Relationship getFromRelationship() { return prevRel; } public int hashCode() { return pNode.hashCode(); } public boolean equals( Object o ) { if ( o instanceof PatternElement ) { return pNode.equals( ( (PatternElement) o ).pNode ); } return false; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_PatternElement.java
5,427
@Deprecated class OptionalPatternFinder { private List<PatternFinder> optionalFinders; private List<PatternMatch> currentMatches; private Collection<PatternNode> optionalNodes; private PatternMatch baseMatch; private int position = -1; private final PatternMatcher matcher; OptionalPatternFinder( PatternMatcher matcher, PatternMatch baseMatch, Collection<PatternNode> optionalNodes ) { this.matcher = matcher; this.baseMatch = baseMatch; this.optionalNodes = optionalNodes; initialize(); } private boolean first = true; PatternMatch findNextOptionalPatterns() { if ( position < 0 ) { return null; } if ( first && anyMatchFound() ) { first = false; return PatternMatch.merge( currentMatches ); } boolean found = false; for ( ; position >= 0; position-- ) { if ( optionalFinders.get( position ).hasNext() ) { currentMatches.set( position, optionalFinders.get( position ) .next() ); if ( position < currentMatches.size() - 1 ) { position++; reset( position ); } found = true; break; } } if ( !found ) { return null; } return PatternMatch.merge( currentMatches ); } boolean anyMatchFound() { return !currentMatches.isEmpty(); } private void initialize() { optionalFinders = new ArrayList<PatternFinder>(); currentMatches = new ArrayList<PatternMatch>(); for ( PatternNode node : optionalNodes ) { PatternFinder finder = new PatternFinder( matcher, node, this .getNodeFor( node ), true ); if ( finder.hasNext() ) { optionalFinders.add( finder ); currentMatches.add( finder.next() ); position++; } } } private Node getNodeFor( PatternNode node ) { for ( PatternElement element : baseMatch.getElements() ) { if ( node.getLabel().equals( element.getPatternNode().getLabel() ) ) { return element.getNode(); } } throw new RuntimeException( "Optional graph isn't connected to the main graph." ); } private void reset( int fromIndex ) { for ( int i = fromIndex; i < optionalFinders.size(); i++ ) { PatternFinder finder = optionalFinders.get( i ); PatternFinder newFinder = new PatternFinder( matcher, finder .getStartPatternNode(), finder.getStartNode(), true ); optionalFinders.set( i, newFinder ); // Only patterns with matches were added in the first place, // so newFinder must have at least one match. currentMatches.set( i, newFinder.next() ); position = i; } } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_OptionalPatternFinder.java
5,428
private static class RegexMatcher implements ValueMatcher { private final Pattern pattern; public RegexMatcher( Pattern pattern ) { this.pattern = pattern; } public boolean matches( Object value ) { return value != null && pattern.matcher( value.toString() ).matches(); } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_CommonValueMatchers.java
5,429
private static class ExactMatcher implements ValueMatcher { private final Object valueToMatch; public ExactMatcher( Object valueToMatch ) { this.valueToMatch = valueToMatch; } public boolean matches( Object value ) { return value != null && this.valueToMatch.equals( value ); } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_CommonValueMatchers.java
5,430
private static class ExactAnyMatcher implements ValueMatcher { private final Object[] valuesToMatch; public ExactAnyMatcher( Object... valueToMatch ) { this.valuesToMatch = valueToMatch; } public boolean matches( Object value ) { if ( value != null ) { if ( value.getClass().isArray() ) { for ( Object item : ArrayPropertyUtil.propertyValueToCollection( value ) ) { if ( item != null && anyMatches( item ) ) { return true; } } } else if ( anyMatches( value ) ) { return true; } } return false; } private boolean anyMatches( Object value ) { for ( Object matchValue : valuesToMatch ) { if ( value.equals( matchValue ) ) { return true; } } return false; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_CommonValueMatchers.java
5,431
{ public boolean matches( Object value ) { return value != null; } };
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_CommonValueMatchers.java
5,432
@Deprecated public abstract class CommonValueMatchers { private CommonValueMatchers() { } private static final ValueMatcher HAS = new ValueMatcher() { public boolean matches( Object value ) { return value != null; } }; /** * Checks for equality between a value and {@code valueToMatch}. Returns * {@code true} if the value isn't null and is equal to * {@code valueToMatch}, else {@code false}. * * @param valueToMatch the expected value. * @return whether or not a value is equal to {@code valueToMatch}. */ public static ValueMatcher exact( Object valueToMatch ) { return new ExactMatcher( valueToMatch ); } /** * Checks for equality between a value and {@code valueToMatch}. * If the value is an array each item in the array is matched against * {@code valueToMatch} and if any of those matches it's considered * a match. * * @param valueToMatch the expected value. * @return whether or not a value is equal to {@code valueToMatch}. */ public static ValueMatcher exactAny( Object valueToMatch ) { return new ExactAnyMatcher( valueToMatch ); } /** * Checks for equality between a value and any one of * {@code anyOfTheseToMatch}. If the value is an array each item in * the array is matched against any one of {@code valueToMatch} and if * any of those matches it's considered a match. * * @param anyOfTheseToMatch the expected value. * @return whether or not a value is equal to any one of * {@code anyOfTheseToMatch}. */ public static ValueMatcher exactAnyOf( Object... anyOfTheseToMatch ) { return new ExactAnyMatcher( anyOfTheseToMatch ); } /** * Checks that the property exists. * * @return a matcher that verifies that the property exists. */ public static ValueMatcher has() { return HAS; } /** * Checks that the {@link String} property matches the specified regular * expression pattern. * * @param pattern the regular expression pattern to match the property with. * @return a matcher that verifies that the property matches the given * regular expression. */ public static ValueMatcher regex( Pattern pattern ) { return new RegexMatcher( pattern ); } private static class ExactMatcher implements ValueMatcher { private final Object valueToMatch; public ExactMatcher( Object valueToMatch ) { this.valueToMatch = valueToMatch; } public boolean matches( Object value ) { return value != null && this.valueToMatch.equals( value ); } } private static class ExactAnyMatcher implements ValueMatcher { private final Object[] valuesToMatch; public ExactAnyMatcher( Object... valueToMatch ) { this.valuesToMatch = valueToMatch; } public boolean matches( Object value ) { if ( value != null ) { if ( value.getClass().isArray() ) { for ( Object item : ArrayPropertyUtil.propertyValueToCollection( value ) ) { if ( item != null && anyMatches( item ) ) { return true; } } } else if ( anyMatches( value ) ) { return true; } } return false; } private boolean anyMatches( Object value ) { for ( Object matchValue : valuesToMatch ) { if ( value.equals( matchValue ) ) { return true; } } return false; } } private static class RegexMatcher implements ValueMatcher { private final Pattern pattern; public RegexMatcher( Pattern pattern ) { this.pattern = pattern; } public boolean matches( Object value ) { return value != null && pattern.matcher( value.toString() ).matches(); } } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_CommonValueMatchers.java
5,433
@Deprecated public class ArrayPropertyUtil { /** * @param propertyValue node.getProperty value. * @return a collection of all the values from a property. If the value is * just a plain "single" value the collection will contain that * single value. If the value is an array of values, all those * values are added to the collection. */ public static Collection<Object> propertyValueToCollection( Object propertyValue ) { Set<Object> values = new HashSet<Object>(); try { int length = Array.getLength( propertyValue ); for ( int i = 0; i < length; i++ ) { values.add( Array.get( propertyValue, i ) ); } } catch ( IllegalArgumentException e ) { values.add( propertyValue ); } return values; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_ArrayPropertyUtil.java
5,434
@Deprecated public abstract class AbstractPatternObject<T extends PropertyContainer> { private T assocication; private Map<String, Collection<ValueMatcher>> constrains = new HashMap<String, Collection<ValueMatcher>>(); protected String label; AbstractPatternObject() { } /** * Add a constraint to the property with the given key on this pattern * object. * * @param propertyKey the key of the property to add a constraint to. * @param matcher the constraint to add on the property. */ public void addPropertyConstraint( String propertyKey, ValueMatcher matcher ) { Collection<ValueMatcher> matchers = this.constrains.get( propertyKey ); if ( matchers == null ) { matchers = new ArrayList<ValueMatcher>(); this.constrains.put( propertyKey, matchers ); } matchers.add( matcher ); } /** * Associate this object with a particular {@link Node} or * {@link Relationship}. When a pattern object is associated with an actual * object it will only match that object. Set the association to * <code>null</code> to remove the association. * * @param object the {@link Node} or {@link Relationship} to associate this * pattern object with. */ public void setAssociation( T object ) { this.assocication = object; } /** * Get the {@link Node} or {@link Relationship} currently associated with * this pattern object. * * @return the {@link Node} or {@link Relationship} associated with this * pattern object. */ public T getAssociation() { return this.assocication; } /** * Get all the constraints on the properties of this pattern object. * * @return an iterable of all constrained properties with all constraints * for each of them. */ public Iterable<Map.Entry<String, Collection<ValueMatcher>>> getPropertyConstraints() { Iterable<Map.Entry<String, Collection<ValueMatcher>>> matchers = this.constrains.entrySet(); return matchers != null ? matchers : Collections.<Map.Entry<String, Collection<ValueMatcher>>>emptyList(); } /** * Get the label of this pattern object. * * @return the label of this pattern object. */ public String getLabel() { return label; } /** * Sets the label of this pattern object; * @param label the label of this pattern object; */ public void setLabel(String label) { this.label = label; } }
false
community_graph-matching_src_main_java_org_neo4j_graphmatching_AbstractPatternObject.java
5,435
NONE { public UniquenessFilter create( Object optionalParameter ) { acceptNull( optionalParameter ); return notUniqueInstance; } };
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Uniqueness.java
5,436
RELATIONSHIP_LEVEL { @Override public UniquenessFilter create( Object optionalParameter ) { acceptNull( optionalParameter ); return new LevelUnique( PrimitiveTypeFetcher.RELATIONSHIP ); } },
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Uniqueness.java
5,437
RELATIONSHIP_RECENT { public UniquenessFilter create( Object optionalParameter ) { acceptIntegerOrNull( optionalParameter ); return new RecentlyUnique( PrimitiveTypeFetcher.RELATIONSHIP, optionalParameter ); } },
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Uniqueness.java
5,438
RELATIONSHIP_PATH { public UniquenessFilter create( Object optionalParameter ) { acceptNull( optionalParameter ); return new PathUnique( PrimitiveTypeFetcher.RELATIONSHIP ); } },
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Uniqueness.java
5,439
RELATIONSHIP_GLOBAL { public UniquenessFilter create( Object optionalParameter ) { acceptNull( optionalParameter ); return new GloballyUnique( PrimitiveTypeFetcher.RELATIONSHIP ); } },
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Uniqueness.java
5,440
NODE_LEVEL { @Override public UniquenessFilter create( Object optionalParameter ) { acceptNull( optionalParameter ); return new LevelUnique( PrimitiveTypeFetcher.NODE ); } },
false
community_kernel_src_main_java_org_neo4j_graphdb_traversal_Uniqueness.java
5,441
{ @Override public void leftCluster( InstanceId member ) { latch1.countDown(); masterDb.getDependencyResolver().resolveDependency( ClusterClient.class ) .removeClusterListener( this ); } } );
false
enterprise_ha_src_test_java_org_neo4j_ha_TestPullUpdatesApplied.java
5,442
{ @Override public void failed( InstanceId server ) { latch2.countDown(); masterDb.getDependencyResolver().resolveDependency( ClusterClient.class ) .removeHeartbeatListener( this ); } } );
false
enterprise_ha_src_test_java_org_neo4j_ha_TestPullUpdatesApplied.java
5,443
public class TestSlaveOnlyCluster { @Test public void testMasterElectionAfterMasterRecoversInSlaveOnlyCluster() throws Throwable { ClusterManager clusterManager = new ClusterManager( fromXml( getClass().getResource( "/threeinstances.xml" ).toURI() ), TargetDirectory.forTest( getClass() ).cleanDirectory( "testCluster" ), MapUtil.stringMap(), MapUtil.<Integer, Map<String, String>>genericMap( 2, MapUtil.stringMap( HaSettings.slave_only.name(), "true" ), 3, MapUtil.stringMap( HaSettings.slave_only.name(), "true" )) ); try { clusterManager.start(); clusterManager.getDefaultCluster().await( ClusterManager.allSeesAllAsAvailable() ); final CountDownLatch failedLatch = new CountDownLatch( 2 ); final CountDownLatch electedLatch = new CountDownLatch( 2 ); HeartbeatListener masterDownListener = new HeartbeatListener() { @Override public void failed( InstanceId server ) { failedLatch.countDown(); } @Override public void alive( InstanceId server ) { } }; for ( HighlyAvailableGraphDatabase highlyAvailableGraphDatabase : clusterManager.getDefaultCluster().getAllMembers() ) { if (!highlyAvailableGraphDatabase.isMaster()) { highlyAvailableGraphDatabase.getDependencyResolver().resolveDependency( ClusterClient.class ).addHeartbeatListener( masterDownListener ); highlyAvailableGraphDatabase.getDependencyResolver().resolveDependency( ClusterClient.class ).addClusterListener( new ClusterListener.Adapter() { @Override public void elected( String role, InstanceId electedMember, URI availableAtUri ) { electedLatch.countDown(); } } ); } } HighlyAvailableGraphDatabase master = clusterManager.getDefaultCluster().getMaster(); ClusterManager.RepairKit repairKit = clusterManager.getDefaultCluster().fail( master ); failedLatch.await(); repairKit.repair(); electedLatch.await(); HighlyAvailableGraphDatabase slaveDatabase = clusterManager.getDefaultCluster().getAnySlave( ); long nodeId; try ( Transaction tx = slaveDatabase.beginTx() ) { Node node = slaveDatabase.createNode(); node.setProperty( "foo", "bar" ); nodeId = node.getId(); tx.success(); } try ( Transaction ignore = master.beginTx() ) { assertThat( master.getNodeById( nodeId ).getProperty( "foo" ).toString(), equalTo( "bar" ) ); } } finally { clusterManager.stop(); } } @Test public void testMasterElectionAfterSlaveOnlyInstancesStartFirst() throws Throwable { ClusterManager clusterManager = new ClusterManager( fromXml( getClass().getResource( "/threeinstances.xml" ).toURI() ), TargetDirectory.forTest( getClass() ).cleanDirectory( "testCluster" ), MapUtil.stringMap(), MapUtil.<Integer, Map<String, String>>genericMap( 1, MapUtil.stringMap( HaSettings.slave_only.name(), "true" ), 2, MapUtil.stringMap( HaSettings.slave_only.name(), "true" )) ); try { clusterManager.start(); clusterManager.getDefaultCluster().await( ClusterManager.allSeesAllAsAvailable() ); HighlyAvailableGraphDatabase master = clusterManager.getDefaultCluster().getMaster(); assertThat( clusterManager.getDefaultCluster().getServerId( master ), CoreMatchers.equalTo( 3 ) ); } finally { clusterManager.stop(); } } }
false
enterprise_ha_src_test_java_org_neo4j_ha_TestSlaveOnlyCluster.java
5,444
public class HostnamePort { private final String host; private final int[] ports; public HostnamePort( String hostnamePort ) throws IllegalArgumentException { String[] parts = hostnamePort.split( ":" ); if ( parts.length == 1 ) { host = zeroLengthMeansNull( parts[0] ); ports = new int[]{0, 0}; } else if ( parts.length == 2 ) { host = zeroLengthMeansNull( parts[0] ); String[] portStrings = parts[1].split( "-" ); ports = new int[2]; if ( portStrings.length == 1 ) { ports[0] = ports[1] = Integer.parseInt( portStrings[0] ); } else if ( portStrings.length == 2 ) { ports[0] = Integer.parseInt( portStrings[0] ); ports[1] = Integer.parseInt( portStrings[1] ); } else { throw new IllegalArgumentException( format( "Cannot have more than two port ranges: %s", hostnamePort ) ); } } else { throw new IllegalArgumentException( hostnamePort ); } } private String zeroLengthMeansNull( String string ) { if ( string == null || string.length() == 0 ) return null; return string; } public HostnamePort( String host, int port ) { this( host, port, port ); } public HostnamePort( String host, int portFrom, int portTo ) { this.host = host; ports = new int[]{portFrom, portTo}; } /** * The host part, or null if not given. * * @return */ public String getHost() { return host; } public String getHost( String defaultHost ) { if (host == null) return defaultHost; try { InetAddress ip = InetAddress.getByName( host ); if (ip == null) return defaultHost; return ip.getHostAddress(); } catch ( UnknownHostException e ) { return host; } } /** * The port range as two ints. If only one port given, then both ints have the same value. * If no port range is given, then the array has {0,0} as value. * * @return */ public int[] getPorts() { return ports; } /** * The first port, or 0 if no port was given. * * @return */ public int getPort() { return ports[0]; } public boolean isRange() { return ports[0] != ports[1]; } @Override public String toString() { return toString( null /*no default host*/ ); } public String toString( String defaultHost ) { StringBuilder builder = new StringBuilder(); String host = getHost( defaultHost ); if ( host != null ) { builder.append( host ); } if ( getPort() != 0 ) { builder.append( ":" ); builder.append( getPort() ); if ( isRange() ) { builder.append( "-" ).append( getPorts()[1] ); } } return builder.toString(); } public boolean matches( URI toMatch ) { boolean result = false; for ( int port = ports[0]; port <= ports[1]; port++ ) { if ( port == toMatch.getPort() ) { result = true; break; } } if ( host == null && toMatch.getHost() == null ) { return result; } else if ( host == null ) { return false; } // URI always contains IP, so make sure we convert ours too return result && getHost(null).equalsIgnoreCase( toMatch.getHost() ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_HostnamePort.java
5,445
{ @Override public boolean isDone() { return tryGetExitValue( process ) != null; } private Integer tryGetExitValue( final Process process ) { try { return process.exitValue(); } catch ( IllegalThreadStateException e ) { // Thrown if this process hasn't exited yet. return null; } } @Override public Integer get() throws InterruptedException { return process.waitFor(); } @Override public Integer get( long timeout, TimeUnit unit ) throws InterruptedException, ExecutionException, TimeoutException { long end = System.currentTimeMillis() + unit.toMillis( timeout ); while ( System.currentTimeMillis() < end ) { Integer result = tryGetExitValue( process ); if ( result != null ) { return result; } Thread.sleep( 10 ); } throw new TimeoutException( "Process '" + process + "' didn't exit within " + timeout + " " + unit ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_FutureAdapter.java
5,446
{ @Override public boolean isDone() { return guardedByLatch.getCount() == 0; } @Override public T get() throws InterruptedException, ExecutionException { guardedByLatch.await(); return value.get(); } @Override public T get( long timeout, TimeUnit unit ) throws InterruptedException, ExecutionException, TimeoutException { if ( !guardedByLatch.await( timeout, unit ) ) throw new TimeoutException( "Index population job cancel didn't complete within " + timeout + " " + unit ); return value.get(); } };
false
community_kernel_src_main_java_org_neo4j_helpers_FutureAdapter.java
5,447
public abstract class FutureAdapter<V> implements Future<V> { @Override public boolean cancel( boolean mayInterruptIfRunning ) { throw new UnsupportedOperationException(); } @Override public boolean isCancelled() { throw new UnsupportedOperationException(); } public static class Present<V> extends FutureAdapter<V> { private final V value; public Present( V value ) { this.value = value; } @Override public boolean isDone() { return true; } @Override public V get() { return value; } @Override public V get( long timeout, TimeUnit unit ) { return value; } }; public static final Future<Void> VOID = new Present<>( null ); public static <T> Future<T> latchGuardedValue( final ValueGetter<T> value, final CountDownLatch guardedByLatch ) { return new FutureAdapter<T>() { @Override public boolean isDone() { return guardedByLatch.getCount() == 0; } @Override public T get() throws InterruptedException, ExecutionException { guardedByLatch.await(); return value.get(); } @Override public T get( long timeout, TimeUnit unit ) throws InterruptedException, ExecutionException, TimeoutException { if ( !guardedByLatch.await( timeout, unit ) ) throw new TimeoutException( "Index population job cancel didn't complete within " + timeout + " " + unit ); return value.get(); } }; } public static Future<Integer> processFuture( final Process process ) { return new FutureAdapter<Integer>() { @Override public boolean isDone() { return tryGetExitValue( process ) != null; } private Integer tryGetExitValue( final Process process ) { try { return process.exitValue(); } catch ( IllegalThreadStateException e ) { // Thrown if this process hasn't exited yet. return null; } } @Override public Integer get() throws InterruptedException { return process.waitFor(); } @Override public Integer get( long timeout, TimeUnit unit ) throws InterruptedException, ExecutionException, TimeoutException { long end = System.currentTimeMillis() + unit.toMillis( timeout ); while ( System.currentTimeMillis() < end ) { Integer result = tryGetExitValue( process ); if ( result != null ) { return result; } Thread.sleep( 10 ); } throw new TimeoutException( "Process '" + process + "' didn't exit within " + timeout + " " + unit ); } }; } public static <T> Future<T> future( final Callable<T> task ) { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<T> future = executor.submit( task ); executor.shutdown(); return future; } }
false
community_kernel_src_main_java_org_neo4j_helpers_FutureAdapter.java
5,448
{ @Override public Integer apply( Integer value ) { return value + 1; } };
false
community_kernel_src_test_java_org_neo4j_helpers_FunctionsTest.java
5,449
{ @Override public Integer apply( Integer from1, Integer from2 ) { return from1 * from2; } };
false
community_kernel_src_test_java_org_neo4j_helpers_FunctionsTest.java
5,450
{ @Override public Integer apply( Integer from1, Integer from2 ) { return from1 + from2; } };
false
community_kernel_src_test_java_org_neo4j_helpers_FunctionsTest.java
5,451
public class FunctionsTest { @Test public void testMap() throws Exception { assertThat( map( stringMap( "foo", "bar" ) ).apply( "foo" ), equalTo( "bar" ) ); } @Test public void testWithDefaults() throws Exception { assertThat( Functions.withDefaults( map( stringMap( "foo", "bar" ) ), Functions.<String, String>nullFunction() ).apply( "foo" ), equalTo( "bar" ) ); assertThat( Functions.withDefaults( map( stringMap( "foo", "bar" ) ), map( stringMap( "foo", "xyzzy" ) ) ).apply( "foo" ), equalTo( "xyzzy" ) ); } @Test public void testNullFunction() throws Exception { assertThat( Functions.nullFunction().apply( "foo" ), CoreMatchers.nullValue() ); } @Test public void testConstant() throws Exception { assertThat( Functions.constant( "foo" ).apply( "bar" ), equalTo( "foo" ) ); } @Test public void testCompose2() throws Exception { Function2<Integer, Integer, Integer> add = new Function2<Integer, Integer, Integer>() { @Override public Integer apply( Integer from1, Integer from2 ) { return from1 + from2; } }; Function2<Integer, Integer, Integer> mult = new Function2<Integer, Integer, Integer>() { @Override public Integer apply( Integer from1, Integer from2 ) { return from1 * from2; } }; assertThat( Functions.<Integer, Integer>compose2().apply( add, mult ).apply( 2, 3 ), equalTo( 9 )); } @Test public void testCompose() throws Exception { Function<Integer, Integer> inc = new Function<Integer, Integer>() { @Override public Integer apply( Integer value ) { return value + 1; } }; assertThat( Functions.<String, Integer, Integer>compose().apply( Settings.INTEGER, inc ).apply( "3" ), equalTo( 4 )); } }
false
community_kernel_src_test_java_org_neo4j_helpers_FunctionsTest.java
5,452
{ @Override public TO apply( FROM from ) { return to.cast( from ); } @Override public String toString() { return "cast(to=" + to.getName() + ")"; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Functions.java
5,453
{ @Override public String apply( Object from ) { if (from != null) return from.toString(); else return ""; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Functions.java
5,454
{ @Override public T1 apply( T1 from1, T2 from2 ) { return function1.apply( function2.apply( from1, from2 ), from2 ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Functions.java
5,455
{ @Override public Function2<T1, T2, T1> apply( final Function2<T1, T2, T1> function1, final Function2<T1, T2, T1> function2 ) { return new Function2<T1, T2, T1>() { @Override public T1 apply( T1 from1, T2 from2 ) { return function1.apply( function2.apply( from1, from2 ), from2 ); } }; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Functions.java
5,456
{ @Override public To apply( From from ) { return f2.apply( f1.apply( from ) ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Functions.java
5,457
{ @Override public Function<From, To> apply( final Function<From, From2> f1, final Function<From2, To> f2 ) { return new Function<From, To>() { @Override public To apply( From from ) { return f2.apply( f1.apply( from ) ); } }; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Functions.java
5,458
{ @Override public To apply( From from ) { return value; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Functions.java
5,459
{ @Override public To apply( From from ) { return null; // Always return null } };
false
community_kernel_src_main_java_org_neo4j_helpers_Functions.java
5,460
{ @Override public To apply( From from ) { To to = f.apply( from ); if ( to == null ) { return defaults.apply( from ); } else { return to; } } };
false
community_kernel_src_main_java_org_neo4j_helpers_Functions.java
5,461
{ @Override public To apply( From from ) { return map.get( from ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Functions.java
5,462
public final class Functions { public static <From, To> Function<From, To> map( final Map<From, To> map ) { return new Function<From, To>() { @Override public To apply( From from ) { return map.get( from ); } }; } public static <From, To> Function<From, To> withDefaults( final Function<From, To> defaults, final Function<From, To> f ) { return new Function<From, To>() { @Override public To apply( From from ) { To to = f.apply( from ); if ( to == null ) { return defaults.apply( from ); } else { return to; } } }; } public static <From, To> Function<From, To> nullFunction() { return new Function<From, To>() { @Override public To apply( From from ) { return null; // Always return null } }; } public static <From, To> Function<From, To> constant( final To value ) { return new Function<From, To>() { @Override public To apply( From from ) { return value; } }; } public static <From, From2, To> Function2<Function<From, From2>, Function<From2, To>, Function<From, To>> compose() { return new Function2<Function<From, From2>, Function<From2, To>, Function<From, To>>() { @Override public Function<From, To> apply( final Function<From, From2> f1, final Function<From2, To> f2 ) { return new Function<From, To>() { @Override public To apply( From from ) { return f2.apply( f1.apply( from ) ); } }; } }; } public static <T1, T2> Function2<Function2<T1, T2, T1>, Function2<T1, T2, T1>, Function2<T1, T2, T1>> compose2() { return new Function2<Function2<T1, T2, T1>, Function2<T1, T2, T1>, Function2<T1, T2, T1>>() { @Override public Function2<T1, T2, T1> apply( final Function2<T1, T2, T1> function1, final Function2<T1, T2, T1> function2 ) { return new Function2<T1, T2, T1>() { @Override public T1 apply( T1 from1, T2 from2 ) { return function1.apply( function2.apply( from1, from2 ), from2 ); } }; } }; } public static Function<Object, String> TO_STRING = new Function<Object, String>() { @Override public String apply( Object from ) { if (from != null) return from.toString(); else return ""; } }; private Functions() { } public static <FROM, TO> Function<FROM, TO> cast( final Class<TO> to ) { return new Function<FROM, TO>() { @Override public TO apply( FROM from ) { return to.cast( from ); } @Override public String toString() { return "cast(to=" + to.getName() + ")"; } }; } }
false
community_kernel_src_main_java_org_neo4j_helpers_Functions.java
5,463
private static class ThreadLocalFormat extends ThreadLocal<DateFormat> { private final String format; ThreadLocalFormat( String format ) { this.format = format; } String format( Date date, TimeZone timeZone ) { DateFormat dateFormat = get(); dateFormat.setTimeZone( timeZone ); return dateFormat.format( date ); } @Override protected DateFormat initialValue() { return new SimpleDateFormat( format ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_Format.java
5,464
public static class Present<V> extends FutureAdapter<V> { private final V value; public Present( V value ) { this.value = value; } @Override public boolean isDone() { return true; } @Override public V get() { return value; } @Override public V get( long timeout, TimeUnit unit ) { return value; } };
false
community_kernel_src_main_java_org_neo4j_helpers_FutureAdapter.java
5,465
public class HostnamePortTest { @Test public void testHostnameOnly() { HostnamePort hostnamePort = new HostnamePort( "myhost" ); assertThat( hostnamePort.getHost(), equalTo( "myhost" ) ); assertThat( hostnamePort.getPort(), equalTo( 0 ) ); assertThat( hostnamePort.getPorts(), equalTo( new int[]{0, 0} ) ); } @Test public void testHostnamePort() { HostnamePort hostnamePort = new HostnamePort( "myhost:1234" ); assertThat( hostnamePort.getHost(), equalTo( "myhost" ) ); assertThat( hostnamePort.getPort(), equalTo( 1234 ) ); assertThat( hostnamePort.getPorts(), equalTo( new int[] {1234, 1234} ) ); } @Test public void testHostnamePortRange() { HostnamePort hostnamePort = new HostnamePort( "myhost:1234-1243" ); assertThat( hostnamePort.getHost(), equalTo( "myhost" ) ); assertThat( hostnamePort.getPort(), equalTo( 1234 ) ); assertThat( hostnamePort.getPorts(), equalTo( new int[] {1234, 1243} ) ); } @Test public void testHostnamePortRangeInversed() { HostnamePort hostnamePort = new HostnamePort( "myhost:1243-1234" ); assertThat( hostnamePort.getHost(), equalTo( "myhost" ) ); assertThat( hostnamePort.getPort(), equalTo( 1243 ) ); assertThat( hostnamePort.getPorts(), equalTo( new int[] {1243, 1234} ) ); } @Test public void testSinglePortOnly() throws Exception { HostnamePort hostnamePort = new HostnamePort( ":1234" ); assertNull( hostnamePort.getHost() ); assertThat( hostnamePort.getPort(), equalTo( 1234 ) ); assertThat( hostnamePort.getPorts(), equalTo( new int[] { 1234, 1234 } ) ); } @Test public void testPortRangeOnly() throws Exception { HostnamePort hostnamePort = new HostnamePort( ":1230-1240" ); assertNull( hostnamePort.getHost() ); assertThat( hostnamePort.getPort(), equalTo( 1230 ) ); assertThat( hostnamePort.getPorts(), equalTo( new int[] { 1230, 1240 } ) ); } @Test public void testDefaultHost() throws Exception { HostnamePort hostnamePort = new HostnamePort( ":1234" ); assertThat( hostnamePort.getHost( "1.2.3.4" ), equalTo( "1.2.3.4" ) ); } @Test public void testMatches() throws Exception { HostnamePort hostnamePortSinglePort = new HostnamePort( "host1:1234" ); // Should match, same host and port assertTrue( hostnamePortSinglePort.matches( URI.create( "ha://host1:1234" ) ) ); // Should fail, different host or port assertFalse( hostnamePortSinglePort.matches( URI.create( "ha://host1:1235" ) ) ); assertFalse( hostnamePortSinglePort.matches( URI.create( "ha://host2:1234" ) ) ); assertFalse( hostnamePortSinglePort.matches( URI.create( "ha://host2:1235" ) ) ); // Should fail, no port assertFalse( hostnamePortSinglePort.matches( URI.create( "ha://host1" ) ) ); assertFalse( hostnamePortSinglePort.matches( URI.create( "ha://host2" ) ) ); HostnamePort hostnamePortWithRange = new HostnamePort( "host1:1234-1236" ); // Should match, port in range and host the same assertTrue( hostnamePortWithRange.matches( URI.create( "ha://host1:1234" ) ) ); assertTrue( hostnamePortWithRange.matches( URI.create( "ha://host1:1235" ) ) ); assertTrue( hostnamePortWithRange.matches( URI.create( "ha://host1:1236" ) ) ); // Should not match, different host assertFalse( hostnamePortWithRange.matches( URI.create( "ha://host2:1234" ) ) ); assertFalse( hostnamePortWithRange.matches( URI.create( "ha://host2:1235" ) ) ); // Should not match, port outside of range assertFalse( hostnamePortWithRange.matches( URI.create( "ha://host1:1233" ) ) ); assertFalse( hostnamePortWithRange.matches( URI.create( "ha://host1:1237" ) ) ); // Should not match, no port assertFalse( hostnamePortWithRange.matches( URI.create( "ha://host1" ) ) ); assertFalse( hostnamePortWithRange.matches( URI.create( "ha://host2" ) ) ); } @Test public void testMatchesNullHost() throws Exception { HostnamePort hostnamePortSinglePort = new HostnamePort( ":1234" ); assertFalse( hostnamePortSinglePort.matches( URI.create( "ha://host1:1234" ) ) ); // no scheme means no ports and no host, so both null therefore comparison fails assertFalse( hostnamePortSinglePort.matches( URI.create( "host1:1234" ) ) ); } @Test public void testHostnameLookup() throws Exception { String hostName = InetAddress.getLocalHost().getHostName(); HostnamePort hostnamePort = new HostnamePort( hostName, 1234 ); assertThat( hostnamePort.toString( null ), equalTo( InetAddress.getByName( hostName ).getHostAddress()+":1234" ) ); } }
false
community_kernel_src_test_java_org_neo4j_helpers_HostnamePortTest.java
5,466
{ @Override public void failed( InstanceId server ) { failedLatch.countDown(); } @Override public void alive( InstanceId server ) { } };
false
enterprise_ha_src_test_java_org_neo4j_ha_TestSlaveOnlyCluster.java
5,467
public class Listeners { public interface Notification<T> { void notify(T listener); } public static <T> Iterable<T> newListeners() { return new LinkedList<T>(); } public static <T> Iterable<T> addListener(T listener, Iterable<T> listeners) { List<T> newListeners = new LinkedList<T>( (Collection<T>) listeners ); newListeners.add( listener ); return newListeners; } public static <T> Iterable<T> removeListener(T listener, Iterable<T> listeners) { List<T> newListeners = new LinkedList<T>( (Collection<T>) listeners ); newListeners.remove( listener ); return newListeners; } /** * @return {@code true} if all listeners succeeded, otherwise {@code false} if one or more failed. */ public static <T> boolean notifyListeners(Iterable<T> listeners, Notification<T> notification) { boolean successful = true; for( T listener : listeners ) { synchronized( listener ) { try { notification.notify( listener ); } catch( Throwable e ) { e.printStackTrace(); successful = false; } } } return successful; } public static <T> void notifyListeners(Iterable<T> listeners, Executor executor, final Notification<T> notification) { for( final T listener : listeners ) { executor.execute( new Runnable() { @Override public void run() { synchronized( listener ) { try { notification.notify( listener ); } catch( Throwable e ) { e.printStackTrace(); } } } }); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_Listeners.java
5,468
public class RunCarefully { private final Runnable[] operations; public RunCarefully( Runnable... operations ) { this.operations = operations; } public RunCarefully( Iterable<Runnable> operations ) { this( toArray( Runnable.class, operations ) ); } public void run() { Throwable error = null; for ( Runnable o : operations ) { try { o.run(); } catch ( RuntimeException e) { error = combine( error, e ); } } if ( error != null ) { throw new RuntimeException( error ); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_RunCarefully.java
5,469
public static final class Entry { private final String part; private final Throwable failure; public Entry( String part, Throwable failure ) { this.part = part; this.failure = failure; } @Override public String toString() { return "In '" + part + "': " + failure; } }
false
community_kernel_src_main_java_org_neo4j_helpers_ProcessFailureException.java
5,470
public class ProcessFailureException extends Exception { public static final class Entry { private final String part; private final Throwable failure; public Entry( String part, Throwable failure ) { this.part = part; this.failure = failure; } @Override public String toString() { return "In '" + part + "': " + failure; } } private final Entry[] causes; public ProcessFailureException( List<Entry> causes ) { super( "Monitored process failed" + message( causes ), cause( causes ) ); this.causes = causes.toArray( new Entry[causes.size()] ); } private static String message( List<Entry> causes ) { if ( causes.isEmpty() ) { return "."; } if ( causes.size() == 1 ) { return " in '" + causes.get( 0 ).part + "'."; } StringBuilder result = new StringBuilder( ":" ); for ( Entry entry : causes ) { result.append( "\n\t" ).append( entry ); } return result.toString(); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") private static Throwable cause( List<Entry> causes ) { return causes.size() >= 1 ? causes.get( 0 ).failure : null; } @Override public void printStackTrace( PrintStream s ) { super.printStackTrace( s ); printAllCauses( new PrintWriter( s, true ) ); } @Override public void printStackTrace( PrintWriter s ) { super.printStackTrace( s ); printAllCauses( s ); } public void printAllCauses( PrintWriter writer ) { if ( getCause() == null ) { for ( Entry entry : causes ) { entry.failure.printStackTrace( writer ); } writer.flush(); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_ProcessFailureException.java
5,471
public static class OrPredicate<T> implements Predicate<T> { private final Iterable<Predicate<T>> predicates; private OrPredicate( Iterable<Predicate<T>> predicates ) { this.predicates = predicates; } @Override public boolean accept( T instance ) { for ( Predicate<T> specification : predicates ) { if ( specification.accept( instance ) ) { return true; } } return false; } public AndPredicate<T> and( Predicate<T>... predicates ) { return Predicates.and( Iterables.prepend( this, Arrays.asList( predicates ) ) ); } public OrPredicate<T> or( Predicate<T>... predicates ) { Iterable<Predicate<T>> iterable = Iterables.iterable( predicates ); Iterable<Predicate<T>> flatten = Iterables.flatten( this.predicates, iterable ); return Predicates.or( flatten ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_Predicates.java
5,472
public static class AndPredicate<T> implements Predicate<T> { private final Iterable<Predicate<T>> predicates; private AndPredicate( Iterable<Predicate<T>> predicates ) { this.predicates = predicates; } @Override public boolean accept( T instance ) { for ( Predicate<T> specification : predicates ) { if ( !specification.accept( instance ) ) { return false; } } return true; } public AndPredicate<T> and( Predicate<T>... predicates ) { Iterable<Predicate<T>> iterable = Iterables.iterable( predicates ); Iterable<Predicate<T>> flatten = Iterables.flatten( this.predicates, iterable ); return Predicates.and( flatten ); } public OrPredicate<T> or( Predicate<T>... predicates ) { return Predicates.or( Iterables.prepend( this, Arrays.asList( predicates ) ) ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_Predicates.java
5,473
{ @Override public boolean accept( String item ) { return item.contains( string ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Predicates.java
5,474
{ @Override public boolean accept( FROM item ) { return specification.accept( function.apply( item ) ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Predicates.java
5,475
{ @Override public boolean accept( Object item ) { return item != null; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Predicates.java
5,476
{ @Override public boolean accept( T item ) { return allowed.contains( item ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Predicates.java
5,477
{ @Override public boolean accept( T item ) { for ( T allow : allowed ) { if ( allow.equals( item ) ) { return true; } } return false; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Predicates.java
5,478
{ @Override public boolean accept( T item ) { return allowed == null ? item == null : allowed.equals( item ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Predicates.java
5,479
{ @Override public boolean accept( T instance ) { return !specification.accept( instance ); } };
false
community_kernel_src_main_java_org_neo4j_helpers_Predicates.java
5,480
{ @Override public boolean accept( T instance ) { return true; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Predicates.java
5,481
public class Predicates { public static <T> Predicate<T> TRUE() { return new Predicate<T>() { @Override public boolean accept( T instance ) { return true; } }; } public static <T> Predicate<T> not( final Predicate<T> specification ) { return new Predicate<T>() { @Override public boolean accept( T instance ) { return !specification.accept( instance ); } }; } public static <T> AndPredicate<T> and( final Predicate<T>... predicates ) { return and( Arrays.asList( predicates ) ); } public static <T> AndPredicate<T> and( final Iterable<Predicate<T>> predicates ) { return new AndPredicate<T>( predicates ); } public static <T> OrPredicate<T> or( final Predicate<T>... predicates ) { return or( Arrays.asList( predicates ) ); } public static <T> OrPredicate<T> or( final Iterable<Predicate<T>> predicates ) { return new OrPredicate<T>( predicates ); } public static <T> Predicate<T> equalTo( final T allowed ) { return new Predicate<T>() { @Override public boolean accept( T item ) { return allowed == null ? item == null : allowed.equals( item ); } }; } public static <T> Predicate<T> in( final T... allowed ) { return in( Arrays.asList( allowed ) ); } public static <T> Predicate<T> in( final Iterable<T> allowed ) { return new Predicate<T>() { @Override public boolean accept( T item ) { for ( T allow : allowed ) { if ( allow.equals( item ) ) { return true; } } return false; } }; } public static <T> Predicate<T> in( final Collection<T> allowed ) { return new Predicate<T>() { @Override public boolean accept( T item ) { return allowed.contains( item ); } }; } @SuppressWarnings( "rawtypes" ) private static Predicate NOT_NULL = new Predicate() { @Override public boolean accept( Object item ) { return item != null; } }; @SuppressWarnings( "unchecked" ) public static <T> Predicate<T> notNull() { return NOT_NULL; } public static <FROM, TO> Predicate<FROM> translate( final Function<FROM, TO> function, final Predicate<? super TO> specification ) { return new Predicate<FROM>() { @Override public boolean accept( FROM item ) { return specification.accept( function.apply( item ) ); } }; } public static class AndPredicate<T> implements Predicate<T> { private final Iterable<Predicate<T>> predicates; private AndPredicate( Iterable<Predicate<T>> predicates ) { this.predicates = predicates; } @Override public boolean accept( T instance ) { for ( Predicate<T> specification : predicates ) { if ( !specification.accept( instance ) ) { return false; } } return true; } public AndPredicate<T> and( Predicate<T>... predicates ) { Iterable<Predicate<T>> iterable = Iterables.iterable( predicates ); Iterable<Predicate<T>> flatten = Iterables.flatten( this.predicates, iterable ); return Predicates.and( flatten ); } public OrPredicate<T> or( Predicate<T>... predicates ) { return Predicates.or( Iterables.prepend( this, Arrays.asList( predicates ) ) ); } } public static class OrPredicate<T> implements Predicate<T> { private final Iterable<Predicate<T>> predicates; private OrPredicate( Iterable<Predicate<T>> predicates ) { this.predicates = predicates; } @Override public boolean accept( T instance ) { for ( Predicate<T> specification : predicates ) { if ( specification.accept( instance ) ) { return true; } } return false; } public AndPredicate<T> and( Predicate<T>... predicates ) { return Predicates.and( Iterables.prepend( this, Arrays.asList( predicates ) ) ); } public OrPredicate<T> or( Predicate<T>... predicates ) { Iterable<Predicate<T>> iterable = Iterables.iterable( predicates ); Iterable<Predicate<T>> flatten = Iterables.flatten( this.predicates, iterable ); return Predicates.or( flatten ); } } public static Predicate<String> stringContains( final String string ) { return new Predicate<String>() { @Override public boolean accept( String item ) { return item.contains( string ); } }; } }
false
community_kernel_src_main_java_org_neo4j_helpers_Predicates.java
5,482
public class Platforms { private static final String OS_NAME = System.getProperty("os.name").toLowerCase(); public static boolean platformIsWindows() { return OS_NAME.indexOf( "win" ) >= 0; } }
false
community_kernel_src_main_java_org_neo4j_helpers_Platforms.java
5,483
{ @Override public T1 first() { return first; } @Override public T2 other() { return other; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Pair.java
5,484
public abstract class Pair<T1, T2> { @SuppressWarnings( "rawtypes" ) private static final Pair EMPTY = Pair.of( null, null ); @SuppressWarnings( "unchecked" ) public static <T1, T2> Pair<T1, T2> empty() { return EMPTY; } /** * Create a new pair of objects. * * @param first the first object in the pair. * @param other the other object in the pair. * @return a new pair of the two parameters. */ public static <T1, T2> Pair<T1, T2> of( final T1 first, final T2 other ) { return new Pair<T1, T2>() { @Override public T1 first() { return first; } @Override public T2 other() { return other; } }; } Pair() { // package private, limited number of subclasses } /** * @return the first object in the pair. */ public abstract T1 first(); /** * @return the other object in the pair. */ public abstract T2 other(); @Override public String toString() { return "(" + first() + ", " + other() + ")"; } @Override public int hashCode() { return ( 31 * hashCode( first() ) ) | hashCode( other() ); } @Override public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj instanceof Pair ) { @SuppressWarnings( "rawtypes" ) Pair that = (Pair) obj; return equals( this.other(), that.other() ) && equals( this.first(), that.first() ); } return false; } static int hashCode( Object obj ) { return obj == null ? 0 : obj.hashCode(); } static boolean equals( Object obj1, Object obj2 ) { return ( obj1 == obj2 ) || ( obj1 != null && obj1.equals( obj2 ) ); } }
false
community_kernel_src_main_java_org_neo4j_helpers_Pair.java
5,485
public class NamedThreadFactory implements ThreadFactory { private final ThreadGroup group; private final AtomicInteger threadCounter = new AtomicInteger( 1 ); private String threadNamePrefix; private final int priority; public NamedThreadFactory( String threadNamePrefix ) { this( threadNamePrefix, Thread.NORM_PRIORITY ); } public NamedThreadFactory( String threadNamePrefix, int priority ) { this.threadNamePrefix = threadNamePrefix; SecurityManager securityManager = System.getSecurityManager(); group = (securityManager != null) ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup(); this.priority = priority; } public Thread newThread( Runnable runnable ) { final int id = threadCounter.getAndIncrement(); Thread result = new Thread( group, runnable, threadNamePrefix + "-" + id ); result.setDaemon( false ); result.setPriority( priority ); return result; } }
false
community_kernel_src_main_java_org_neo4j_helpers_NamedThreadFactory.java
5,486
{ @Override public void run() { synchronized( listener ) { try { notification.notify( listener ); } catch( Throwable e ) { e.printStackTrace(); } } } });
false
community_kernel_src_main_java_org_neo4j_helpers_Listeners.java
5,487
public class Format { public static String date() { return date( DEFAULT_TIME_ZONE ); } public static String date( TimeZone timeZone ) { return date( new Date(), timeZone ); } public static String date( long millis ) { return date( millis, DEFAULT_TIME_ZONE ); } public static String date( long millis, TimeZone timeZone ) { return date( new Date( millis ), timeZone ); } public static String date( Date date ) { return date( date, DEFAULT_TIME_ZONE ); } public static String date( Date date, TimeZone timeZone ) { return DATE.format( date, timeZone ); } public static String time() { return time( DEFAULT_TIME_ZONE ); } public static String time( TimeZone timeZone ) { return time( new Date() ); } public static String time( long millis ) { return time( millis, DEFAULT_TIME_ZONE ); } public static String time( long millis, TimeZone timeZone ) { return time( new Date( millis ), timeZone ); } public static String time( Date date ) { return time( date, DEFAULT_TIME_ZONE ); } public static String time( Date date, TimeZone timeZone ) { return TIME.format( date, timeZone ); } public static String bytes( long bytes ) { double size = bytes; for ( String suffix : BYTE_SIZES ) { if ( size < 1024 ) return String.format( "%.2f %s", Double.valueOf( size ), suffix ); size /= 1024; } return String.format( "%.2f TB", Double.valueOf( size ) ); } private Format() { // No instances } private static final String[] BYTE_SIZES = { "B", "kB", "MB", "GB" }; public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSSZ"; public static final String TIME_FORMAT = "HH:mm:ss.SSS"; /** * Default time zone is UTC (+00:00) so that comparing timestamped logs from different * sources is an easier task. */ public static final TimeZone DEFAULT_TIME_ZONE = TimeZone.getTimeZone( "UTC" ); private static final ThreadLocalFormat DATE = new ThreadLocalFormat( DATE_FORMAT ), TIME = new ThreadLocalFormat( TIME_FORMAT ); private static class ThreadLocalFormat extends ThreadLocal<DateFormat> { private final String format; ThreadLocalFormat( String format ) { this.format = format; } String format( Date date, TimeZone timeZone ) { DateFormat dateFormat = get(); dateFormat.setTimeZone( timeZone ); return dateFormat.format( date ); } @Override protected DateFormat initialValue() { return new SimpleDateFormat( format ); } } }
false
community_kernel_src_main_java_org_neo4j_helpers_Format.java
5,488
public abstract class FooService extends Service { public FooService() { super("foo"); } }
false
community_kernel_src_test_java_org_neo4j_helpers_FooService.java
5,489
public class FakeClock implements Clock { private long time = 0; @Override public long currentTimeMillis() { return time; } public void forward( long amount, TimeUnit timeUnit) { time = time + timeUnit.toMillis( amount ); } }
false
community_kernel_src_test_java_org_neo4j_helpers_FakeClock.java
5,490
{ @Override public boolean accept( Throwable item ) { for ( Class cls : anyOfTheseClasses ) { if ( cls.isInstance( item ) ) { return true; } } return false; } };
false
community_kernel_src_main_java_org_neo4j_helpers_Exceptions.java
5,491
class MessageDeliveryAction implements ClusterAction { public static final Function<Message,ClusterAction> MESSAGE_TO_ACTION = new Function<Message, ClusterAction>() { @Override public ClusterAction apply( Message message ) { return new MessageDeliveryAction( message ); } }; private final Message message; public MessageDeliveryAction( Message message ) { this.message = message; } @Override public Iterable<ClusterAction> perform( ClusterState state ) throws URISyntaxException { String to = message.getHeader( Message.TO ); return Iterables.map( MESSAGE_TO_ACTION, state.instance( to ).process( messageCopy() ) ); } private Message<? extends MessageType> messageCopy() throws URISyntaxException { URI to = new URI( message.getHeader( Message.TO ) ); Message<MessageType> copy = Message.to( message.getMessageType(), to, message.getPayload()); return message.copyHeadersTo( copy ); } @Override public String toString() { return "("+message.getHeader( Message.FROM ) + ")-[" + message.getMessageType().name() + "]->(" + message.getHeader( Message.TO ) + ")"; } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } return messageEquals( message, ((MessageDeliveryAction) o).message ); } private boolean messageEquals( Message first, Message other ) { if( !first.getMessageType().equals( other.getMessageType() )) { return false; } if( !first.getHeader( Message.FROM ).equals( other.getHeader( Message.FROM ) )) { return false; } if( !first.getHeader( Message.TO ).equals( other.getHeader( Message.TO ) )) { return false; } if(first.getPayload() instanceof Message && other.getPayload() instanceof Message) { return messageEquals((Message)first.getPayload(), (Message)other.getPayload() ); } else if(first.getPayload() == null) { if(other.getPayload() != null) { return false; } } else if( !first.getPayload().equals( other.getPayload() )) { return false; } return true; } @Override public int hashCode() { int result = message.getMessageType().hashCode(); result = 31 * result + message.getHeader( Message.FROM ).hashCode(); result = 31 * result + message.getHeader( Message.TO ).hashCode(); return result; } }
false
enterprise_ha_src_test_java_org_neo4j_ha_correctness_MessageDeliveryAction.java
5,492
public class InstanceCrashedAction implements ClusterAction { private final String instanceUri; public InstanceCrashedAction( String instanceUri ) { this.instanceUri = instanceUri; } @Override public Iterable<ClusterAction> perform( ClusterState state ) throws Exception { state.instance( instanceUri ).crash(); return Iterables.empty(); } @Override public String toString() { return "[CRASH "+instanceUri+"]"; } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } return instanceUri.equals( ((InstanceCrashedAction)o).instanceUri ); } @Override public int hashCode() { return instanceUri.hashCode(); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_correctness_InstanceCrashedAction.java
5,493
public class GraphVizExporter { private final File target; public GraphVizExporter( File target ) { this.target = target; } public void export(GraphDatabaseService db) throws IOException { FileOutputStream stream = new FileOutputStream( target ); PrintWriter out = new PrintWriter( stream ); out.println("digraph G {"); out.println(" rankdir=LR;"); try( Transaction tx = db.beginTx() ) { Set<Node> seen = new HashSet<>(); Queue<Node> toExplore = new LinkedList<>(); toExplore.add( db.getNodeById( 0 ) ); while(toExplore.size() > 0) { Node current = toExplore.poll(); out.println( " " + current.getId() + " [shape=box,label=\"" + current.getProperty( "description" ) + "\"];" ); for ( Relationship relationship : current.getRelationships() ) { out.println(" " + current.getId() + " -> " + relationship.getEndNode().getId() + " [label=\""+relationship.getProperty( "description" )+"\"];" ); if(!seen.contains( relationship.getEndNode() )) { toExplore.offer( relationship.getEndNode() ); seen.add( relationship.getEndNode() ); } } } tx.success(); } out.println("}"); out.flush(); stream.close(); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_correctness_GraphVizExporter.java
5,494
{ @Override protected Pair<ClusterAction, ClusterState> fetchNextOrNull() { try { if(actions.hasNext()) { ClusterAction action = actions.next(); return Pair.of( action, performAction( action ) ); } else if(instancesWithTimeouts.hasNext()) { ClusterInstance instance = instancesWithTimeouts.next(); return performNextTimeoutFrom(instance); } else { return null; } } catch(Exception e) { throw new RuntimeException( e ); } } };
false
enterprise_ha_src_test_java_org_neo4j_ha_correctness_ClusterState.java
5,495
{ @Override public boolean accept( ClusterInstance item ) { return item.hasPendingTimeouts(); } };
false
enterprise_ha_src_test_java_org_neo4j_ha_correctness_ClusterState.java
5,496
class ClusterState { public static final Predicate<ClusterInstance> HAS_TIMEOUTS = new Predicate<ClusterInstance>() { @Override public boolean accept( ClusterInstance item ) { return item.hasPendingTimeouts(); } }; private final Set<ClusterAction> pendingActions; private final List<ClusterInstance> instances = new ArrayList<>(); public ClusterState( List<ClusterInstance> instances, Set<ClusterAction> pendingActions ) { this.pendingActions = pendingActions instanceof LinkedHashSet ? pendingActions : new LinkedHashSet<>( pendingActions ); for ( ClusterInstance instance : instances ) { this.instances.add( instance ); } } public void addPendingActions( ClusterAction ... actions ) { for ( ClusterAction action : actions ) { pendingActions.add( action ); } } /** All possible new cluster states that can be generated from this one. */ public Iterator<Pair<ClusterAction, ClusterState>> transitions() { final Iterator<ClusterAction> actions = pendingActions.iterator(); final Iterator<ClusterInstance> instancesWithTimeouts = filter( HAS_TIMEOUTS, instances ).iterator(); return new PrefetchingIterator<Pair<ClusterAction, ClusterState>>() { @Override protected Pair<ClusterAction, ClusterState> fetchNextOrNull() { try { if(actions.hasNext()) { ClusterAction action = actions.next(); return Pair.of( action, performAction( action ) ); } else if(instancesWithTimeouts.hasNext()) { ClusterInstance instance = instancesWithTimeouts.next(); return performNextTimeoutFrom(instance); } else { return null; } } catch(Exception e) { throw new RuntimeException( e ); } } }; } /** Managing timeouts is trickier than putting all of them in a long list, like regular message delivery. * Timeouts are ordered and can be cancelled, so they need special treatment. Hence a separate method for * managing timeouts triggering. */ private Pair<ClusterAction, ClusterState> performNextTimeoutFrom( ClusterInstance instance ) throws Exception { ClusterState newState = snapshot(); ClusterAction clusterAction = newState.instance( instance.uri().toASCIIString() ).popTimeout(); clusterAction.perform( newState ); return Pair.of(clusterAction, newState); } /** Clone the state and perform the action with the provided index. Returns the new state and the action. */ ClusterState performAction( ClusterAction action ) throws Exception { ClusterState newState = snapshot(); // Remove the action from the list of things that can happen in the snapshot newState.pendingActions.remove( action ); // Perform the action on the cloned state Iterable<ClusterAction> newActions = action.perform( newState ); // Include any outcome actions into the new state snapshot newState.pendingActions.addAll( asCollection(newActions) ); return newState; } public ClusterState snapshot() { Set<ClusterAction> newPendingActions = new LinkedHashSet<>( pendingActions ); // Clone the current state & perform the action on it to change it List<ClusterInstance> cloneInstances = new ArrayList<>(); for ( ClusterInstance clusterInstance : instances ) { cloneInstances.add( clusterInstance.newCopy() ); } return new ClusterState(cloneInstances, newPendingActions); } public ClusterInstance instance( String to ) throws URISyntaxException { URI uri = new URI(to); for ( ClusterInstance clusterInstance : instances ) { URI instanceUri = clusterInstance.uri(); if( instanceUri.getHost().equals( uri.getHost() ) && instanceUri.getPort() == uri.getPort()) { return clusterInstance; } } throw new IllegalArgumentException( "No instance in cluster at address: " + to ); } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } ClusterState that = (ClusterState) o; if ( !instances.equals( that.instances ) ) { return false; } if ( !pendingActions.equals( that.pendingActions ) ) { return false; } return true; } @Override public int hashCode() { int result = instances.hashCode(); result = 31 * result + pendingActions.hashCode(); return result; } @Override public String toString() { return "Cluster["+ Iterables.toString( instances, ", " )+"]"; } public boolean isDeadEnd() { if(pendingActions.size() > 0) { return false; } for ( ClusterInstance instance : instances ) { if(instance.hasPendingTimeouts()) { return false; } } return true; } }
false
enterprise_ha_src_test_java_org_neo4j_ha_correctness_ClusterState.java
5,497
static class StateVerifierLastTxIdGetter implements LastTxIdGetter { @Override public long getLastTxId() { return 0; } }
false
enterprise_ha_src_test_java_org_neo4j_ha_correctness_ClusterInstance.java
5,498
static class MemberInfoProvider implements HighAvailabilityMemberInfoProvider { @Override public HighAvailabilityMemberState getHighAvailabilityMemberState() { throw new UnsupportedOperationException( "TODO" ); } }
false
enterprise_ha_src_test_java_org_neo4j_ha_correctness_ClusterInstance.java
5,499
private static class ClusterInstanceOutput implements MessageSender { private final List<Message<? extends MessageType>> messages = new ArrayList<>(); private final URI uri; public ClusterInstanceOutput( URI uri ) { this.uri = uri; } @Override public boolean process( Message<? extends MessageType> message ) { messages.add( message.setHeader( Message.FROM, uri.toASCIIString() ) ); return true; } @Override public void process( List<Message<? extends MessageType>> msgList ) { for ( Message<? extends MessageType> msg : msgList ) { process( msg ); } } public Iterable<Message<? extends MessageType>> messages() { return messages; } }
false
enterprise_ha_src_test_java_org_neo4j_ha_correctness_ClusterInstance.java