idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
34,100
@ Procedure ( mode = Mode . WRITE ) @ Description ( "apoc.refactor.rename.nodeProperty(oldName, newName, [nodes]) | rename all node's property from 'oldName' to 'newName'. If 'nodes' is provided renaming is applied to this set only" ) public Stream < BatchAndTotalResultWithInfo > nodeProperty ( @ Name ( "oldName" ) String oldName , @ Name ( "newName" ) String newName , @ Name ( value = "nodes" , defaultValue = "" ) List < Object > nodes ) { String cypherIterate = nodes != null && ! nodes . isEmpty ( ) ? "UNWIND {nodes} AS n WITH n WHERE exists (n." + oldName + ") return n" : "match (n) where exists (n." + oldName + ") return n" ; String cypherAction = "set n." + newName + "= n." + oldName + " remove n." + oldName ; Map < String , Object > parameters = MapUtil . map ( "batchSize" , 100000 , "parallel" , true , "iterateList" , true , "params" , MapUtil . map ( "nodes" , nodes ) ) ; return getResultOfBatchAndTotalWithInfo ( newPeriodic ( ) . iterate ( cypherIterate , cypherAction , parameters ) , db , null , null , oldName ) ; }
Rename property of a node by creating a new one and deleting the old .
34,101
@ Description ( "apoc.meta.data({config}) - examines a subset of the graph to provide a tabular meta information" ) public Stream < MetaResult > data ( @ Name ( value = "config" , defaultValue = "{}" ) Map < String , Object > config ) { MetaConfig metaConfig = new MetaConfig ( config ) ; return collectMetaData ( metaConfig ) . values ( ) . stream ( ) . flatMap ( x -> x . values ( ) . stream ( ) ) ; }
todo put index sizes for indexed properties
34,102
private static int [ ] growArray ( int [ ] array , float growFactor ) { int currentSize = array . length ; int newArray [ ] = new int [ ( int ) ( currentSize * growFactor ) ] ; System . arraycopy ( array , 0 , newArray , 0 , currentSize ) ; return newArray ; }
Not doing it right now because of the complications of the interface .
34,103
private Boolean indexExists ( String labelName , List < String > propertyNames ) { Schema schema = db . schema ( ) ; for ( IndexDefinition indexDefinition : Iterables . asList ( schema . getIndexes ( Label . label ( labelName ) ) ) ) { List < String > properties = Iterables . asList ( indexDefinition . getPropertyKeys ( ) ) ; if ( properties . equals ( propertyNames ) ) { return true ; } } return false ; }
Checks if an index exists for a given label and a list of properties This method checks for index on nodes
34,104
private Boolean constraintsExists ( String labelName , List < String > propertyNames ) { Schema schema = db . schema ( ) ; for ( ConstraintDefinition constraintDefinition : Iterables . asList ( schema . getConstraints ( Label . label ( labelName ) ) ) ) { List < String > properties = Iterables . asList ( constraintDefinition . getPropertyKeys ( ) ) ; if ( properties . equals ( propertyNames ) ) { return true ; } } return false ; }
Checks if a constraint exists for a given label and a list of properties This method checks for constraints on node
34,105
private Boolean constraintsExistsForRelationship ( String type , List < String > propertyNames ) { Schema schema = db . schema ( ) ; for ( ConstraintDefinition constraintDefinition : Iterables . asList ( schema . getConstraints ( RelationshipType . withName ( type ) ) ) ) { List < String > properties = Iterables . asList ( constraintDefinition . getPropertyKeys ( ) ) ; if ( properties . equals ( propertyNames ) ) { return true ; } } return false ; }
Checks if a constraint exists for a given type and a list of properties This method checks for constraints on relationships
34,106
private Stream < ConstraintRelationshipInfo > constraintsForRelationship ( Map < String , Object > config ) { Schema schema = db . schema ( ) ; SchemaConfig schemaConfig = new SchemaConfig ( config ) ; Set < String > includeRelationships = schemaConfig . getRelationships ( ) ; Set < String > excludeRelationships = schemaConfig . getExcludeRelationships ( ) ; try ( Statement ignore = tx . acquireStatement ( ) ) { TokenRead tokenRead = tx . tokenRead ( ) ; Iterable < ConstraintDefinition > constraintsIterator ; if ( ! includeRelationships . isEmpty ( ) ) { constraintsIterator = includeRelationships . stream ( ) . filter ( type -> ! excludeRelationships . contains ( type ) && tokenRead . relationshipType ( type ) != - 1 ) . flatMap ( type -> { Iterable < ConstraintDefinition > constraintsForType = schema . getConstraints ( RelationshipType . withName ( type ) ) ; return StreamSupport . stream ( constraintsForType . spliterator ( ) , false ) ; } ) . collect ( Collectors . toList ( ) ) ; } else { Iterable < ConstraintDefinition > allConstraints = schema . getConstraints ( ) ; constraintsIterator = StreamSupport . stream ( allConstraints . spliterator ( ) , false ) . filter ( index -> ! excludeRelationships . contains ( index . getRelationshipType ( ) . name ( ) ) ) . collect ( Collectors . toList ( ) ) ; } Stream < ConstraintRelationshipInfo > constraintRelationshipInfoStream = StreamSupport . stream ( constraintsIterator . spliterator ( ) , false ) . filter ( constraintDefinition -> constraintDefinition . isConstraintType ( ConstraintType . RELATIONSHIP_PROPERTY_EXISTENCE ) ) . map ( this :: relationshipInfoFromConstraintDefinition ) ; return constraintRelationshipInfoStream ; } }
Collects constraints for relationships
34,107
private IndexConstraintNodeInfo nodeInfoFromConstraintDescriptor ( ConstraintDescriptor constraintDescriptor , TokenNameLookup tokens ) { String labelName = tokens . labelGetName ( constraintDescriptor . schema ( ) . keyId ( ) ) ; List < String > properties = new ArrayList < > ( ) ; Arrays . stream ( constraintDescriptor . schema ( ) . getPropertyIds ( ) ) . forEach ( ( i ) -> properties . add ( tokens . propertyKeyGetName ( i ) ) ) ; return new IndexConstraintNodeInfo ( String . format ( ":%s(%s)" , labelName , StringUtils . join ( properties , "," ) ) , labelName , properties , StringUtils . EMPTY , ConstraintType . NODE_PROPERTY_EXISTENCE . toString ( ) , "NO FAILURE" , 0 , 0 , 0 , constraintDescriptor . userDescription ( tokens ) ) ; }
ConstraintInfo info from ConstraintDescriptor
34,108
private IndexConstraintNodeInfo nodeInfoFromIndexDefinition ( IndexReference indexReference , SchemaRead schemaRead , TokenNameLookup tokens ) { int [ ] labelIds = indexReference . schema ( ) . getEntityTokenIds ( ) ; if ( labelIds . length != 1 ) throw new IllegalStateException ( "Index with more than one label" ) ; String labelName = tokens . labelGetName ( labelIds [ 0 ] ) ; List < String > properties = new ArrayList < > ( ) ; Arrays . stream ( indexReference . properties ( ) ) . forEach ( ( i ) -> properties . add ( tokens . propertyKeyGetName ( i ) ) ) ; try { return new IndexConstraintNodeInfo ( String . format ( ":%s(%s)" , labelName , StringUtils . join ( properties , "," ) ) , labelName , properties , schemaRead . indexGetState ( indexReference ) . toString ( ) , ! indexReference . isUnique ( ) ? "INDEX" : "UNIQUENESS" , schemaRead . indexGetState ( indexReference ) . equals ( InternalIndexState . FAILED ) ? schemaRead . indexGetFailure ( indexReference ) : "NO FAILURE" , schemaRead . indexGetPopulationProgress ( indexReference ) . getCompleted ( ) / schemaRead . indexGetPopulationProgress ( indexReference ) . getTotal ( ) * 100 , schemaRead . indexSize ( indexReference ) , schemaRead . indexUniqueValuesSelectivity ( indexReference ) , indexReference . userDescription ( tokens ) ) ; } catch ( IndexNotFoundKernelException e ) { return new IndexConstraintNodeInfo ( String . format ( ":%s(%s)" , labelName , StringUtils . join ( properties , "," ) ) , labelName , properties , "NOT_FOUND" , ! indexReference . isUnique ( ) ? "INDEX" : "UNIQUENESS" , "NOT_FOUND" , 0 , 0 , 0 , indexReference . userDescription ( tokens ) ) ; } }
Index info from IndexDefinition
34,109
private ConstraintRelationshipInfo relationshipInfoFromConstraintDefinition ( ConstraintDefinition constraintDefinition ) { return new ConstraintRelationshipInfo ( String . format ( "CONSTRAINT %s" , constraintDefinition . toString ( ) ) , constraintDefinition . getConstraintType ( ) . name ( ) , Iterables . asList ( constraintDefinition . getPropertyKeys ( ) ) , "" ) ; }
Constraint info from ConstraintDefinition for relationships
34,110
@ UserFunction ( "apoc.temporal.format" ) @ Description ( "apoc.temporal.format(input, format) | Format a temporal value" ) public String format ( @ Name ( "temporal" ) Object input , @ Name ( value = "format" , defaultValue = "yyyy-MM-dd" ) String format ) { try { DateTimeFormatter formatter = getOrCreate ( format ) ; if ( input instanceof LocalDate ) { return ( ( LocalDate ) input ) . format ( formatter ) ; } else if ( input instanceof ZonedDateTime ) { return ( ( ZonedDateTime ) input ) . format ( formatter ) ; } else if ( input instanceof LocalDateTime ) { return ( ( LocalDateTime ) input ) . format ( formatter ) ; } else if ( input instanceof LocalTime ) { return ( ( LocalTime ) input ) . format ( formatter ) ; } else if ( input instanceof OffsetTime ) { return ( ( OffsetTime ) input ) . format ( formatter ) ; } else if ( input instanceof DurationValue ) { return formatDuration ( input , format ) ; } } catch ( Exception e ) { throw new RuntimeException ( "Available formats are:\n" + String . join ( "\n" , getTypes ( ) ) + "\nSee also: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/mapping-date-format.html#built-in-date-formats " + "and https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html" ) ; } return input . toString ( ) ; }
Format a temporal value to a String
34,111
@ UserFunction ( "apoc.temporal.formatDuration" ) @ Description ( "apoc.temporal.formatDuration(input, format) | Format a Duration" ) public String formatDuration ( @ Name ( "input" ) Object input , @ Name ( "format" ) String format ) { try { LocalDateTime midnight = LocalDateTime . of ( 0 , 1 , 1 , 0 , 0 , 0 , 0 ) ; LocalDateTime newDuration = midnight . plus ( ( DurationValue ) input ) ; DateTimeFormatter formatter = getOrCreate ( format ) ; return newDuration . format ( formatter ) ; } catch ( Exception e ) { throw new RuntimeException ( "Available formats are:\n" + String . join ( "\n" , getTypes ( ) ) + "\nSee also: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/mapping-date-format.html#built-in-date-formats " + "and https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html" ) ; } }
Convert a Duration into a LocalTime and format the value as a String
34,112
protected int getMajorVersion ( ) { return this . cluster . authenticate ( this . passwordAuthenticator ) . clusterManager ( ) . info ( 5 , TimeUnit . SECONDS ) . getMinVersion ( ) . major ( ) ; }
Get the major version of Couchbase server that is 4 . x or 5 . x
34,113
public List < JsonObject > executeStatement ( String statement ) { SimpleN1qlQuery query = N1qlQuery . simple ( statement ) ; return executeQuery ( query ) ; }
Executes a plain un - parameterized N1QL kernelTransaction .
34,114
public List < JsonObject > executeParametrizedStatement ( String statement , List < Object > parameters ) { JsonArray positionalParams = JsonArray . from ( parameters ) ; ParameterizedN1qlQuery query = N1qlQuery . parameterized ( statement , positionalParams ) ; return executeQuery ( query ) ; }
Executes a N1QL kernelTransaction with positional parameters .
34,115
public List < JsonObject > executeParametrizedStatement ( String statement , List < String > parameterNames , List < Object > parameterValues ) { JsonObject namedParams = JsonObject . create ( ) ; for ( int param = 0 ; param < parameterNames . size ( ) ; param ++ ) { namedParams . put ( parameterNames . get ( param ) , parameterValues . get ( param ) ) ; } ParameterizedN1qlQuery query = N1qlQuery . parameterized ( statement , namedParams ) ; return executeQuery ( query ) ; }
Executes a N1QL kernelTransaction with named parameters .
34,116
private List < Pair < Integer , Integer > > doGenerateEdgesWithOmitList ( ) { final int numberOfNodes = getConfiguration ( ) . getNumberOfNodes ( ) ; final int numberOfEdges = getConfiguration ( ) . getNumberOfEdges ( ) ; final long maxEdges = numberOfNodes * ( numberOfNodes - 1 ) / 2 ; final List < Pair < Integer , Integer > > edges = new LinkedList < > ( ) ; for ( Long index : edgeIndices ( numberOfEdges , maxEdges ) ) { edges . add ( indexToEdgeBijection ( index ) ) ; } return edges ; }
Improved implementation of Erdos - Renyi generator based on bijection from edge labels to edge realisations . Works very well for large number of nodes but is slow with increasing number of edges . Best for denser networks with a clear giant component .
34,117
private Pair < Integer , Integer > indexToEdgeBijection ( long index ) { long i = ( long ) Math . ceil ( ( Math . sqrt ( 1 + 8 * ( index + 1 ) ) - 1 ) / 2 ) ; long diff = index + 1 - ( i * ( i - 1 ) ) / 2 ; return Pair . of ( ( int ) i , ( int ) diff - 1 ) ; }
Maps an index in a hypothetical list of all edges to the actual edge .
34,118
public static boolean transactionIsTerminated ( TerminationGuard db ) { try { db . check ( ) ; return false ; } catch ( TransactionGuardException | TransactionTerminatedException | NotInTransactionException tge ) { return true ; } }
Given a context related to the procedure invocation this method checks if the transaction is terminated in some way
34,119
private void handleTypeAndAttributes ( Node node , Map < String , Object > elementMap ) { if ( node . getLocalName ( ) != null ) { elementMap . put ( "_type" , node . getLocalName ( ) ) ; } if ( node . getAttributes ( ) != null ) { NamedNodeMap attributeMap = node . getAttributes ( ) ; for ( int i = 0 ; i < attributeMap . getLength ( ) ; i ++ ) { Node attribute = attributeMap . item ( i ) ; elementMap . put ( attribute . getNodeName ( ) , attribute . getNodeValue ( ) ) ; } } }
Collects type and attributes for the node
34,120
private void handleTextNode ( Node node , Map < String , Object > elementMap ) { Object text = "" ; int nodeType = node . getNodeType ( ) ; switch ( nodeType ) { case Node . TEXT_NODE : text = normalizeText ( node . getNodeValue ( ) ) ; break ; case Node . CDATA_SECTION_NODE : text = normalizeText ( ( ( CharacterData ) node ) . getData ( ) ) ; break ; default : break ; } if ( ! StringUtils . isEmpty ( text . toString ( ) ) ) { Object previousText = elementMap . get ( "_text" ) ; if ( previousText != null ) { text = Arrays . asList ( previousText . toString ( ) , text ) ; } elementMap . put ( "_text" , text ) ; } }
Handle TEXT nodes and CDATA nodes
34,121
private String normalizeText ( String text ) { String [ ] tokens = StringUtils . split ( text , "\n" ) ; for ( int i = 0 ; i < tokens . length ; i ++ ) { tokens [ i ] = tokens [ i ] . trim ( ) ; } return StringUtils . join ( tokens , " " ) . trim ( ) ; }
Remove trailing whitespaces and new line characters
34,122
public static List < CsvHeaderField > processHeader ( final String header , final char delimiter , final char quotationCharacter ) { final String separatorRegex = Pattern . quote ( String . valueOf ( delimiter ) ) ; final List < String > attributes = Arrays . asList ( header . split ( separatorRegex ) ) ; final List < CsvHeaderField > fieldEntries = IntStream . range ( 0 , attributes . size ( ) ) . mapToObj ( i -> CsvHeaderField . parse ( i , attributes . get ( i ) , quotationCharacter ) ) . collect ( Collectors . toList ( ) ) ; return fieldEntries ; }
Processes CSV header . Works for both nodes and relationships .
34,123
public static Evaluator endAndTerminatorNodeEvaluator ( List < Node > endNodes , List < Node > terminatorNodes ) { Evaluator endNodeEvaluator = null ; Evaluator terminatorNodeEvaluator = null ; if ( ! endNodes . isEmpty ( ) ) { Node [ ] nodes = endNodes . toArray ( new Node [ endNodes . size ( ) ] ) ; endNodeEvaluator = Evaluators . includeWhereEndNodeIs ( nodes ) ; } if ( ! terminatorNodes . isEmpty ( ) ) { Node [ ] nodes = terminatorNodes . toArray ( new Node [ terminatorNodes . size ( ) ] ) ; terminatorNodeEvaluator = Evaluators . pruneWhereEndNodeIs ( nodes ) ; } if ( endNodeEvaluator != null || terminatorNodeEvaluator != null ) { return new EndAndTerminatorNodeEvaluator ( endNodeEvaluator , terminatorNodeEvaluator ) ; } return null ; }
Returns an evaluator which handles end nodes and terminator nodes Returns null if both lists are empty
34,124
private static int interleaveBits ( int odd , int even ) { int val = 0 ; int max = Math . max ( odd , even ) ; int n = 0 ; while ( max > 0 ) { n ++ ; max >>= 1 ; } for ( int i = 0 ; i < n ; i ++ ) { int bitMask = 1 << i ; int a = ( even & bitMask ) > 0 ? ( 1 << ( 2 * i ) ) : 0 ; int b = ( odd & bitMask ) > 0 ? ( 1 << ( 2 * i + 1 ) ) : 0 ; val += a + b ; } return val ; }
Interleave the bits from two input integer values
34,125
public CoreGraphAlgorithms init ( String label , String rel ) { TokenRead token = ktx . tokenRead ( ) ; int labelId = token . nodeLabel ( label ) ; int relTypeId = token . relationshipType ( rel ) ; loadNodes ( labelId , relTypeId ) ; loadRels ( labelId , relTypeId ) ; return this ; }
keep threads with open worker - tx for reads
34,126
public Chunks withDefault ( int defaultValue ) { this . defaultValue = defaultValue ; if ( defaultValue != 0 ) { for ( int [ ] chunk : chunks ) { Arrays . fill ( chunk , defaultValue ) ; } } return this ; }
call directly after construction todo move to constructor or static factory
34,127
void set ( int index , int value ) { int chunk = assertSpace ( index ) ; chunks [ chunk ] [ index & mask ] = value ; }
Sets a value an grows chunks dynamically if exceeding size or missing chunk encountered
34,128
private int [ ] newChunk ( ) { if ( defaultValue == 0 ) return new int [ chunkSize ] ; if ( baseChunk == null ) { baseChunk = new int [ chunkSize ] ; Arrays . fill ( baseChunk , defaultValue ) ; } return baseChunk . clone ( ) ; }
todo use pool
34,129
public void sumUp ( ) { int offset = 0 ; int tmp = 0 ; for ( int i = 0 ; i < numChunks ; i ++ ) { int [ ] chunk = chunks [ i ] ; if ( chunk == null ) throw new IllegalStateException ( "Chunks are not continous, null fragement at offset " + i ) ; for ( int j = 0 ; j < chunkSize ; j ++ ) { tmp = chunk [ j ] ; chunk [ j ] = offset ; offset += tmp ; } } }
special operation implemented inline to compute and store sum up until here
34,130
public void add ( Chunks c ) { assert c . chunkBits == chunkBits ; assert c . defaultValue == defaultValue ; int [ ] [ ] oChunks = c . chunks ; if ( c . numChunks > numChunks ) growTo ( c . numChunks - 1 ) ; for ( int i = 0 ; i < oChunks . length ; i ++ ) { int [ ] oChunk = oChunks [ i ] ; if ( oChunk != null ) { if ( chunks [ i ] == null ) { chunks [ i ] = oChunk . clone ( ) ; } else { int [ ] chunk = chunks [ i ] ; for ( int j = 0 ; j < oChunk . length ; j ++ ) { chunk [ j ] += oChunk [ j ] ; } } } } this . maxIndex = Math . max ( this . maxIndex , c . maxIndex ) ; }
adds values from another Chunks to the current one missing chunks are cloned over
34,131
public int [ ] mergeAllChunks ( ) { int [ ] merged = new int [ chunkSize * numChunks ] ; int filledChunks = Math . min ( numChunks , getFilledChunks ( ) + 1 ) ; for ( int i = 0 ; i < filledChunks ; i ++ ) { if ( chunks [ i ] != null ) { System . arraycopy ( chunks [ i ] , 0 , merged , i * chunkSize , chunkSize ) ; } } if ( defaultValue != 0 ) Arrays . fill ( merged , size ( ) , merged . length , defaultValue ) ; return merged ; }
turn this chunked array into a regular int - array mostly for compatibility also copying unused space at the end filled with default value
34,132
public int [ ] mergeChunks ( ) { int filledChunks = getFilledChunks ( ) ; int [ ] merged = new int [ size ( ) ] ; for ( int i = 0 ; i < filledChunks ; i ++ ) { if ( chunks [ i ] != null ) { System . arraycopy ( chunks [ i ] , 0 , merged , i * chunkSize , chunkSize ) ; } } int remainder = size ( ) % chunkSize ; if ( remainder != 0 && chunks [ filledChunks ] != null ) { System . arraycopy ( chunks [ filledChunks ] , 0 , merged , ( filledChunks ) * chunkSize , remainder ) ; } return merged ; }
turn this chunked array into a regular int - array mostly for compatibility cuts off unused space at the end
34,133
public int randomIndexChoice ( List < Integer > weights ) { int result = 0 , index ; double maxKey = 0.0 ; double u , key ; int weight ; for ( ListIterator < Integer > it = weights . listIterator ( ) ; it . hasNext ( ) ; ) { index = it . nextIndex ( ) ; weight = it . next ( ) ; u = random . nextDouble ( ) ; key = Math . pow ( u , ( 1.0 / weight ) ) ; if ( key > maxKey ) { maxKey = key ; result = index ; } } return result ; }
Returns an integer at random weighted according to its index
34,134
public static Stream < Relationship > coverNodes ( Collection < Node > nodes ) { return nodes . stream ( ) . flatMap ( n -> StreamSupport . stream ( n . getRelationships ( Direction . OUTGOING ) . spliterator ( ) , false ) . filter ( r -> nodes . contains ( r . getEndNode ( ) ) ) ) ; }
non - parallelized utility method for use by other procedures
34,135
private synchronized Map < String , Map < String , Collection < Index < Node > > > > initIndexConfiguration ( ) { Map < String , Map < String , Collection < Index < Node > > > > indexesByLabelAndProperty = new HashMap < > ( ) ; try ( Transaction tx = graphDatabaseService . beginTx ( ) ) { final IndexManager indexManager = graphDatabaseService . index ( ) ; for ( String indexName : indexManager . nodeIndexNames ( ) ) { final Index < Node > index = indexManager . forNodes ( indexName ) ; Map < String , String > indexConfig = indexManager . getConfiguration ( index ) ; if ( Util . toBoolean ( indexConfig . get ( "autoUpdate" ) ) ) { String labels = indexConfig . getOrDefault ( "labels" , "" ) ; for ( String label : labels . split ( ":" ) ) { Map < String , Collection < Index < Node > > > propertyKeyToIndexMap = indexesByLabelAndProperty . computeIfAbsent ( label , s -> new HashMap < > ( ) ) ; String [ ] keysForLabel = indexConfig . getOrDefault ( "keysForLabel:" + label , "" ) . split ( ":" ) ; for ( String property : keysForLabel ) { propertyKeyToIndexMap . computeIfAbsent ( property , s -> new ArrayList < > ( ) ) . add ( index ) ; } } } } tx . success ( ) ; } return indexesByLabelAndProperty ; }
might be run from a scheduler so we need to make sure we have a transaction
34,136
public synchronized void forceTxRollover ( ) { if ( async ) { try { forceTxRolloverFlag = false ; indexCommandQueue . put ( FORCE_TX_ROLLOVER ) ; while ( ! forceTxRolloverFlag ) { Thread . sleep ( 5 ) ; } } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } }
to be used from unit tests to ensure a tx rollover has happenend
34,137
@ Procedure ( mode = Mode . WRITE ) @ Description ( "apoc.periodic.iterate('statement returning items', 'statement per item', {batchSize:1000,iterateList:true,parallel:false,params:{},concurrency:50,retries:0}) YIELD batches, total - run the second statement for each item returned by the first statement. Returns number of batches and total processed rows" ) public Stream < BatchAndTotalResult > iterate ( @ Name ( "cypherIterate" ) String cypherIterate , @ Name ( "cypherAction" ) String cypherAction , @ Name ( "config" ) Map < String , Object > config ) { long batchSize = Util . toLong ( config . getOrDefault ( "batchSize" , 10000 ) ) ; int concurrency = Util . toInteger ( config . getOrDefault ( "concurrency" , 50 ) ) ; boolean parallel = Util . toBoolean ( config . getOrDefault ( "parallel" , false ) ) ; boolean iterateList = Util . toBoolean ( config . getOrDefault ( "iterateList" , true ) ) ; long retries = Util . toLong ( config . getOrDefault ( "retries" , 0 ) ) ; Map < String , Object > params = ( Map ) config . getOrDefault ( "params" , Collections . emptyMap ( ) ) ; int failedParams = Util . toInteger ( config . getOrDefault ( "failedParams" , - 1 ) ) ; try ( Result result = db . execute ( slottedRuntime ( cypherIterate ) , params ) ) { Pair < String , Boolean > prepared = prepareInnerStatement ( cypherAction , iterateList , result . columns ( ) , "_batch" ) ; String innerStatement = prepared . first ( ) ; iterateList = prepared . other ( ) ; log . info ( "starting batching from `%s` operation using iteration `%s` in separate thread" , cypherIterate , cypherAction ) ; return iterateAndExecuteBatchedInSeparateThread ( ( int ) batchSize , parallel , iterateList , retries , result , ( p ) -> db . execute ( innerStatement , merge ( params , p ) ) . close ( ) , concurrency , failedParams ) ; } }
invoke cypherAction in batched transactions being feeded from cypherIteration running in main thread
34,138
private Map < String , Object > documentToPackableMap ( Map < String , Object > document ) { if ( compatibleValues ) { try { return jsonMapper . readValue ( jsonMapper . writeValueAsBytes ( document ) , new TypeReference < Map < String , Object > > ( ) { } ) ; } catch ( Exception e ) { throw new RuntimeException ( "Cannot convert document to json and back to Map " + e . getMessage ( ) ) ; } } if ( document != null ) { Object objectId = document . get ( "_id" ) ; if ( objectId != null ) { document . put ( "_id" , objectId . toString ( ) ) ; } } return document ; }
It translates a MongoDB document into a Map where the _id field is not an ObjectId but a simple String representation of it
34,139
protected String getQueryUrl ( String hostOrKey , String index , String type , String id , Object query ) { return getElasticSearchUrl ( hostOrKey ) + formatQueryUrl ( index , type , id , query ) ; }
Get the full Elasticsearch url
34,140
private int getDegreeSafe ( Node node , RelationshipType relType , Direction direction ) { if ( relType == null ) { return node . getDegree ( direction ) ; } return node . getDegree ( relType , direction ) ; }
works in cases when relType is null
34,141
static String sanitizeJavadoc ( String documentation ) { documentation = documentation . replaceAll ( "[^\\S\n]+\n" , "\n" ) ; documentation = documentation . replaceAll ( "\\s+$" , "" ) ; documentation = documentation . replaceAll ( "\\*/" , "&#42;/" ) ; documentation = documentation . replaceAll ( "@see (http:" + URL_CHARS + "+)" , "@see <a href=\"$1\">$1</a>" ) ; return documentation ; }
A grab - bag of fixes for things that can go wrong when converting to javadoc .
34,142
@ SuppressWarnings ( "unchecked" ) private Object union ( Linker linker , Object a , Object b ) { if ( a instanceof List ) { return union ( ( List < ? > ) a , ( List < ? > ) b ) ; } else if ( a instanceof Map ) { return union ( linker , ( Map < ProtoMember , Object > ) a , ( Map < ProtoMember , Object > ) b ) ; } else { linker . addError ( "conflicting options: %s, %s" , a , b ) ; return a ; } }
Combine values for the same key resolving conflicts based on their type .
34,143
private ProtoFile loadDescriptorProto ( ) throws IOException { InputStream resourceAsStream = SchemaLoader . class . getResourceAsStream ( "/" + DESCRIPTOR_PROTO ) ; try ( BufferedSource buffer = Okio . buffer ( Okio . source ( resourceAsStream ) ) ) { String data = buffer . readUtf8 ( ) ; Location location = Location . get ( "" , DESCRIPTOR_PROTO ) ; ProtoFileElement element = ProtoParser . parse ( location , data ) ; return ProtoFile . get ( element ) ; } }
Returns Google s protobuf descriptor which defines standard options like default deprecated and java_package . If the user has provided their own version of the descriptor proto that is preferred .
34,144
public String readString ( ) { skipWhitespace ( true ) ; char c = peekChar ( ) ; return c == '"' || c == '\'' ? readQuotedString ( ) : readWord ( ) ; }
Reads a quoted or unquoted string and returns it .
34,145
public String readWord ( ) { skipWhitespace ( true ) ; int start = pos ; while ( pos < data . length ) { char c = data [ pos ] ; if ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || ( c >= '0' && c <= '9' ) || ( c == '_' ) || ( c == '-' ) || ( c == '.' ) ) { pos ++ ; } else { break ; } } if ( start == pos ) { throw unexpected ( "expected a word" ) ; } return new String ( data , start , pos - start ) ; }
Reads a non - empty word and returns it .
34,146
private String readComment ( ) { if ( pos == data . length || data [ pos ] != '/' ) throw new AssertionError ( ) ; pos ++ ; int commentType = pos < data . length ? data [ pos ++ ] : - 1 ; if ( commentType == '*' ) { StringBuilder result = new StringBuilder ( ) ; boolean startOfLine = true ; for ( ; pos + 1 < data . length ; pos ++ ) { char c = data [ pos ] ; if ( c == '*' && data [ pos + 1 ] == '/' ) { pos += 2 ; return result . toString ( ) . trim ( ) ; } if ( c == '\n' ) { result . append ( '\n' ) ; newline ( ) ; startOfLine = true ; } else if ( ! startOfLine ) { result . append ( c ) ; } else if ( c == '*' ) { if ( data [ pos + 1 ] == ' ' ) { pos += 1 ; } startOfLine = false ; } else if ( ! Character . isWhitespace ( c ) ) { result . append ( c ) ; startOfLine = false ; } } throw unexpected ( "unterminated comment" ) ; } else if ( commentType == '/' ) { if ( pos < data . length && data [ pos ] == ' ' ) { pos += 1 ; } int start = pos ; while ( pos < data . length ) { char c = data [ pos ++ ] ; if ( c == '\n' ) { newline ( ) ; break ; } } return new String ( data , start , pos - 1 - start ) ; } else { throw unexpected ( "unexpected '/'" ) ; } }
Reads a comment and returns its body .
34,147
private String stripDefault ( List < OptionElement > options ) { String result = null ; for ( Iterator < OptionElement > i = options . iterator ( ) ; i . hasNext ( ) ; ) { OptionElement option = i . next ( ) ; if ( option . getName ( ) . equals ( "default" ) ) { i . remove ( ) ; result = String . valueOf ( option . getValue ( ) ) ; } } return result ; }
Defaults aren t options . This finds an option named default removes and returns it . Returns null if no default option is present .
34,148
private ReservedElement readReserved ( Location location , String documentation ) { ImmutableList . Builder < Object > valuesBuilder = ImmutableList . builder ( ) ; while ( true ) { char c = reader . peekChar ( ) ; if ( c == '"' || c == '\'' ) { valuesBuilder . add ( reader . readQuotedString ( ) ) ; } else { int tagStart = reader . readInt ( ) ; c = reader . peekChar ( ) ; if ( c != ',' && c != ';' ) { if ( ! reader . readWord ( ) . equals ( "to" ) ) { throw reader . unexpected ( "expected ',', ';', or 'to'" ) ; } int tagEnd = reader . readInt ( ) ; valuesBuilder . add ( Range . closed ( tagStart , tagEnd ) ) ; } else { valuesBuilder . add ( tagStart ) ; } } c = reader . readChar ( ) ; if ( c == ';' ) break ; if ( c != ',' ) throw reader . unexpected ( "expected ',' or ';'" ) ; } ImmutableList < Object > values = valuesBuilder . build ( ) ; if ( values . isEmpty ( ) ) { throw reader . unexpected ( "'reserved' must have at least one field name or tag" ) ; } return new ReservedElement ( location , documentation , values ) ; }
Reads a reserved tags and names list like reserved 10 12 to 14 foo ; .
34,149
private EnumConstantElement readEnumConstant ( String documentation , Location location , String label ) { reader . require ( '=' ) ; int tag = reader . readInt ( ) ; List < OptionElement > options = new OptionReader ( reader ) . readOptions ( ) ; reader . require ( ';' ) ; documentation = reader . tryAppendTrailingDocumentation ( documentation ) ; return new EnumConstantElement ( location , label , tag , documentation , options ) ; }
Reads an enum constant like ROCK = 0 ; . The label is the constant name .
34,150
Multimap < Path , String > pathsToAttempt ( Set < Location > protoLocations ) { Multimap < Path , String > result = MultimapBuilder . linkedHashKeys ( ) . linkedHashSetValues ( ) . build ( ) ; for ( Location location : protoLocations ) { pathsToAttempt ( result , location ) ; } return result ; }
Returns a multimap whose keys are base directories and whose values are potential locations of wire profile files .
34,151
boolean mark ( ProtoType type ) { if ( type == null ) throw new NullPointerException ( "type == null" ) ; if ( identifierSet . excludes ( type ) ) return false ; return types . add ( type ) ; }
Marks a type as transitively reachable by the includes set . Returns true if the mark is new the type will be retained and its own dependencies should be traversed .
34,152
boolean mark ( ProtoMember protoMember ) { if ( protoMember == null ) throw new NullPointerException ( "type == null" ) ; if ( identifierSet . excludes ( protoMember ) ) return false ; return members . containsKey ( protoMember . type ( ) ) ? members . put ( protoMember . type ( ) , protoMember ) : types . add ( protoMember . type ( ) ) ; }
Marks a member as transitively reachable by the includes set . Returns true if the mark is new the member will be retained and its own dependencies should be traversed .
34,153
public String enclosingTypeOrPackage ( ) { int dot = string . lastIndexOf ( '.' ) ; return dot == - 1 ? null : string . substring ( 0 , dot ) ; }
Returns the enclosing type or null if this type is not nested in another type .
34,154
String packageName ( ) { for ( Object context : contextStack ) { if ( context instanceof ProtoFile ) return ( ( ProtoFile ) context ) . packageName ( ) ; } return null ; }
Returns the current package name from the context stack .
34,155
public static XWPFTemplate compile ( InputStream inputStream , Configure config ) { try { XWPFTemplate instance = new XWPFTemplate ( ) ; instance . config = config ; instance . doc = new NiceXWPFDocument ( inputStream ) ; instance . visitor = new TemplateVisitor ( instance . config ) ; instance . eleTemplates = instance . visitor . visitDocument ( instance . doc ) ; return instance ; } catch ( IOException e ) { logger . error ( "Compile template failed" , e ) ; throw new ResolverException ( "Compile template failed" ) ; } }
template file as InputStream
34,156
private boolean isInvalidEncodedPath ( String path ) { if ( path . contains ( "%" ) ) { try { String decodedPath = URLDecoder . decode ( path , "UTF-8" ) ; if ( isInvalidPath ( decodedPath ) ) { return true ; } decodedPath = processPath ( decodedPath ) ; if ( isInvalidPath ( decodedPath ) ) { return true ; } } catch ( IllegalArgumentException | UnsupportedEncodingException ex ) { } } return false ; }
Check whether the given path contains invalid escape sequences .
34,157
public CredentialsProvider createFor ( String uri , String username , String password , String passphrase ) { return createFor ( uri , username , password , passphrase , false ) ; }
Search for a credential provider that will handle the specified URI . If not found and the username or passphrase has text then create a default using the provided username and password or passphrase . Otherwise null .
34,158
public CredentialsProvider createFor ( String uri , String username , String password , String passphrase , boolean skipSslValidation ) { CredentialsProvider provider = null ; if ( awsAvailable ( ) && AwsCodeCommitCredentialProvider . canHandle ( uri ) ) { this . logger . debug ( "Constructing AwsCodeCommitCredentialProvider for URI " + uri ) ; AwsCodeCommitCredentialProvider aws = new AwsCodeCommitCredentialProvider ( ) ; aws . setUsername ( username ) ; aws . setPassword ( password ) ; provider = aws ; } else if ( hasText ( username ) ) { this . logger . debug ( "Constructing UsernamePasswordCredentialsProvider for URI " + uri ) ; provider = new UsernamePasswordCredentialsProvider ( username , password . toCharArray ( ) ) ; } else if ( hasText ( passphrase ) ) { this . logger . debug ( "Constructing PassphraseCredentialsProvider for URI " + uri ) ; provider = new PassphraseCredentialsProvider ( passphrase ) ; } if ( skipSslValidation && GitSkipSslValidationCredentialsProvider . canHandle ( uri ) ) { this . logger . debug ( "Constructing GitSkipSslValidationCredentialsProvider for URI " + uri ) ; provider = new GitSkipSslValidationCredentialsProvider ( provider ) ; } if ( provider == null ) { this . logger . debug ( "No credentials provider required for URI " + uri ) ; } return provider ; }
Search for a credential provider that will handle the specified URI . If not found and the username or passphrase has text then create a default using the provided username and password or passphrase .
34,159
public String refresh ( String label ) { Git git = null ; try { git = createGitClient ( ) ; if ( shouldPull ( git ) ) { FetchResult fetchStatus = fetch ( git , label ) ; if ( this . deleteUntrackedBranches && fetchStatus != null ) { deleteUntrackedLocalBranches ( fetchStatus . getTrackingRefUpdates ( ) , git ) ; } checkout ( git , label ) ; tryMerge ( git , label ) ; } else { checkout ( git , label ) ; tryMerge ( git , label ) ; } return git . getRepository ( ) . findRef ( "HEAD" ) . getObjectId ( ) . getName ( ) ; } catch ( RefNotFoundException e ) { throw new NoSuchLabelException ( "No such label: " + label , e ) ; } catch ( NoRemoteRepositoryException e ) { throw new NoSuchRepositoryException ( "No such repository: " + getUri ( ) , e ) ; } catch ( GitAPIException e ) { throw new NoSuchRepositoryException ( "Cannot clone or checkout repository: " + getUri ( ) , e ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Cannot load environment" , e ) ; } finally { try { if ( git != null ) { git . close ( ) ; } } catch ( Exception e ) { this . logger . warn ( "Could not close git repository" , e ) ; } } }
Get the working directory ready .
34,160
private void initClonedRepository ( ) throws GitAPIException , IOException { if ( ! getUri ( ) . startsWith ( FILE_URI_PREFIX ) ) { deleteBaseDirIfExists ( ) ; Git git = cloneToBasedir ( ) ; if ( git != null ) { git . close ( ) ; } git = openGitRepository ( ) ; if ( git != null ) { git . close ( ) ; } } }
Clones the remote repository and then opens a connection to it .
34,161
private Collection < String > deleteUntrackedLocalBranches ( Collection < TrackingRefUpdate > trackingRefUpdates , Git git ) { if ( CollectionUtils . isEmpty ( trackingRefUpdates ) ) { return Collections . emptyList ( ) ; } Collection < String > branchesToDelete = new ArrayList < > ( ) ; for ( TrackingRefUpdate trackingRefUpdate : trackingRefUpdates ) { ReceiveCommand receiveCommand = trackingRefUpdate . asReceiveCommand ( ) ; if ( receiveCommand . getType ( ) == DELETE ) { String localRefName = trackingRefUpdate . getLocalName ( ) ; if ( StringUtils . startsWithIgnoreCase ( localRefName , LOCAL_BRANCH_REF_PREFIX ) ) { String localBranchName = localRefName . substring ( LOCAL_BRANCH_REF_PREFIX . length ( ) , localRefName . length ( ) ) ; branchesToDelete . add ( localBranchName ) ; } } } if ( CollectionUtils . isEmpty ( branchesToDelete ) ) { return Collections . emptyList ( ) ; } try { checkout ( git , this . defaultLabel ) ; return deleteBranches ( git , branchesToDelete ) ; } catch ( Exception ex ) { String message = format ( "Failed to delete %s branches." , branchesToDelete ) ; warn ( message , ex ) ; return Collections . emptyList ( ) ; } }
Deletes local branches if corresponding remote branch was removed .
34,162
private synchronized Git copyRepository ( ) throws IOException , GitAPIException { deleteBaseDirIfExists ( ) ; getBasedir ( ) . mkdirs ( ) ; Assert . state ( getBasedir ( ) . exists ( ) , "Could not create basedir: " + getBasedir ( ) ) ; if ( getUri ( ) . startsWith ( FILE_URI_PREFIX ) ) { return copyFromLocalRepository ( ) ; } else { return cloneToBasedir ( ) ; } }
request ) .
34,163
private static byte [ ] canonicalRequestDigest ( URIish uri ) throws NoSuchAlgorithmException { StringBuilder canonicalRequest = new StringBuilder ( ) ; canonicalRequest . append ( "GIT\n" ) . append ( uri . getPath ( ) ) . append ( "\n" ) . append ( "\n" ) . append ( "host:" ) . append ( uri . getHost ( ) ) . append ( "\n" ) . append ( "\n" ) . append ( "host\n" ) ; MessageDigest digest = MessageDigest . getInstance ( SHA_256 ) ; return digest . digest ( canonicalRequest . toString ( ) . getBytes ( ) ) ; }
Creates a message digest .
34,164
public boolean get ( URIish uri , CredentialItem ... items ) throws UnsupportedCredentialItem { String codeCommitPassword ; String awsAccessKey ; String awsSecretKey ; try { AWSCredentials awsCredentials = retrieveAwsCredentials ( ) ; StringBuilder awsKey = new StringBuilder ( ) ; awsKey . append ( awsCredentials . getAWSAccessKeyId ( ) ) ; awsSecretKey = awsCredentials . getAWSSecretKey ( ) ; if ( awsCredentials instanceof AWSSessionCredentials ) { AWSSessionCredentials sessionCreds = ( AWSSessionCredentials ) awsCredentials ; if ( sessionCreds . getSessionToken ( ) != null ) { awsKey . append ( '%' ) . append ( sessionCreds . getSessionToken ( ) ) ; } } awsAccessKey = awsKey . toString ( ) ; } catch ( Throwable t ) { this . logger . warn ( "Unable to retrieve AWS Credentials" , t ) ; return false ; } try { codeCommitPassword = calculateCodeCommitPassword ( uri , awsSecretKey ) ; } catch ( Throwable t ) { this . logger . warn ( "Error calculating the AWS CodeCommit password" , t ) ; return false ; } for ( CredentialItem i : items ) { if ( i instanceof CredentialItem . Username ) { ( ( CredentialItem . Username ) i ) . setValue ( awsAccessKey ) ; this . logger . trace ( "Returning username " + awsAccessKey ) ; continue ; } if ( i instanceof CredentialItem . Password ) { ( ( CredentialItem . Password ) i ) . setValue ( codeCommitPassword . toCharArray ( ) ) ; this . logger . trace ( "Returning password " + codeCommitPassword ) ; continue ; } if ( i instanceof CredentialItem . StringType && i . getPromptText ( ) . equals ( "Password: " ) ) { ( ( CredentialItem . StringType ) i ) . setValue ( codeCommitPassword ) ; this . logger . trace ( "Returning password string " + codeCommitPassword ) ; continue ; } throw new UnsupportedCredentialItem ( uri , i . getClass ( ) . getName ( ) + ":" + i . getPromptText ( ) ) ; } return true ; }
Get the username and password to use for the given uri .
34,165
public boolean get ( URIish uri , CredentialItem ... items ) throws UnsupportedCredentialItem { for ( final CredentialItem item : items ) { if ( item instanceof CredentialItem . StringType && item . getPromptText ( ) . startsWith ( PROMPT ) ) { ( ( CredentialItem . StringType ) item ) . setValue ( this . passphrase ) ; continue ; } throw new UnsupportedCredentialItem ( uri , item . getClass ( ) . getName ( ) + ":" + item . getPromptText ( ) ) ; } return true ; }
Ask for the credential items to be populated with the passphrase .
34,166
boolean isGuarded ( T resource ) { if ( guarded . contains ( resource ) ) { return true ; } Context context = contextStack . peek ( ) ; if ( ! context . safe ) { return false ; } while ( context != null && context . conditional != null ) { registeredGuards . put ( context . conditional , resource ) ; context = context . linked ; } return true ; }
Determines if the given resource is guarded either intrinsically or conditionally . If the former any ancestor conditional nodes are registered as feature - testing the resource .
34,167
private void prioritizeFromEntryNode ( DiGraphNode < Node , Branch > entry ) { PriorityQueue < DiGraphNode < Node , Branch > > worklist = new PriorityQueue < > ( 10 , priorityComparator ) ; worklist . add ( entry ) ; while ( ! worklist . isEmpty ( ) ) { DiGraphNode < Node , Branch > current = worklist . remove ( ) ; if ( nodePriorities . containsKey ( current ) ) { continue ; } nodePriorities . put ( current , ++ priorityCounter ) ; List < DiGraphNode < Node , Branch > > successors = cfg . getDirectedSuccNodes ( current ) ; worklist . addAll ( successors ) ; } }
Given an entry node find all the nodes reachable from that node and prioritize them .
34,168
static Node computeFallThrough ( Node n ) { switch ( n . getToken ( ) ) { case DO : case FOR : return computeFallThrough ( n . getFirstChild ( ) ) ; case FOR_IN : case FOR_OF : case FOR_AWAIT_OF : return n . getSecondChild ( ) ; case LABEL : return computeFallThrough ( n . getLastChild ( ) ) ; default : return n ; } }
Computes the destination node of n when we want to fallthrough into the subtree of n . We don t always create a CFG edge into n itself because of DOs and FORs .
34,169
private void createEdge ( Node fromNode , ControlFlowGraph . Branch branch , Node toNode ) { cfg . createNode ( fromNode ) ; cfg . createNode ( toNode ) ; cfg . connectIfNotFound ( fromNode , branch , toNode ) ; }
Connects the two nodes in the control flow graph .
34,170
private void connectToPossibleExceptionHandler ( Node cfgNode , Node target ) { if ( mayThrowException ( target ) && ! exceptionHandler . isEmpty ( ) ) { Node lastJump = cfgNode ; for ( Node handler : exceptionHandler ) { if ( handler . isFunction ( ) ) { return ; } checkState ( handler . isTry ( ) ) ; Node catchBlock = NodeUtil . getCatchBlock ( handler ) ; boolean lastJumpInCatchBlock = false ; for ( Node ancestor : lastJump . getAncestors ( ) ) { if ( ancestor == handler ) { break ; } else if ( ancestor == catchBlock ) { lastJumpInCatchBlock = true ; break ; } } if ( ! NodeUtil . hasCatchHandler ( catchBlock ) || lastJumpInCatchBlock ) { if ( lastJump == cfgNode ) { createEdge ( cfgNode , Branch . ON_EX , handler . getLastChild ( ) ) ; } else { finallyMap . put ( lastJump , handler . getLastChild ( ) ) ; } } else { if ( lastJump == cfgNode ) { createEdge ( cfgNode , Branch . ON_EX , catchBlock ) ; return ; } else { finallyMap . put ( lastJump , catchBlock ) ; } } lastJump = handler ; } } }
Connects cfgNode to the proper CATCH block if target subtree might throw an exception . If there are FINALLY blocks reached before a CATCH it will make the corresponding entry in finallyMap .
34,171
public static boolean isBreakTarget ( Node target , String label ) { return isBreakStructure ( target , label != null ) && matchLabel ( target . getParent ( ) , label ) ; }
Checks if target is actually the break target of labeled continue . The label can be null if it is an unlabeled break .
34,172
static boolean isContinueTarget ( Node target , String label ) { return NodeUtil . isLoopStructure ( target ) && matchLabel ( target . getParent ( ) , label ) ; }
Checks if target is actually the continue target of labeled continue . The label can be null if it is an unlabeled continue .
34,173
private static boolean matchLabel ( Node target , String label ) { if ( label == null ) { return true ; } while ( target . isLabel ( ) ) { if ( target . getFirstChild ( ) . getString ( ) . equals ( label ) ) { return true ; } target = target . getParent ( ) ; } return false ; }
Check if label is actually referencing the target control structure . If label is null it always returns true .
34,174
public static boolean mayThrowException ( Node n ) { switch ( n . getToken ( ) ) { case CALL : case TAGGED_TEMPLATELIT : case GETPROP : case GETELEM : case THROW : case NEW : case ASSIGN : case INC : case DEC : case INSTANCEOF : case IN : case YIELD : case AWAIT : return true ; case FUNCTION : return false ; default : break ; } for ( Node c = n . getFirstChild ( ) ; c != null ; c = c . getNext ( ) ) { if ( ! ControlFlowGraph . isEnteringNewCfgNode ( c ) && mayThrowException ( c ) ) { return true ; } } return false ; }
Determines if the subtree might throw an exception .
34,175
static boolean isBreakStructure ( Node n , boolean labeled ) { switch ( n . getToken ( ) ) { case FOR : case FOR_IN : case FOR_OF : case FOR_AWAIT_OF : case DO : case WHILE : case SWITCH : return true ; case BLOCK : case ROOT : case IF : case TRY : return labeled ; default : return false ; } }
Determines whether the given node can be terminated with a BREAK node .
34,176
static Node getExceptionHandler ( Node n ) { for ( Node cur = n ; ! cur . isScript ( ) && ! cur . isFunction ( ) ; cur = cur . getParent ( ) ) { Node catchNode = getCatchHandlerForBlock ( cur ) ; if ( catchNode != null ) { return catchNode ; } } return null ; }
Get the TRY block with a CATCH that would be run if n throws an exception .
34,177
static Node getCatchHandlerForBlock ( Node block ) { if ( block . isBlock ( ) && block . getParent ( ) . isTry ( ) && block . getParent ( ) . getFirstChild ( ) == block ) { for ( Node s = block . getNext ( ) ; s != null ; s = s . getNext ( ) ) { if ( NodeUtil . hasCatchHandler ( s ) ) { return s . getFirstChild ( ) ; } } } return null ; }
Locate the catch BLOCK given the first block in a TRY .
34,178
public void visit ( NodeTraversal traversal , Node node , Node parent ) { if ( node . isScript ( ) ) { String fileName = getFileName ( traversal ) ; if ( instrumentationData . get ( fileName ) != null ) { if ( node . hasChildren ( ) && node . getFirstChild ( ) . isModuleBody ( ) ) { node = node . getFirstChild ( ) ; } node . addChildrenToFront ( newHeaderNode ( traversal , node ) . removeChildren ( ) ) ; } traversal . reportCodeChange ( ) ; return ; } if ( reach == CoverageReach . CONDITIONAL && parent != null && parent . isScript ( ) ) { return ; } if ( node . isFunction ( ) && ! NodeUtil . getFunctionBody ( node ) . isBlock ( ) ) { Node returnValue = NodeUtil . getFunctionBody ( node ) ; Node body = IR . block ( IR . returnNode ( returnValue . detach ( ) ) ) ; body . useSourceInfoIfMissingFromForTree ( returnValue ) ; node . addChildToBack ( body ) ; } if ( node . isFunction ( ) || node . isWith ( ) || node . isCase ( ) || node . isDefaultCase ( ) || node . isCatch ( ) ) { Node codeBlock = node . getLastChild ( ) ; codeBlock . addChildToFront ( newInstrumentationNode ( traversal , node ) ) ; traversal . reportCodeChange ( ) ; return ; } if ( node . isTry ( ) ) { Node firstChild = node . getFirstChild ( ) ; firstChild . addChildToFront ( newInstrumentationNode ( traversal , node ) ) ; traversal . reportCodeChange ( ) ; return ; } if ( parent != null && NodeUtil . isStatementBlock ( parent ) && ! node . isModuleBody ( ) ) { parent . addChildBefore ( newInstrumentationNode ( traversal , node ) , node ) ; traversal . reportCodeChange ( ) ; return ; } }
Instruments the JS code by inserting appropriate nodes into the AST . The instrumentation logic is tuned to collect line coverage data only .
34,179
private void normalizeNodeTypes ( Node n ) { normalizeBlocks ( n ) ; for ( Node child = n . getFirstChild ( ) ; child != null ; child = child . getNext ( ) ) { checkState ( child . getParent ( ) == n ) ; normalizeNodeTypes ( child ) ; } }
Covert EXPR_VOID to EXPR_RESULT to simplify the rest of the code .
34,180
private void normalizeBlocks ( Node n ) { if ( NodeUtil . isControlStructure ( n ) && ! n . isLabel ( ) && ! n . isSwitch ( ) ) { for ( Node c = n . getFirstChild ( ) ; c != null ; c = c . getNext ( ) ) { if ( NodeUtil . isControlStructureCodeBlock ( n , c ) && ! c . isBlock ( ) ) { Node newBlock = IR . block ( ) . srcref ( n ) ; n . replaceChild ( c , newBlock ) ; newBlock . setIsAddedBlock ( true ) ; if ( ! c . isEmpty ( ) ) { newBlock . addChildrenToFront ( c ) ; } c = newBlock ; reportChange ( ) ; } } } }
Add blocks to IF WHILE DO etc .
34,181
private boolean isInterface ( Node n ) { if ( ! n . isFunction ( ) ) { return false ; } JSDocInfo jsDoc = NodeUtil . getBestJSDocInfo ( n ) ; return jsDoc != null && jsDoc . isInterface ( ) ; }
Whether a function is an interface constructor or a method on an interface .
34,182
private void pullDestructuringOutOfParams ( Node paramList , Node function ) { Node insertSpot = null ; Node body = function . getLastChild ( ) ; int i = 0 ; Node next = null ; for ( Node param = paramList . getFirstChild ( ) ; param != null ; param = next , i ++ ) { next = param . getNext ( ) ; if ( param . isDefaultValue ( ) ) { Node nameOrPattern = param . removeFirstChild ( ) ; JSDocInfo jsDoc = nameOrPattern . getJSDocInfo ( ) ; nameOrPattern . setJSDocInfo ( null ) ; Node defaultValue = param . removeFirstChild ( ) ; Node newParam ; boolean isNoop = false ; if ( ! nameOrPattern . isName ( ) ) { } else if ( defaultValue . isName ( ) ) { isNoop = "undefined" . equals ( defaultValue . getString ( ) ) ; } else if ( defaultValue . isVoid ( ) ) { isNoop = NodeUtil . isImmutableValue ( defaultValue . getFirstChild ( ) ) ; } if ( isNoop ) { newParam = nameOrPattern . cloneTree ( ) ; } else { newParam = nameOrPattern . isName ( ) ? nameOrPattern : astFactory . createName ( getTempVariableName ( ) , nameOrPattern . getJSType ( ) ) ; Node lhs = nameOrPattern . cloneTree ( ) ; Node rhs = defaultValueHook ( newParam . cloneTree ( ) , defaultValue ) ; Node newStatement = nameOrPattern . isName ( ) ? IR . exprResult ( astFactory . createAssign ( lhs , rhs ) ) : IR . var ( lhs , rhs ) ; newStatement . useSourceInfoIfMissingFromForTree ( param ) ; body . addChildAfter ( newStatement , insertSpot ) ; insertSpot = newStatement ; } paramList . replaceChild ( param , newParam ) ; newParam . setOptionalArg ( true ) ; newParam . setJSDocInfo ( jsDoc ) ; compiler . reportChangeToChangeScope ( function ) ; } else if ( param . isDestructuringPattern ( ) ) { insertSpot = replacePatternParamWithTempVar ( function , insertSpot , param , getTempVariableName ( ) ) ; compiler . reportChangeToChangeScope ( function ) ; } else if ( param . isRest ( ) && param . getFirstChild ( ) . isDestructuringPattern ( ) ) { insertSpot = replacePatternParamWithTempVar ( function , insertSpot , param . getFirstChild ( ) , getTempVariableName ( ) ) ; compiler . reportChangeToChangeScope ( function ) ; } } }
the parameter list contains a usage of OBJECT_REST .
34,183
private Node replacePatternParamWithTempVar ( Node function , Node insertSpot , Node patternParam , String tempVarName ) { JSType paramType = patternParam . getJSType ( ) ; Node newParam = astFactory . createName ( tempVarName , paramType ) ; newParam . setJSDocInfo ( patternParam . getJSDocInfo ( ) ) ; patternParam . replaceWith ( newParam ) ; Node newDecl = IR . var ( patternParam , astFactory . createName ( tempVarName , paramType ) ) ; function . getLastChild ( ) . addChildAfter ( newDecl , insertSpot ) ; return newDecl ; }
Replace a destructuring pattern parameter with a a temporary parameter name and add a new local variable declaration to the function assigning the temporary parameter to the pattern .
34,184
private void replacePattern ( NodeTraversal t , Node pattern , Node rhs , Node parent , Node nodeToDetach ) { checkArgument ( NodeUtil . isStatement ( nodeToDetach ) , nodeToDetach ) ; switch ( pattern . getToken ( ) ) { case ARRAY_PATTERN : replaceArrayPattern ( t , pattern , rhs , parent , nodeToDetach ) ; break ; case OBJECT_PATTERN : replaceObjectPattern ( t , pattern , rhs , parent , nodeToDetach ) ; break ; default : throw new IllegalStateException ( "unexpected" ) ; } }
Transpiles a destructuring pattern in a declaration or assignment to ES5
34,185
private Node objectPatternRestRHS ( Node objectPattern , Node rest , String restTempVarName , ArrayList < Node > statedProperties ) { checkArgument ( objectPattern . getLastChild ( ) == rest ) ; Node restTempVarModel = astFactory . createName ( restTempVarName , objectPattern . getJSType ( ) ) ; Node result = restTempVarModel . cloneNode ( ) ; if ( ! statedProperties . isEmpty ( ) ) { Iterator < Node > propItr = statedProperties . iterator ( ) ; Node comma = deletionNodeForRestProperty ( restTempVarModel . cloneNode ( ) , propItr . next ( ) ) ; while ( propItr . hasNext ( ) ) { comma = astFactory . createComma ( comma , deletionNodeForRestProperty ( restTempVarModel . cloneNode ( ) , propItr . next ( ) ) ) ; } result = astFactory . createComma ( comma , result ) ; } result . useSourceInfoIfMissingFromForTree ( rest ) ; return result ; }
Convert rest of object destructuring lhs by making a clone and deleting any properties that were stated in the original object pattern .
34,186
private Node defaultValueHook ( Node getprop , Node defaultValue ) { Node undefined = astFactory . createName ( "undefined" , JSTypeNative . VOID_TYPE ) ; undefined . makeNonIndexable ( ) ; Node getpropClone = getprop . cloneTree ( ) . setJSType ( getprop . getJSType ( ) ) ; return astFactory . createHook ( astFactory . createSheq ( getprop , undefined ) , defaultValue , getpropClone ) ; }
Helper for transpiling DEFAULT_VALUE trees .
34,187
public JSDocInfo cloneClassDoc ( ) { JSDocInfo other = new JSDocInfo ( ) ; other . info = this . info == null ? null : this . info . cloneClassDoc ( ) ; other . documentation = this . documentation ; other . visibility = this . visibility ; other . bitset = this . bitset ; other . type = cloneType ( this . type , false ) ; other . thisType = cloneType ( this . thisType , false ) ; other . includeDocumentation = this . includeDocumentation ; other . originalCommentPosition = this . originalCommentPosition ; other . setConstructor ( false ) ; other . setStruct ( false ) ; if ( ! isInterface ( ) && other . info != null ) { other . info . baseType = null ; } return other ; }
This is used to get all nodes + the description excluding the param nodes . Used to help in an ES5 to ES6 class converter only .
34,188
public JSDocInfo cloneConstructorDoc ( ) { JSDocInfo other = new JSDocInfo ( ) ; other . info = this . info == null ? null : this . info . cloneConstructorDoc ( ) ; other . documentation = this . documentation == null ? null : this . documentation . cloneConstructorDoc ( ) ; return other ; }
This is used to get only the parameter nodes . Used to help in an ES5 to ES6 converter class only .
34,189
boolean setDeprecationReason ( String reason ) { lazyInitInfo ( ) ; if ( info . deprecated != null ) { return false ; } info . deprecated = reason ; return true ; }
Sets the deprecation reason .
34,190
void addSuppression ( String suppression ) { lazyInitInfo ( ) ; if ( info . suppressions == null ) { info . suppressions = ImmutableSet . of ( suppression ) ; } else { info . suppressions = new ImmutableSet . Builder < String > ( ) . addAll ( info . suppressions ) . add ( suppression ) . build ( ) ; } }
Add a suppressed warning .
34,191
boolean setModifies ( Set < String > modifies ) { lazyInitInfo ( ) ; if ( info . modifies != null ) { return false ; } info . modifies = ImmutableSet . copyOf ( modifies ) ; return true ; }
Sets modifies values .
34,192
boolean documentVersion ( String version ) { if ( ! lazyInitDocumentation ( ) ) { return true ; } if ( documentation . version != null ) { return false ; } documentation . version = version ; return true ; }
Documents the version .
34,193
boolean declareThrows ( JSTypeExpression jsType ) { lazyInitInfo ( ) ; if ( info . thrownTypes == null ) { info . thrownTypes = new ArrayList < > ( ) ; } info . thrownTypes . add ( jsType ) ; return true ; }
Declares that the method throws a given type .
34,194
public JSTypeExpression getParameterType ( String parameter ) { if ( info == null || info . parameters == null ) { return null ; } return info . parameters . get ( parameter ) ; }
Gets the type of a given named parameter .
34,195
public boolean hasParameter ( String parameter ) { if ( info == null || info . parameters == null ) { return false ; } return info . parameters . containsKey ( parameter ) ; }
Returns whether the parameter is defined .
34,196
public Set < String > getParameterNames ( ) { if ( info == null || info . parameters == null ) { return ImmutableSet . of ( ) ; } return ImmutableSet . copyOf ( info . parameters . keySet ( ) ) ; }
Returns the set of names of the defined parameters . The iteration order of the returned set is the order in which parameters are defined in the JSDoc rather than the order in which the function declares them .
34,197
public String getParameterNameAt ( int index ) { if ( info == null || info . parameters == null ) { return null ; } if ( index >= info . parameters . size ( ) ) { return null ; } return Iterables . get ( info . parameters . keySet ( ) , index ) ; }
Returns the nth name in the defined parameters . The iteration order is the order in which parameters are defined in the JSDoc rather than the order in which the function declares them .
34,198
public List < JSTypeExpression > getThrownTypes ( ) { if ( info == null || info . thrownTypes == null ) { return ImmutableList . of ( ) ; } return Collections . unmodifiableList ( info . thrownTypes ) ; }
Returns the list of thrown types .
34,199
public String getThrowsDescriptionForType ( JSTypeExpression type ) { if ( documentation == null || documentation . throwsDescriptions == null ) { return null ; } return documentation . throwsDescriptions . get ( type ) ; }
Get the message for a given thrown type .