idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
7,600
private Optional < OperationTypeDefinition > synthOperationTypeDefinition ( Function < Type , Optional < ObjectTypeDefinition > > typeReteriver , String opName ) { TypeName type = TypeName . newTypeName ( ) . name ( capitalize ( opName ) ) . build ( ) ; Optional < ObjectTypeDefinition > typeDef = typeReteriver . apply ( type ) ; return typeDef . map ( objectTypeDefinition -> OperationTypeDefinition . newOperationTypeDefinition ( ) . name ( opName ) . typeName ( type ) . build ( ) ) ; }
looks for a type called Query|Mutation|Subscription and if it exist then assumes it as an operation def
7,601
public ConnectionCursor cursorForObjectInConnection ( T object ) { int index = data . indexOf ( object ) ; if ( index == - 1 ) { return null ; } String cursor = createCursor ( index ) ; return new DefaultConnectionCursor ( cursor ) ; }
find the object s cursor or null if the object is not in this connection .
7,602
public GraphQLInputObjectField transform ( Consumer < Builder > builderConsumer ) { Builder builder = newInputObjectField ( this ) ; builderConsumer . accept ( builder ) ; return builder . build ( ) ; }
This helps you transform the current GraphQLInputObjectField into another one by starting a builder with all the current values and allows you to transform it how you want .
7,603
public MergedSelectionSet collectFields ( FieldCollectorParameters parameters , SelectionSet selectionSet ) { Map < String , MergedField > subFields = new LinkedHashMap < > ( ) ; List < String > visitedFragments = new ArrayList < > ( ) ; this . collectFields ( parameters , selectionSet , visitedFragments , subFields ) ; return newMergedSelectionSet ( ) . subFields ( subFields ) . build ( ) ; }
Given a selection set this will collect the sub - field selections and return it as a map
7,604
public ExecutionResult execute ( ExecutionInput executionInput ) { try { return executeAsync ( executionInput ) . join ( ) ; } catch ( CompletionException e ) { if ( e . getCause ( ) instanceof RuntimeException ) { throw ( RuntimeException ) e . getCause ( ) ; } else { throw e ; } } }
Executes the graphql query using the provided input object
7,605
public String print ( GraphQLSchema schema ) { StringWriter sw = new StringWriter ( ) ; PrintWriter out = new PrintWriter ( sw ) ; GraphqlFieldVisibility visibility = schema . getCodeRegistry ( ) . getFieldVisibility ( ) ; printer ( schema . getClass ( ) ) . print ( out , schema , visibility ) ; List < GraphQLType > typesAsList = schema . getAllTypesAsList ( ) . stream ( ) . sorted ( Comparator . comparing ( GraphQLType :: getName ) ) . collect ( toList ( ) ) ; printType ( out , typesAsList , GraphQLInterfaceType . class , visibility ) ; printType ( out , typesAsList , GraphQLUnionType . class , visibility ) ; printType ( out , typesAsList , GraphQLObjectType . class , visibility ) ; printType ( out , typesAsList , GraphQLEnumType . class , visibility ) ; printType ( out , typesAsList , GraphQLScalarType . class , visibility ) ; printType ( out , typesAsList , GraphQLInputObjectType . class , visibility ) ; String result = sw . toString ( ) ; if ( result . endsWith ( "\n\n" ) ) { result = result . substring ( 0 , result . length ( ) - 1 ) ; } return result ; }
This can print an in memory GraphQL schema back to a logical schema definition
7,606
public void addError ( GraphQLError error , ExecutionPath fieldPath ) { for ( GraphQLError graphQLError : errors ) { List < Object > path = graphQLError . getPath ( ) ; if ( path != null ) { if ( fieldPath . equals ( ExecutionPath . fromList ( path ) ) ) { return ; } } } this . errors . add ( error ) ; }
This method will only put one error per field path .
7,607
public ExecutionContext transform ( Consumer < ExecutionContextBuilder > builderConsumer ) { ExecutionContextBuilder builder = ExecutionContextBuilder . newExecutionContextBuilder ( this ) ; builderConsumer . accept ( builder ) ; return builder . build ( ) ; }
This helps you transform the current ExecutionContext object into another one by starting a builder with all the current values and allows you to transform it how you want .
7,608
public GraphQLInputObjectType transform ( Consumer < Builder > builderConsumer ) { Builder builder = newInputObject ( this ) ; builderConsumer . accept ( builder ) ; return builder . build ( ) ; }
This helps you transform the current GraphQLInputObjectType into another one by starting a builder with all the current values and allows you to transform it how you want .
7,609
public GraphQLDirective transform ( Consumer < Builder > builderConsumer ) { Builder builder = newDirective ( this ) ; builderConsumer . accept ( builder ) ; return builder . build ( ) ; }
This helps you transform the current GraphQLDirective into another one by starting a builder with all the current values and allows you to transform it how you want .
7,610
public GraphQLInputType buildDirectiveInputType ( Value value ) { if ( value instanceof NullValue ) { return Scalars . GraphQLString ; } if ( value instanceof FloatValue ) { return Scalars . GraphQLFloat ; } if ( value instanceof StringValue ) { return Scalars . GraphQLString ; } if ( value instanceof IntValue ) { return Scalars . GraphQLInt ; } if ( value instanceof BooleanValue ) { return Scalars . GraphQLBoolean ; } if ( value instanceof ArrayValue ) { ArrayValue arrayValue = ( ArrayValue ) value ; return list ( buildDirectiveInputType ( getArrayValueWrappedType ( arrayValue ) ) ) ; } return assertShouldNeverHappen ( "Directive values of type '%s' are not supported yet" , value . getClass ( ) . getSimpleName ( ) ) ; }
We support the basic types as directive types
7,611
public GraphQLDirective buildDirective ( Directive directive , Set < GraphQLDirective > directiveDefinitions , DirectiveLocation directiveLocation ) { Optional < GraphQLDirective > directiveDefinition = directiveDefinitions . stream ( ) . filter ( dd -> dd . getName ( ) . equals ( directive . getName ( ) ) ) . findFirst ( ) ; GraphQLDirective . Builder builder = GraphQLDirective . newDirective ( ) . name ( directive . getName ( ) ) . description ( buildDescription ( directive , null ) ) . validLocations ( directiveLocation ) ; List < GraphQLArgument > arguments = directive . getArguments ( ) . stream ( ) . map ( arg -> buildDirectiveArgument ( arg , directiveDefinition ) ) . collect ( Collectors . toList ( ) ) ; if ( directiveDefinition . isPresent ( ) ) { arguments = transferMissingArguments ( arguments , directiveDefinition . get ( ) ) ; } arguments . forEach ( builder :: argument ) ; return builder . build ( ) ; }
builds directives from a type and its extensions
7,612
public GraphQLEnumValueDefinition transform ( Consumer < Builder > builderConsumer ) { Builder builder = newEnumValueDefinition ( this ) ; builderConsumer . accept ( builder ) ; return builder . build ( ) ; }
This helps you transform the current GraphQLEnumValueDefinition into another one by starting a builder with all the current values and allows you to transform it how you want .
7,613
public ExecutionInput transform ( Consumer < Builder > builderConsumer ) { Builder builder = new Builder ( ) . query ( this . query ) . operationName ( this . operationName ) . context ( this . context ) . root ( this . root ) . dataLoaderRegistry ( this . dataLoaderRegistry ) . cacheControl ( this . cacheControl ) . variables ( this . variables ) ; builderConsumer . accept ( builder ) ; return builder . build ( ) ; }
This helps you transform the current ExecutionInput object into another one by starting a builder with all the current values and allows you to transform it how you want .
7,614
@ SuppressWarnings ( "unchecked" ) public < T > T getArgument ( String name ) { return ( T ) arguments . get ( name ) ; }
Returns the named argument
7,615
@ SuppressWarnings ( { "unchecked" , "TypeParameterUnusedInFormals" } ) private < T extends GraphQLOutputType > T buildOutputType ( BuildContext buildCtx , Type rawType ) { TypeDefinition typeDefinition = buildCtx . getTypeDefinition ( rawType ) ; TypeInfo typeInfo = TypeInfo . typeInfo ( rawType ) ; GraphQLOutputType outputType = buildCtx . hasOutputType ( typeDefinition ) ; if ( outputType != null ) { return typeInfo . decorate ( outputType ) ; } if ( buildCtx . stackContains ( typeInfo ) ) { return typeInfo . decorate ( typeRef ( typeInfo . getName ( ) ) ) ; } buildCtx . push ( typeInfo ) ; if ( typeDefinition instanceof ObjectTypeDefinition ) { outputType = buildObjectType ( buildCtx , ( ObjectTypeDefinition ) typeDefinition ) ; } else if ( typeDefinition instanceof InterfaceTypeDefinition ) { outputType = buildInterfaceType ( buildCtx , ( InterfaceTypeDefinition ) typeDefinition ) ; } else if ( typeDefinition instanceof UnionTypeDefinition ) { outputType = buildUnionType ( buildCtx , ( UnionTypeDefinition ) typeDefinition ) ; } else if ( typeDefinition instanceof EnumTypeDefinition ) { outputType = buildEnumType ( buildCtx , ( EnumTypeDefinition ) typeDefinition ) ; } else if ( typeDefinition instanceof ScalarTypeDefinition ) { outputType = buildScalar ( buildCtx , ( ScalarTypeDefinition ) typeDefinition ) ; } else { throw new NotAnOutputTypeError ( rawType , typeDefinition ) ; } buildCtx . putOutputType ( outputType ) ; buildCtx . pop ( ) ; return ( T ) typeInfo . decorate ( outputType ) ; }
This is the main recursive spot that builds out the various forms of Output types
7,616
public static Value astFromValue ( Object value , GraphQLType type ) { if ( value == null ) { return null ; } if ( isNonNull ( type ) ) { return handleNonNull ( value , ( GraphQLNonNull ) type ) ; } if ( isList ( type ) ) { return handleList ( value , ( GraphQLList ) type ) ; } if ( type instanceof GraphQLInputObjectType ) { return handleInputObject ( value , ( GraphQLInputObjectType ) type ) ; } if ( ! ( type instanceof GraphQLScalarType || type instanceof GraphQLEnumType ) ) { throw new AssertException ( "Must provide Input Type, cannot use: " + type . getClass ( ) ) ; } final Object serialized = serialize ( type , value ) ; if ( isNullish ( serialized ) ) { return null ; } if ( serialized instanceof Boolean ) { return BooleanValue . newBooleanValue ( ) . value ( ( Boolean ) serialized ) . build ( ) ; } String stringValue = serialized . toString ( ) ; if ( serialized instanceof Number ) { return handleNumber ( stringValue ) ; } if ( serialized instanceof String ) { if ( type instanceof GraphQLEnumType ) { return EnumValue . newEnumValue ( ) . name ( stringValue ) . build ( ) ; } if ( type == Scalars . GraphQLID && stringValue . matches ( "^[0-9]+$" ) ) { return IntValue . newIntValue ( ) . value ( new BigInteger ( stringValue ) ) . build ( ) ; } return StringValue . newStringValue ( ) . value ( jsonStringify ( stringValue ) ) . build ( ) ; } throw new AssertException ( "'Cannot convert value to AST: " + serialized ) ; }
Produces a GraphQL Value AST given a Java value .
7,617
private void checkObjectImplementsInterface ( GraphQLObjectType objectType , GraphQLInterfaceType interfaceType , SchemaValidationErrorCollector validationErrorCollector ) { List < GraphQLFieldDefinition > fieldDefinitions = interfaceType . getFieldDefinitions ( ) ; for ( GraphQLFieldDefinition interfaceFieldDef : fieldDefinitions ) { GraphQLFieldDefinition objectFieldDef = objectType . getFieldDefinition ( interfaceFieldDef . getName ( ) ) ; if ( objectFieldDef == null ) { validationErrorCollector . addError ( error ( format ( "object type '%s' does not implement interface '%s' because field '%s' is missing" , objectType . getName ( ) , interfaceType . getName ( ) , interfaceFieldDef . getName ( ) ) ) ) ; } else { checkFieldTypeCompatibility ( objectType , interfaceType , validationErrorCollector , interfaceFieldDef , objectFieldDef ) ; } } }
when completely open
7,618
public synchronized void reloadableScan ( String fileName ) { if ( ! isFirstInit ) { return ; } if ( DisClientConfig . getInstance ( ) . ENABLE_DISCONF ) { try { if ( ! DisClientConfig . getInstance ( ) . getIgnoreDisconfKeySet ( ) . contains ( fileName ) ) { if ( scanMgr != null ) { scanMgr . reloadableScan ( fileName ) ; } if ( disconfCoreMgr != null ) { disconfCoreMgr . processFile ( fileName ) ; } LOGGER . debug ( "disconf reloadable file: {}" , fileName ) ; } } catch ( Exception e ) { LOGGER . error ( e . toString ( ) , e ) ; } } }
reloadable config file scan for xml config
7,619
protected Object retryOperation ( ZooKeeperOperation operation ) throws KeeperException , InterruptedException { KeeperException exception = null ; for ( int i = 0 ; i < retryCount ; i ++ ) { try { return operation . execute ( ) ; } catch ( KeeperException . SessionExpiredException e ) { LOG . warn ( "Session expired for: " + zookeeper + " so reconnecting due to: " + e , e ) ; throw e ; } catch ( KeeperException . ConnectionLossException e ) { if ( exception == null ) { exception = e ; } LOG . debug ( "Attempt " + i + " failed with connection loss so " + "attempting to reconnect: " + e , e ) ; retryDelay ( i ) ; } } throw exception ; }
Perform the given operation retrying if the connection fails
7,620
protected void ensureExists ( final String path , final byte [ ] data , final List < ACL > acl , final CreateMode flags ) { try { retryOperation ( new ZooKeeperOperation ( ) { public boolean execute ( ) throws KeeperException , InterruptedException { Stat stat = zookeeper . exists ( path , false ) ; if ( stat != null ) { return true ; } zookeeper . create ( path , data , acl , flags ) ; return true ; } } ) ; } catch ( KeeperException e ) { LOG . warn ( "Caught: " + e , e ) ; } catch ( InterruptedException e ) { LOG . warn ( "Caught: " + e , e ) ; } }
Ensures that the given path exists with the given data ACL and flags
7,621
protected void retryDelay ( int attemptCount ) { if ( attemptCount > 0 ) { try { Thread . sleep ( attemptCount * retryDelay ) ; } catch ( InterruptedException e ) { LOG . debug ( "Failed to sleep: " + e , e ) ; } } }
Performs a retry delay if this is not the first attempt
7,622
private String getFileName ( String fileName ) { if ( fileName != null ) { int index = fileName . indexOf ( ':' ) ; if ( index < 0 ) { return fileName ; } else { fileName = fileName . substring ( index + 1 ) ; index = fileName . lastIndexOf ( '/' ) ; if ( index < 0 ) { return fileName ; } else { return fileName . substring ( index + 1 ) ; } } } return null ; }
get file name from resource
7,623
public synchronized void unlock ( ) throws RuntimeException { if ( ! isClosed ( ) && id != null ) { try { ZooKeeperOperation zopdel = new ZooKeeperOperation ( ) { public boolean execute ( ) throws KeeperException , InterruptedException { zookeeper . delete ( id , - 1 ) ; return Boolean . TRUE ; } } ; zopdel . execute ( ) ; } catch ( InterruptedException e ) { LOG . warn ( "Caught: " + e , e ) ; Thread . currentThread ( ) . interrupt ( ) ; } catch ( KeeperException . NoNodeException e ) { } catch ( KeeperException e ) { LOG . warn ( "Caught: " + e , e ) ; throw ( RuntimeException ) new RuntimeException ( e . getMessage ( ) ) . initCause ( e ) ; } finally { if ( callback != null ) { callback . lockReleased ( ) ; } id = null ; } } }
Removes the lock or associated znode if you no longer require the lock . this also removes your request in the queue for locking in case you do not already hold the lock .
7,624
public synchronized boolean lock ( ) throws KeeperException , InterruptedException { if ( isClosed ( ) ) { return false ; } ensurePathExists ( dir ) ; return ( Boolean ) retryOperation ( zop ) ; }
Attempts to acquire the exclusive write lock returning whether or not it was acquired . Note that the exclusive lock may be acquired some time later after this method has been invoked due to the current lock owner going away .
7,625
public static Map < String , String > parse2Map ( String json ) { Type stringStringMap = new TypeToken < Map < String , String > > ( ) { } . getType ( ) ; Gson gson = new Gson ( ) ; Map < String , String > map = gson . fromJson ( json , stringStringMap ) ; return map ; }
Parse json to map
7,626
private void registerAspect ( BeanDefinitionRegistry registry ) { GenericBeanDefinition beanDefinition = new GenericBeanDefinition ( ) ; beanDefinition . setBeanClass ( DisconfAspectJ . class ) ; beanDefinition . setLazyInit ( false ) ; beanDefinition . setAbstract ( false ) ; beanDefinition . setAutowireCandidate ( true ) ; beanDefinition . setScope ( "singleton" ) ; registry . registerBeanDefinition ( "disconfAspectJ" , beanDefinition ) ; }
register aspectJ for disconf get request
7,627
public RequestPatternBuilder apply ( Request request ) { final RequestPatternBuilder builder = new RequestPatternBuilder ( request . getMethod ( ) , urlEqualTo ( request . getUrl ( ) ) ) ; if ( headers != null && ! headers . isEmpty ( ) ) { for ( Map . Entry < String , CaptureHeadersSpec > header : headers . entrySet ( ) ) { String headerName = header . getKey ( ) ; if ( request . containsHeader ( headerName ) ) { CaptureHeadersSpec spec = header . getValue ( ) ; StringValuePattern headerMatcher = new EqualToPattern ( request . getHeader ( headerName ) , spec . getCaseInsensitive ( ) ) ; builder . withHeader ( headerName , headerMatcher ) ; } } } byte [ ] body = request . getBody ( ) ; if ( bodyPatternFactory != null && body != null && body . length > 0 ) { builder . withRequestBody ( bodyPatternFactory . forRequest ( request ) ) ; } return builder ; }
Returns a RequestPatternBuilder matching a given Request
7,628
protected Map < String , Object > addExtraModelElements ( Request request , ResponseDefinition responseDefinition , FileSource files , Parameters parameters ) { return Collections . emptyMap ( ) ; }
Override this to add extra elements to the template model
7,629
public static RequestPatternBuilder like ( RequestPattern requestPattern ) { RequestPatternBuilder builder = new RequestPatternBuilder ( ) ; builder . url = requestPattern . getUrlMatcher ( ) ; builder . method = requestPattern . getMethod ( ) ; if ( requestPattern . getHeaders ( ) != null ) { builder . headers = requestPattern . getHeaders ( ) ; } if ( requestPattern . getQueryParameters ( ) != null ) { builder . queryParams = requestPattern . getQueryParameters ( ) ; } if ( requestPattern . getCookies ( ) != null ) { builder . cookies = requestPattern . getCookies ( ) ; } if ( requestPattern . getBodyPatterns ( ) != null ) { builder . bodyPatterns = requestPattern . getBodyPatterns ( ) ; } if ( requestPattern . hasInlineCustomMatcher ( ) ) { builder . customMatcher = requestPattern . getMatcher ( ) ; } if ( requestPattern . getMultipartPatterns ( ) != null ) { builder . multiparts = requestPattern . getMultipartPatterns ( ) ; } builder . basicCredentials = requestPattern . getBasicAuthCredentials ( ) ; builder . customMatcherDefinition = requestPattern . getCustomMatcher ( ) ; return builder ; }
Construct a builder that uses an existing RequestPattern as a template
7,630
public void shutdown ( ) { final WireMockServer server = this ; Thread shutdownThread = new Thread ( new Runnable ( ) { public void run ( ) { try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } server . stop ( ) ; } } ) ; shutdownThread . start ( ) ; }
Gracefully shutdown the server .
7,631
public void extractInPlace ( StubMapping stubMapping ) { byte [ ] body = stubMapping . getResponse ( ) . getByteBody ( ) ; HttpHeaders responseHeaders = stubMapping . getResponse ( ) . getHeaders ( ) ; String extension = ContentTypes . determineFileExtension ( stubMapping . getRequest ( ) . getUrl ( ) , responseHeaders != null ? responseHeaders . getContentTypeHeader ( ) : ContentTypeHeader . absent ( ) , body ) ; String bodyFileName = SafeNames . makeSafeFileName ( stubMapping , extension ) ; String noStringBody = null ; byte [ ] noByteBody = null ; stubMapping . setResponse ( ResponseDefinitionBuilder . like ( stubMapping . getResponse ( ) ) . withBodyFile ( bodyFileName ) . withBody ( noStringBody ) . withBody ( noByteBody ) . withBase64Body ( null ) . build ( ) ) ; fileSource . writeBinaryFile ( bodyFileName , body ) ; }
Extracts body of the ResponseDefinition to a file written to the files source . Modifies the ResponseDefinition to point to the file in - place .
7,632
protected String handleError ( final String message ) { notifier ( ) . error ( formatMessage ( message ) ) ; return formatMessage ( message ) ; }
Handle invalid helper data without exception details or because none was thrown .
7,633
protected String handleError ( final String message , final Throwable cause ) { notifier ( ) . error ( formatMessage ( message ) , cause ) ; return formatMessage ( message ) ; }
Handle invalid helper data with exception details in the log message .
7,634
public static Elements collect ( Evaluator eval , Element root ) { Elements elements = new Elements ( ) ; NodeTraversor . traverse ( new Accumulator ( root , elements , eval ) , root ) ; return elements ; }
Build a list of elements by visiting root and every descendant of root and testing it against the evaluator .
7,635
public void setKey ( String key ) { Validate . notNull ( key ) ; key = key . trim ( ) ; Validate . notEmpty ( key ) ; if ( parent != null ) { int i = parent . indexOfKey ( this . key ) ; if ( i != Attributes . NotFound ) parent . keys [ i ] = key ; } this . key = key ; }
Set the attribute key ; case is preserved .
7,636
public static Attribute createFromEncoded ( String unencodedKey , String encodedValue ) { String value = Entities . unescape ( encodedValue , true ) ; return new Attribute ( unencodedKey , value , null ) ; }
Create a new Attribute from an unencoded key and a HTML attribute encoded value .
7,637
public Document fromJsoup ( org . jsoup . nodes . Document in ) { Validate . notNull ( in ) ; DocumentBuilder builder ; try { factory . setNamespaceAware ( true ) ; builder = factory . newDocumentBuilder ( ) ; Document out = builder . newDocument ( ) ; convert ( in , out ) ; return out ; } catch ( ParserConfigurationException e ) { throw new IllegalStateException ( e ) ; } }
Convert a jsoup Document to a W3C Document .
7,638
public void convert ( org . jsoup . nodes . Document in , Document out ) { if ( ! StringUtil . isBlank ( in . location ( ) ) ) out . setDocumentURI ( in . location ( ) ) ; org . jsoup . nodes . Element rootEl = in . child ( 0 ) ; NodeTraversor . traverse ( new W3CBuilder ( out ) , rootEl ) ; }
Converts a jsoup document into the provided W3C Document . If required you can set options on the output document before converting .
7,639
public String asString ( Document doc ) { try { DOMSource domSource = new DOMSource ( doc ) ; StringWriter writer = new StringWriter ( ) ; StreamResult result = new StreamResult ( writer ) ; TransformerFactory tf = TransformerFactory . newInstance ( ) ; Transformer transformer = tf . newTransformer ( ) ; transformer . transform ( domSource , result ) ; return writer . toString ( ) ; } catch ( TransformerException e ) { throw new IllegalStateException ( e ) ; } }
Serialize a W3C document to a String .
7,640
int nextIndexOf ( char c ) { bufferUp ( ) ; for ( int i = bufPos ; i < bufLength ; i ++ ) { if ( c == charBuf [ i ] ) return i - bufPos ; } return - 1 ; }
Returns the number of characters between the current position and the next instance of the input char
7,641
int nextIndexOf ( CharSequence seq ) { bufferUp ( ) ; char startChar = seq . charAt ( 0 ) ; for ( int offset = bufPos ; offset < bufLength ; offset ++ ) { if ( startChar != charBuf [ offset ] ) while ( ++ offset < bufLength && startChar != charBuf [ offset ] ) { } int i = offset + 1 ; int last = i + seq . length ( ) - 1 ; if ( offset < bufLength && last <= bufLength ) { for ( int j = 1 ; i < last && seq . charAt ( j ) == charBuf [ i ] ; i ++ , j ++ ) { } if ( i == last ) return offset - bufPos ; } } return - 1 ; }
Returns the number of characters between the current position and the next instance of the input sequence
7,642
public String consumeTo ( char c ) { int offset = nextIndexOf ( c ) ; if ( offset != - 1 ) { String consumed = cacheString ( charBuf , stringCache , bufPos , offset ) ; bufPos += offset ; return consumed ; } else { return consumeToEnd ( ) ; } }
Reads characters up to the specific char .
7,643
public String consumeToAny ( final char ... chars ) { bufferUp ( ) ; int pos = bufPos ; final int start = pos ; final int remaining = bufLength ; final char [ ] val = charBuf ; final int charLen = chars . length ; int i ; OUTER : while ( pos < remaining ) { for ( i = 0 ; i < charLen ; i ++ ) { if ( val [ pos ] == chars [ i ] ) break OUTER ; } pos ++ ; } bufPos = pos ; return pos > start ? cacheString ( charBuf , stringCache , start , pos - start ) : "" ; }
Read characters until the first of any delimiters is found .
7,644
static boolean rangeEquals ( final char [ ] charBuf , final int start , int count , final String cached ) { if ( count == cached . length ( ) ) { int i = start ; int j = 0 ; while ( count -- != 0 ) { if ( charBuf [ i ++ ] != cached . charAt ( j ++ ) ) return false ; } return true ; } return false ; }
Check if the value of the provided range equals the string .
7,645
boolean rangeEquals ( final int start , final int count , final String cached ) { return rangeEquals ( charBuf , start , count , cached ) ; }
just used for testing
7,646
static void escape ( Appendable accum , String string , Document . OutputSettings out , boolean inAttribute , boolean normaliseWhite , boolean stripLeadingWhite ) throws IOException { boolean lastWasWhite = false ; boolean reachedNonWhite = false ; final EscapeMode escapeMode = out . escapeMode ( ) ; final CharsetEncoder encoder = out . encoder ( ) ; final CoreCharset coreCharset = out . coreCharset ; final int length = string . length ( ) ; int codePoint ; for ( int offset = 0 ; offset < length ; offset += Character . charCount ( codePoint ) ) { codePoint = string . codePointAt ( offset ) ; if ( normaliseWhite ) { if ( StringUtil . isWhitespace ( codePoint ) ) { if ( ( stripLeadingWhite && ! reachedNonWhite ) || lastWasWhite ) continue ; accum . append ( ' ' ) ; lastWasWhite = true ; continue ; } else { lastWasWhite = false ; reachedNonWhite = true ; } } if ( codePoint < Character . MIN_SUPPLEMENTARY_CODE_POINT ) { final char c = ( char ) codePoint ; switch ( c ) { case '&' : accum . append ( "&amp;" ) ; break ; case 0xA0 : if ( escapeMode != EscapeMode . xhtml ) accum . append ( "&nbsp;" ) ; else accum . append ( "&#xa0;" ) ; break ; case '<' : if ( ! inAttribute || escapeMode == EscapeMode . xhtml ) accum . append ( "&lt;" ) ; else accum . append ( c ) ; break ; case '>' : if ( ! inAttribute ) accum . append ( "&gt;" ) ; else accum . append ( c ) ; break ; case '"' : if ( inAttribute ) accum . append ( "&quot;" ) ; else accum . append ( c ) ; break ; default : if ( canEncode ( coreCharset , c , encoder ) ) accum . append ( c ) ; else appendEncoded ( accum , escapeMode , codePoint ) ; } } else { final String c = new String ( Character . toChars ( codePoint ) ) ; if ( encoder . canEncode ( c ) ) accum . append ( c ) ; else appendEncoded ( accum , escapeMode , codePoint ) ; } } }
this method is ugly and does a lot . but other breakups cause rescanning and stringbuilder generations
7,647
public Node removeAttr ( String attributeKey ) { Validate . notNull ( attributeKey ) ; attributes ( ) . removeIgnoreCase ( attributeKey ) ; return this ; }
Remove an attribute from this element .
7,648
public void setBaseUri ( final String baseUri ) { Validate . notNull ( baseUri ) ; traverse ( new NodeVisitor ( ) { public void head ( Node node , int depth ) { node . doSetBaseUri ( baseUri ) ; } public void tail ( Node node , int depth ) { } } ) ; }
Update the base URI of this node and all of its descendants .
7,649
public List < Node > childNodesCopy ( ) { final List < Node > nodes = ensureChildNodes ( ) ; final ArrayList < Node > children = new ArrayList < > ( nodes . size ( ) ) ; for ( Node node : nodes ) { children . add ( node . clone ( ) ) ; } return children ; }
Returns a deep copy of this node s children . Changes made to these nodes will not be reflected in the original nodes
7,650
public Document ownerDocument ( ) { Node root = root ( ) ; return ( root instanceof Document ) ? ( Document ) root : null ; }
Gets the Document associated with this Node .
7,651
public Node wrap ( String html ) { Validate . notEmpty ( html ) ; Element context = parent ( ) instanceof Element ? ( Element ) parent ( ) : null ; List < Node > wrapChildren = NodeUtils . parser ( this ) . parseFragmentInput ( html , context , baseUri ( ) ) ; Node wrapNode = wrapChildren . get ( 0 ) ; if ( ! ( wrapNode instanceof Element ) ) return null ; Element wrap = ( Element ) wrapNode ; Element deepest = getDeepChild ( wrap ) ; parentNode . replaceChild ( this , wrap ) ; deepest . addChildren ( this ) ; if ( wrapChildren . size ( ) > 0 ) { for ( int i = 0 ; i < wrapChildren . size ( ) ; i ++ ) { Node remainder = wrapChildren . get ( i ) ; remainder . parentNode . removeChild ( remainder ) ; wrap . appendChild ( remainder ) ; } } return this ; }
Wrap the supplied HTML around this node .
7,652
public void replaceWith ( Node in ) { Validate . notNull ( in ) ; Validate . notNull ( parentNode ) ; parentNode . replaceChild ( this , in ) ; }
Replace this node in the DOM with the supplied node .
7,653
public Node nextSibling ( ) { if ( parentNode == null ) return null ; final List < Node > siblings = parentNode . ensureChildNodes ( ) ; final int index = siblingIndex + 1 ; if ( siblings . size ( ) > index ) return siblings . get ( index ) ; else return null ; }
Get this node s next sibling .
7,654
public Node previousSibling ( ) { if ( parentNode == null ) return null ; if ( siblingIndex > 0 ) return parentNode . ensureChildNodes ( ) . get ( siblingIndex - 1 ) ; else return null ; }
Get this node s previous sibling .
7,655
public Node traverse ( NodeVisitor nodeVisitor ) { Validate . notNull ( nodeVisitor ) ; NodeTraversor . traverse ( nodeVisitor , this ) ; return this ; }
Perform a depth - first traversal through this node and its descendants .
7,656
public Node filter ( NodeFilter nodeFilter ) { Validate . notNull ( nodeFilter ) ; NodeTraversor . filter ( nodeFilter , this ) ; return this ; }
Perform a depth - first filtering through this node and its descendants .
7,657
public boolean hasSameValue ( Object o ) { if ( this == o ) return true ; if ( o == null || getClass ( ) != o . getClass ( ) ) return false ; return this . outerHtml ( ) . equals ( ( ( Node ) o ) . outerHtml ( ) ) ; }
Check if this node is has the same content as another node . A node is considered the same if its name attributes and content match the other node ; particularly its position in the tree does not influence its similarity .
7,658
public static Document parse ( String html , String baseUri ) { return Parser . parse ( html , baseUri ) ; }
Parse HTML into a Document . The parser will make a sensible balanced document tree out of any HTML .
7,659
public static Document parse ( File in , String charsetName , String baseUri ) throws IOException { return DataUtil . load ( in , charsetName , baseUri ) ; }
Parse the contents of a file as HTML .
7,660
public static Document parse ( File in , String charsetName ) throws IOException { return DataUtil . load ( in , charsetName , in . getAbsolutePath ( ) ) ; }
Parse the contents of a file as HTML . The location of the file is used as the base URI to qualify relative URLs .
7,661
public static String clean ( String bodyHtml , String baseUri , Whitelist whitelist ) { Document dirty = parseBodyFragment ( bodyHtml , baseUri ) ; Cleaner cleaner = new Cleaner ( whitelist ) ; Document clean = cleaner . clean ( dirty ) ; return clean . body ( ) . html ( ) ; }
Get safe HTML from untrusted input HTML by parsing input HTML and filtering it through a white - list of permitted tags and attributes .
7,662
public Whitelist removeEnforcedAttribute ( String tag , String attribute ) { Validate . notEmpty ( tag ) ; Validate . notEmpty ( attribute ) ; TagName tagName = TagName . valueOf ( tag ) ; if ( tagNames . contains ( tagName ) && enforcedAttributes . containsKey ( tagName ) ) { AttributeKey attrKey = AttributeKey . valueOf ( attribute ) ; Map < AttributeKey , AttributeValue > attrMap = enforcedAttributes . get ( tagName ) ; attrMap . remove ( attrKey ) ; if ( attrMap . isEmpty ( ) ) enforcedAttributes . remove ( tagName ) ; } return this ; }
Remove a previously configured enforced attribute from a tag .
7,663
protected boolean isSafeAttribute ( String tagName , Element el , Attribute attr ) { TagName tag = TagName . valueOf ( tagName ) ; AttributeKey key = AttributeKey . valueOf ( attr . getKey ( ) ) ; Set < AttributeKey > okSet = attributes . get ( tag ) ; if ( okSet != null && okSet . contains ( key ) ) { if ( protocols . containsKey ( tag ) ) { Map < AttributeKey , Set < Protocol > > attrProts = protocols . get ( tag ) ; return ! attrProts . containsKey ( key ) || testValidProtocol ( el , attr , attrProts . get ( key ) ) ; } else { return true ; } } Map < AttributeKey , AttributeValue > enforcedSet = enforcedAttributes . get ( tag ) ; if ( enforcedSet != null ) { Attributes expect = getEnforcedAttributes ( tagName ) ; String attrKey = attr . getKey ( ) ; if ( expect . hasKeyIgnoreCase ( attrKey ) ) { return expect . getIgnoreCase ( attrKey ) . equals ( attr . getValue ( ) ) ; } } return ! tagName . equals ( ":all" ) && isSafeAttribute ( ":all" , el , attr ) ; }
Test if the supplied attribute is allowed by this whitelist for this tag
7,664
public static DataNode createFromEncoded ( String encodedData , String baseUri ) { String data = Entities . unescape ( encodedData ) ; return new DataNode ( data ) ; }
Create a new DataNode from HTML encoded data .
7,665
public static Document createShell ( String baseUri ) { Validate . notNull ( baseUri ) ; Document doc = new Document ( baseUri ) ; doc . parser = doc . parser ( ) ; Element html = doc . appendElement ( "html" ) ; html . appendElement ( "head" ) ; html . appendElement ( "body" ) ; return doc ; }
Create a valid empty shell of a document suitable for adding more elements to .
7,666
public Element createElement ( String tagName ) { return new Element ( Tag . valueOf ( tagName , ParseSettings . preserveCase ) , this . baseUri ( ) ) ; }
Create a new Element with this document s base uri . Does not make the new element a child of this document .
7,667
public Document normalise ( ) { Element htmlEl = findFirstElementByTagName ( "html" , this ) ; if ( htmlEl == null ) htmlEl = appendElement ( "html" ) ; if ( head ( ) == null ) htmlEl . prependElement ( "head" ) ; if ( body ( ) == null ) htmlEl . appendElement ( "body" ) ; normaliseTextNodes ( head ( ) ) ; normaliseTextNodes ( htmlEl ) ; normaliseTextNodes ( this ) ; normaliseStructure ( "head" , htmlEl ) ; normaliseStructure ( "body" , htmlEl ) ; ensureMetaCharsetElement ( ) ; return this ; }
Normalise the document . This happens after the parse phase so generally does not need to be called . Moves any text content that is not in the body element into the body .
7,668
private void normaliseTextNodes ( Element element ) { List < Node > toMove = new ArrayList < > ( ) ; for ( Node node : element . childNodes ) { if ( node instanceof TextNode ) { TextNode tn = ( TextNode ) node ; if ( ! tn . isBlank ( ) ) toMove . add ( tn ) ; } } for ( int i = toMove . size ( ) - 1 ; i >= 0 ; i -- ) { Node node = toMove . get ( i ) ; element . removeChild ( node ) ; body ( ) . prependChild ( new TextNode ( " " ) ) ; body ( ) . prependChild ( node ) ; } }
does not recurse .
7,669
private Element findFirstElementByTagName ( String tag , Node node ) { if ( node . nodeName ( ) . equals ( tag ) ) return ( Element ) node ; else { int size = node . childNodeSize ( ) ; for ( int i = 0 ; i < size ; i ++ ) { Element found = findFirstElementByTagName ( tag , node . childNode ( i ) ) ; if ( found != null ) return found ; } } return null ; }
fast method to get first by tag name used for html head body finders
7,670
private static String encodeUrl ( String url ) { try { URL u = new URL ( url ) ; return encodeUrl ( u ) . toExternalForm ( ) ; } catch ( Exception e ) { return url ; } }
Encodes the input URL into a safe ASCII URL string
7,671
public List < Connection . KeyVal > formData ( ) { ArrayList < Connection . KeyVal > data = new ArrayList < > ( ) ; for ( Element el : elements ) { if ( ! el . tag ( ) . isFormSubmittable ( ) ) continue ; if ( el . hasAttr ( "disabled" ) ) continue ; String name = el . attr ( "name" ) ; if ( name . length ( ) == 0 ) continue ; String type = el . attr ( "type" ) ; if ( "select" . equals ( el . tagName ( ) ) ) { Elements options = el . select ( "option[selected]" ) ; boolean set = false ; for ( Element option : options ) { data . add ( HttpConnection . KeyVal . create ( name , option . val ( ) ) ) ; set = true ; } if ( ! set ) { Element option = el . select ( "option" ) . first ( ) ; if ( option != null ) data . add ( HttpConnection . KeyVal . create ( name , option . val ( ) ) ) ; } } else if ( "checkbox" . equalsIgnoreCase ( type ) || "radio" . equalsIgnoreCase ( type ) ) { if ( el . hasAttr ( "checked" ) ) { final String val = el . val ( ) . length ( ) > 0 ? el . val ( ) : "on" ; data . add ( HttpConnection . KeyVal . create ( name , val ) ) ; } } else { data . add ( HttpConnection . KeyVal . create ( name , el . val ( ) ) ) ; } } return data ; }
Get the data that this form submits . The returned list is a copy of the data and changes to the contents of the list will not be reflected in the DOM .
7,672
private void popStackToClose ( Token . EndTag endTag ) { String elName = settings . normalizeTag ( endTag . tagName ) ; Element firstFound = null ; for ( int pos = stack . size ( ) - 1 ; pos >= 0 ; pos -- ) { Element next = stack . get ( pos ) ; if ( next . nodeName ( ) . equals ( elName ) ) { firstFound = next ; break ; } } if ( firstFound == null ) return ; for ( int pos = stack . size ( ) - 1 ; pos >= 0 ; pos -- ) { Element next = stack . get ( pos ) ; stack . remove ( pos ) ; if ( next == firstFound ) break ; } }
If the stack contains an element with this tag s name pop up the stack to remove the first occurrence . If not found skips .
7,673
public static String join ( String [ ] strings , String sep ) { return join ( Arrays . asList ( strings ) , sep ) ; }
Join an array of strings by a separator
7,674
public static String padding ( int width ) { if ( width < 0 ) throw new IllegalArgumentException ( "width must be > 0" ) ; if ( width < padding . length ) return padding [ width ] ; char [ ] out = new char [ width ] ; for ( int i = 0 ; i < width ; i ++ ) out [ i ] = ' ' ; return String . valueOf ( out ) ; }
Returns space padding
7,675
public static boolean isNumeric ( String string ) { if ( string == null || string . length ( ) == 0 ) return false ; int l = string . length ( ) ; for ( int i = 0 ; i < l ; i ++ ) { if ( ! Character . isDigit ( string . codePointAt ( i ) ) ) return false ; } return true ; }
Tests if a string is numeric i . e . contains only digit characters
7,676
public static void appendNormalisedWhitespace ( StringBuilder accum , String string , boolean stripLeading ) { boolean lastWasWhite = false ; boolean reachedNonWhite = false ; int len = string . length ( ) ; int c ; for ( int i = 0 ; i < len ; i += Character . charCount ( c ) ) { c = string . codePointAt ( i ) ; if ( isActuallyWhitespace ( c ) ) { if ( ( stripLeading && ! reachedNonWhite ) || lastWasWhite ) continue ; accum . append ( ' ' ) ; lastWasWhite = true ; } else if ( ! isInvisibleChar ( c ) ) { accum . appendCodePoint ( c ) ; lastWasWhite = false ; reachedNonWhite = true ; } } }
After normalizing the whitespace within a string appends it to a string builder .
7,677
public static String releaseBuilder ( StringBuilder sb ) { Validate . notNull ( sb ) ; String string = sb . toString ( ) ; if ( sb . length ( ) > MaxCachedBuilderSize ) sb = new StringBuilder ( MaxCachedBuilderSize ) ; else sb . delete ( 0 , sb . length ( ) ) ; synchronized ( builders ) { builders . push ( sb ) ; while ( builders . size ( ) > MaxIdleBuilders ) { builders . pop ( ) ; } } return string ; }
Release a borrowed builder . Care must be taken not to use the builder after it has been returned as its contents may be changed by this method or by a concurrent thread .
7,678
public static Document load ( File in , String charsetName , String baseUri ) throws IOException { return parseInputStream ( new FileInputStream ( in ) , charsetName , baseUri , Parser . htmlParser ( ) ) ; }
Loads a file to a Document .
7,679
public static Document load ( InputStream in , String charsetName , String baseUri ) throws IOException { return parseInputStream ( in , charsetName , baseUri , Parser . htmlParser ( ) ) ; }
Parses a Document from an input steam .
7,680
static void crossStreams ( final InputStream in , final OutputStream out ) throws IOException { final byte [ ] buffer = new byte [ bufferSize ] ; int len ; while ( ( len = in . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , len ) ; } }
Writes the input stream to the output stream . Doesn t close them .
7,681
public static ByteBuffer readToByteBuffer ( InputStream inStream , int maxSize ) throws IOException { Validate . isTrue ( maxSize >= 0 , "maxSize must be 0 (unlimited) or larger" ) ; final ConstrainableInputStream input = ConstrainableInputStream . wrap ( inStream , bufferSize , maxSize ) ; return input . readToByteBuffer ( maxSize ) ; }
Read the input stream into a byte buffer . To deal with slow input streams you may interrupt the thread this method is executing on . The data read until being interrupted will be available .
7,682
static String mimeBoundary ( ) { final StringBuilder mime = StringUtil . borrowBuilder ( ) ; final Random rand = new Random ( ) ; for ( int i = 0 ; i < boundaryLength ; i ++ ) { mime . append ( mimeBoundaryChars [ rand . nextInt ( mimeBoundaryChars . length ) ] ) ; } return StringUtil . releaseBuilder ( mime ) ; }
Creates a random string suitable for use as a mime boundary
7,683
public boolean hasAttr ( String attributeKey ) { for ( Element element : this ) { if ( element . hasAttr ( attributeKey ) ) return true ; } return false ; }
Checks if any of the matched elements have this attribute defined .
7,684
public List < String > eachAttr ( String attributeKey ) { List < String > attrs = new ArrayList < > ( size ( ) ) ; for ( Element element : this ) { if ( element . hasAttr ( attributeKey ) ) attrs . add ( element . attr ( attributeKey ) ) ; } return attrs ; }
Get the attribute value for each of the matched elements . If an element does not have this attribute no value is included in the result set for that element .
7,685
public Elements attr ( String attributeKey , String attributeValue ) { for ( Element element : this ) { element . attr ( attributeKey , attributeValue ) ; } return this ; }
Set an attribute on all matched elements .
7,686
public List < String > eachText ( ) { ArrayList < String > texts = new ArrayList < > ( size ( ) ) ; for ( Element el : this ) { if ( el . hasText ( ) ) texts . add ( el . text ( ) ) ; } return texts ; }
Get the text content of each of the matched elements . If an element has no text then it is not included in the result .
7,687
public String html ( ) { StringBuilder sb = StringUtil . borrowBuilder ( ) ; for ( Element element : this ) { if ( sb . length ( ) != 0 ) sb . append ( "\n" ) ; sb . append ( element . html ( ) ) ; } return StringUtil . releaseBuilder ( sb ) ; }
Get the combined inner HTML of all matched elements .
7,688
public boolean is ( String query ) { Evaluator eval = QueryParser . parse ( query ) ; for ( Element e : this ) { if ( e . is ( eval ) ) return true ; } return false ; }
Test if any of the matched elements match the supplied query .
7,689
public Elements parents ( ) { HashSet < Element > combo = new LinkedHashSet < > ( ) ; for ( Element e : this ) { combo . addAll ( e . parents ( ) ) ; } return new Elements ( combo ) ; }
Get all of the parents and ancestor elements of the matched elements .
7,690
public Element appendChild ( Node child ) { Validate . notNull ( child ) ; reparentChild ( child ) ; ensureChildNodes ( ) ; childNodes . add ( child ) ; child . setSiblingIndex ( childNodes . size ( ) - 1 ) ; return this ; }
Add a node child node to this element .
7,691
public Element appendElement ( String tagName ) { Element child = new Element ( Tag . valueOf ( tagName , NodeUtils . parser ( this ) . settings ( ) ) , baseUri ( ) ) ; appendChild ( child ) ; return child ; }
Create a new element by tag name and add it as the last child .
7,692
public Element prependElement ( String tagName ) { Element child = new Element ( Tag . valueOf ( tagName , NodeUtils . parser ( this ) . settings ( ) ) , baseUri ( ) ) ; prependChild ( child ) ; return child ; }
Create a new element by tag name and add it as the first child .
7,693
public Element appendText ( String text ) { Validate . notNull ( text ) ; TextNode node = new TextNode ( text ) ; appendChild ( node ) ; return this ; }
Create and append a new TextNode to this element .
7,694
public Element prependText ( String text ) { Validate . notNull ( text ) ; TextNode node = new TextNode ( text ) ; prependChild ( node ) ; return this ; }
Create and prepend a new TextNode to this element .
7,695
public Element prepend ( String html ) { Validate . notNull ( html ) ; List < Node > nodes = NodeUtils . parser ( this ) . parseFragmentInput ( html , this , baseUri ( ) ) ; addChildren ( 0 , nodes . toArray ( new Node [ 0 ] ) ) ; return this ; }
Add inner HTML into this element . The supplied HTML will be parsed and each node prepended to the start of the element s children .
7,696
public Elements siblingElements ( ) { if ( parentNode == null ) return new Elements ( 0 ) ; List < Element > elements = parent ( ) . childElementsList ( ) ; Elements siblings = new Elements ( elements . size ( ) - 1 ) ; for ( Element el : elements ) if ( el != this ) siblings . add ( el ) ; return siblings ; }
Get sibling elements . If the element has no sibling elements returns an empty list . An element is not a sibling of itself so will not be included in the returned list .
7,697
public Element lastElementSibling ( ) { List < Element > siblings = parent ( ) . childElementsList ( ) ; return siblings . size ( ) > 1 ? siblings . get ( siblings . size ( ) - 1 ) : null ; }
Gets the last element sibling of this element
7,698
public Elements getElementsByTag ( String tagName ) { Validate . notEmpty ( tagName ) ; tagName = normalize ( tagName ) ; return Collector . collect ( new Evaluator . Tag ( tagName ) , this ) ; }
Finds elements including and recursively under this element with the specified tag name .
7,699
public Elements getElementsByAttribute ( String key ) { Validate . notEmpty ( key ) ; key = key . trim ( ) ; return Collector . collect ( new Evaluator . Attribute ( key ) , this ) ; }
Find elements that have a named attribute set . Case insensitive .