idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
23,600
public void sendEventsFromQueue ( ) { if ( null == queue || stopSending ) { return ; } LOG . fine ( "Scheduler called for sending events" ) ; int packageSize = getEventsPerMessageCall ( ) ; while ( ! queue . isEmpty ( ) ) { final List < Event > list = new ArrayList < Event > ( ) ; int i = 0 ; while ( i < packageSize &&...
Method will be executed asynchronously .
23,601
private void sendEvents ( final List < Event > events ) { if ( null != handlers ) { for ( EventHandler current : handlers ) { for ( Event event : events ) { current . handleEvent ( event ) ; } } } LOG . info ( "Put events(" + events . size ( ) + ") to Monitoring Server." ) ; try { if ( sendToEventadmin ) { EventAdminPu...
Sends the events to monitoring service client .
23,602
public void start ( String [ ] arguments ) { boolean notStarted = ! started . getAndSet ( true ) ; if ( notStarted ) { start ( new SingleInstanceWorkloadStrategy ( job , name , arguments , endpointRegistry , execService ) ) ; } }
Starts the one and only job instance in a separate Thread . Should be called exactly one time before the operation is stopped .
23,603
public static void writeCorrelationId ( Message message , String correlationId ) { Map < String , List < String > > headers = getOrCreateProtocolHeader ( message ) ; headers . put ( CORRELATIONID_HTTP_HEADER_NAME , Collections . singletonList ( correlationId ) ) ; if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine (...
Write correlation id .
23,604
public static String readFlowId ( Message message ) { String flowId = null ; Map < String , List < String > > headers = getOrCreateProtocolHeader ( message ) ; List < String > flowIds = headers . get ( FLOWID_HTTP_HEADER_NAME ) ; if ( flowIds != null && flowIds . size ( ) > 0 ) { flowId = flowIds . get ( 0 ) ; if ( LOG...
Read flow id from message .
23,605
public static void writeFlowId ( Message message , String flowId ) { Map < String , List < String > > headers = getOrCreateProtocolHeader ( message ) ; headers . put ( FLOWID_HTTP_HEADER_NAME , Collections . singletonList ( flowId ) ) ; if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "HTTP header '" + FLOWID_HT...
Write flow id .
23,606
public static void addInterceptors ( InterceptorProvider provider ) { PhaseManager phases = BusFactory . getDefaultBus ( ) . getExtension ( PhaseManager . class ) ; for ( Phase p : phases . getInPhases ( ) ) { provider . getInInterceptors ( ) . add ( new DemoInterceptor ( p . getName ( ) ) ) ; provider . getInFaultInte...
This method will add a DemoInterceptor into every in and every out phase of the interceptor chains .
23,607
private boolean somethingMayHaveChanged ( PhaseInterceptorChain pic ) { Iterator < Interceptor < ? extends Message > > it = pic . iterator ( ) ; Interceptor < ? extends Message > last = null ; while ( it . hasNext ( ) ) { Interceptor < ? extends Message > cur = it . next ( ) ; if ( cur == this ) { if ( last instanceof ...
as we know nothing has changed .
23,608
public void printInterceptorChain ( InterceptorChain chain ) { Iterator < Interceptor < ? extends Message > > it = chain . iterator ( ) ; String phase = "" ; StringBuilder builder = null ; while ( it . hasNext ( ) ) { Interceptor < ? extends Message > interceptor = it . next ( ) ; if ( interceptor instanceof DemoInterc...
Prints out the interceptor chain in a format that is easy to read . It also filters out instances of the DemoInterceptor so you can see what the chain would look like in a normal invokation .
23,609
public com . squareup . okhttp . Call getCharactersCharacterIdShipCall ( Integer characterId , String datasource , String ifNoneMatch , String token , final ApiCallback callback ) throws ApiException { Object localVarPostBody = new Object ( ) ; String localVarPath = "/v1/characters/{character_id}/ship/" . replaceAll ( ...
Build call for getCharactersCharacterIdShip
23,610
public String getAuthorizationUri ( final String redirectUri , final Set < String > scopes , final String state ) { if ( account == null ) throw new IllegalArgumentException ( "Auth is not set" ) ; if ( account . getClientId ( ) == null ) throw new IllegalArgumentException ( "client_id is not set" ) ; StringBuilder bui...
Get the authorization uri where the user logs in .
23,611
public void finishFlow ( final String code , final String state ) throws ApiException { if ( account == null ) throw new IllegalArgumentException ( "Auth is not set" ) ; if ( codeVerifier == null ) throw new IllegalArgumentException ( "code_verifier is not set" ) ; if ( account . getClientId ( ) == null ) throw new Ill...
Finish the oauth flow after the user was redirected back .
23,612
public ApiResponse < String > getPingWithHttpInfo ( ) throws ApiException { com . squareup . okhttp . Call call = getPingValidateBeforeCall ( null ) ; Type localVarReturnType = new TypeToken < String > ( ) { } . getType ( ) ; return apiClient . execute ( call , localVarReturnType ) ; }
Ping route Ping the ESI routers
23,613
public ApiClient setHttpClient ( OkHttpClient newHttpClient ) { if ( ! httpClient . equals ( newHttpClient ) ) { newHttpClient . networkInterceptors ( ) . addAll ( httpClient . networkInterceptors ( ) ) ; httpClient . networkInterceptors ( ) . clear ( ) ; newHttpClient . interceptors ( ) . addAll ( httpClient . interce...
Set HTTP client
23,614
private void addProgressInterceptor ( ) { httpClient . networkInterceptors ( ) . add ( new Interceptor ( ) { public Response intercept ( Interceptor . Chain chain ) throws IOException { final Request request = chain . request ( ) ; final Response originalResponse = chain . proceed ( request ) ; if ( request . tag ( ) i...
Add network interceptor to httpClient to track download progress for async requests .
23,615
public com . squareup . okhttp . Call postUiAutopilotWaypointCall ( Boolean addToBeginning , Boolean clearOtherWaypoints , Long destinationId , String datasource , String token , final ApiCallback callback ) throws ApiException { Object localVarPostBody = new Object ( ) ; String localVarPath = "/v2/ui/autopilot/waypoin...
Build call for postUiAutopilotWaypoint
23,616
public void setColorSchemeResources ( int ... colorResIds ) { final Resources res = getResources ( ) ; int [ ] colorRes = new int [ colorResIds . length ] ; for ( int i = 0 ; i < colorResIds . length ; i ++ ) { colorRes [ i ] = res . getColor ( colorResIds [ i ] ) ; } setColorSchemeColors ( colorRes ) ; }
Set the color resources used in the progress animation from color resources . The first color will also be the color of the bar that grows in response to a user swipe gesture .
23,617
public void setBackgroundColor ( int colorRes ) { if ( getBackground ( ) instanceof ShapeDrawable ) { final Resources res = getResources ( ) ; ( ( ShapeDrawable ) getBackground ( ) ) . getPaint ( ) . setColor ( res . getColor ( colorRes ) ) ; } }
Update the background color of the mBgCircle image view .
23,618
private void logBinaryStringInfo ( StringBuilder binaryString ) { encodeInfo += "Binary Length: " + binaryString . length ( ) + "\n" ; encodeInfo += "Binary String: " ; int nibble = 0 ; for ( int i = 0 ; i < binaryString . length ( ) ; i ++ ) { switch ( i % 4 ) { case 0 : if ( binaryString . charAt ( i ) == '1' ) { nib...
Logs binary string as hexadecimal
23,619
private int combineSubsetBlocks ( Mode [ ] mode_type , int [ ] mode_length , int index_point ) { if ( index_point > 1 ) { for ( int i = 1 ; i < index_point ; i ++ ) { if ( mode_type [ i - 1 ] == mode_type [ i ] ) { mode_length [ i - 1 ] = mode_length [ i - 1 ] + mode_length [ i ] ; for ( int j = i + 1 ; j < index_point...
Modifies the specified mode and length arrays to combine adjacent modes of the same type returning the updated index point .
23,620
public static void main ( String [ ] args ) { Settings settings = new Settings ( ) ; new JCommander ( settings , args ) ; if ( ! settings . isGuiSupressed ( ) ) { OkapiUI okapiUi = new OkapiUI ( ) ; okapiUi . setVisible ( true ) ; } else { int returnValue ; returnValue = commandLine ( settings ) ; if ( returnValue != 0...
Starts the Okapi Barcode UI .
23,621
private int [ ] getPrimaryCodewords ( ) { assert mode == 2 || mode == 3 ; if ( primaryData . length ( ) != 15 ) { throw new OkapiException ( "Invalid Primary String" ) ; } for ( int i = 9 ; i < 15 ; i ++ ) { if ( primaryData . charAt ( i ) < '0' || primaryData . charAt ( i ) > '9' ) { throw new OkapiException ( "Invali...
Extracts the postal code country code and service code from the primary data and returns the corresponding primary message codewords .
23,622
private static int [ ] getMode2PrimaryCodewords ( String postcode , int country , int service ) { for ( int i = 0 ; i < postcode . length ( ) ; i ++ ) { if ( postcode . charAt ( i ) < '0' || postcode . charAt ( i ) > '9' ) { postcode = postcode . substring ( 0 , i ) ; break ; } } int postcodeNum = Integer . parseInt ( ...
Returns the primary message codewords for mode 2 .
23,623
private static int [ ] getMode3PrimaryCodewords ( String postcode , int country , int service ) { int [ ] postcodeNums = new int [ postcode . length ( ) ] ; postcode = postcode . toUpperCase ( ) ; for ( int i = 0 ; i < postcodeNums . length ; i ++ ) { postcodeNums [ i ] = postcode . charAt ( i ) ; if ( postcode . charA...
Returns the primary message codewords for mode 3 .
23,624
private int bestSurroundingSet ( int index , int length , int ... valid ) { int option1 = set [ index - 1 ] ; if ( index + 1 < length ) { int option2 = set [ index + 1 ] ; if ( contains ( valid , option1 ) && contains ( valid , option2 ) ) { return Math . min ( option1 , option2 ) ; } else if ( contains ( valid , optio...
Guesses the best set to use at the specified index by looking at the surrounding sets . In general characters in lower - numbered sets are more common so we choose them if we can . If no good surrounding sets can be found the default value returned is the first value from the valid set .
23,625
private void insert ( int position , int c ) { for ( int i = 143 ; i > position ; i -- ) { set [ i ] = set [ i - 1 ] ; character [ i ] = character [ i - 1 ] ; } character [ position ] = c ; }
Moves everything up so that the specified shift or latch character can be inserted .
23,626
private static int [ ] getErrorCorrection ( int [ ] codewords , int ecclen ) { ReedSolomon rs = new ReedSolomon ( ) ; rs . init_gf ( 0x43 ) ; rs . init_code ( ecclen , 1 ) ; rs . encode ( codewords . length , codewords ) ; int [ ] results = new int [ ecclen ] ; for ( int i = 0 ; i < ecclen ; i ++ ) { results [ i ] = rs...
Returns the error correction codewords for the specified data codewords .
23,627
public void setStructuredAppendMessageId ( String messageId ) { if ( messageId != null && ! messageId . matches ( "^[\\x21-\\x7F]+$" ) ) { throw new IllegalArgumentException ( "Invalid Aztec Code structured append message ID: " + messageId ) ; } this . structuredAppendMessageId = messageId ; }
If this Aztec Code symbol is part of a series of Aztec Code symbols appended in a structured format this method sets the unique message ID for the series . Values may not contain spaces and must contain only printable ASCII characters . Message IDs are optional .
23,628
private void addErrorCorrection ( StringBuilder adjustedString , int codewordSize , int dataBlocks , int eccBlocks ) { int x , poly , startWeight ; switch ( codewordSize ) { case 6 : x = 32 ; poly = 0x43 ; startWeight = 0x20 ; break ; case 8 : x = 128 ; poly = 0x12d ; startWeight = 0x80 ; break ; case 10 : x = 512 ; po...
Adds error correction data to the specified binary string which already contains the primary data
23,629
public ExtendedOutputStreamWriter append ( double d ) throws IOException { super . append ( String . format ( Locale . ROOT , doubleFormat , d ) ) ; return this ; }
Writes the specified double to the stream formatted according to the format specified in the constructor .
23,630
public static int positionOf ( char value , char [ ] array ) { for ( int i = 0 ; i < array . length ; i ++ ) { if ( value == array [ i ] ) { return i ; } } throw new OkapiException ( "Unable to find character '" + value + "' in character array." ) ; }
Returns the position of the specified value in the specified array .
23,631
public static int [ ] insertArray ( int [ ] original , int index , int [ ] inserted ) { int [ ] modified = new int [ original . length + inserted . length ] ; System . arraycopy ( original , 0 , modified , 0 , index ) ; System . arraycopy ( inserted , 0 , modified , index , inserted . length ) ; System . arraycopy ( or...
Inserts the specified array into the specified original array at the specified index .
23,632
private static int getBinaryLength ( int version , QrMode [ ] inputModeUnoptimized , int [ ] inputData , boolean gs1 , int eciMode ) { int i , j ; QrMode currentMode ; int inputLength = inputModeUnoptimized . length ; int count = 0 ; int alphaLength ; int percent = 0 ; QrMode [ ] inputMode = applyOptimisation ( version...
Calculate the actual bit length of the proposed binary string .
23,633
private static int blockLength ( int start , QrMode [ ] inputMode ) { QrMode mode = inputMode [ start ] ; int count = 0 ; int i = start ; do { count ++ ; } while ( ( ( i + count ) < inputMode . length ) && ( inputMode [ i + count ] == mode ) ) ; return count ; }
Find the length of the block starting from start .
23,634
private static int tribus ( int version , int a , int b , int c ) { if ( version < 10 ) { return a ; } else if ( version >= 10 && version <= 26 ) { return b ; } else { return c ; } }
Choose from three numbers based on version .
23,635
private static void addEcc ( int [ ] fullstream , int [ ] datastream , int version , int data_cw , int blocks ) { int ecc_cw = QR_TOTAL_CODEWORDS [ version - 1 ] - data_cw ; int short_data_block_length = data_cw / blocks ; int qty_long_blocks = data_cw % blocks ; int qty_short_blocks = blocks - qty_long_blocks ; int ec...
Splits data into blocks adds error correction and then interleaves the blocks and error correction data .
23,636
private static void addFormatInfoEval ( byte [ ] eval , int size , EccLevel ecc_level , int pattern ) { int format = pattern ; int seq ; int i ; switch ( ecc_level ) { case L : format += 0x08 ; break ; case Q : format += 0x18 ; break ; case H : format += 0x10 ; break ; } seq = QR_ANNEX_C [ format ] ; for ( i = 0 ; i < ...
Adds format information to eval .
23,637
private static void addVersionInfo ( byte [ ] grid , int size , int version ) { long version_data = QR_ANNEX_D [ version - 7 ] ; for ( int i = 0 ; i < 6 ; i ++ ) { grid [ ( ( size - 11 ) * size ) + i ] += ( version_data >> ( i * 3 ) ) & 0x01 ; grid [ ( ( size - 10 ) * size ) + i ] += ( version_data >> ( ( i * 3 ) + 1 )...
Adds version information .
23,638
private static List < Block > createBlocks ( int [ ] data , boolean debug ) { List < Block > blocks = new ArrayList < > ( ) ; Block current = null ; for ( int i = 0 ; i < data . length ; i ++ ) { EncodingMode mode = chooseMode ( data [ i ] ) ; if ( ( current != null && current . mode == mode ) && ( mode != EncodingMode...
Determines the encoding block groups for the specified data .
23,639
private static void mergeBlocks ( List < Block > blocks ) { for ( int i = 1 ; i < blocks . size ( ) ; i ++ ) { Block b1 = blocks . get ( i - 1 ) ; Block b2 = blocks . get ( i ) ; if ( ( b1 . mode == b2 . mode ) && ( b1 . mode != EncodingMode . NUM || b1 . length + b2 . length <= MAX_NUMERIC_COMPACTION_BLOCK_SIZE ) ) { ...
Combines adjacent blocks of the same type .
23,640
protected void eciProcess ( ) { EciMode eci = EciMode . of ( content , "ISO8859_1" , 3 ) . or ( content , "ISO8859_2" , 4 ) . or ( content , "ISO8859_3" , 5 ) . or ( content , "ISO8859_4" , 6 ) . or ( content , "ISO8859_5" , 7 ) . or ( content , "ISO8859_6" , 8 ) . or ( content , "ISO8859_7" , 9 ) . or ( content , "ISO...
Chooses the ECI mode most suitable for the content of this symbol .
23,641
protected void mergeVerticalBlocks ( ) { for ( int i = 0 ; i < rectangles . size ( ) - 1 ; i ++ ) { for ( int j = i + 1 ; j < rectangles . size ( ) ; j ++ ) { Rectangle2D . Double firstRect = rectangles . get ( i ) ; Rectangle2D . Double secondRect = rectangles . get ( j ) ; if ( roughlyEqual ( firstRect . x , secondRe...
Search for rectangles which have the same width and x position and which join together vertically and merge them together to reduce the number of rectangles needed to describe a symbol .
23,642
private String hibcProcess ( String source ) { if ( source . length ( ) > 110 ) { throw new OkapiException ( "Data too long for HIBC LIC" ) ; } source = source . toUpperCase ( ) ; if ( ! source . matches ( "[A-Z0-9-\\. \\$/+\\%]+?" ) ) { throw new OkapiException ( "Invalid characters in input" ) ; } int counter = 41 ; ...
Adds the HIBC prefix and check digit to the specified data returning the resultant data string .
23,643
protected int [ ] getPatternAsCodewords ( int size ) { if ( size >= 10 ) { throw new IllegalArgumentException ( "Pattern groups of 10 or more digits are likely to be too large to parse as integers." ) ; } if ( pattern == null || pattern . length == 0 ) { return new int [ 0 ] ; } else { int count = ( int ) Math . ceil (...
Returns this bar code s pattern converted into a set of corresponding codewords . Useful for bar codes that encode their content as a pattern .
23,644
private static double arcAngle ( Point center , Point a , Point b , Rect area , int radius ) { double angle = threePointsAngle ( center , a , b ) ; Point innerPoint = findMidnormalPoint ( center , a , b , area , radius ) ; Point midInsectPoint = new Point ( ( a . x + b . x ) / 2 , ( a . y + b . y ) / 2 ) ; double dista...
calculate arc angle between point a and point b
23,645
private static Point findMidnormalPoint ( Point center , Point a , Point b , Rect area , int radius ) { if ( a . y == b . y ) { if ( a . y < center . y ) { return new Point ( ( a . x + b . x ) / 2 , center . y + radius ) ; } return new Point ( ( a . x + b . x ) / 2 , center . y - radius ) ; } if ( a . x == b . x ) { if...
find the middle point of two intersect points in circle only one point will be correct
23,646
public static boolean inArea ( Point point , Rect area , float offsetRatio ) { int offset = ( int ) ( area . width ( ) * offsetRatio ) ; return point . x >= area . left - offset && point . x <= area . right + offset && point . y >= area . top - offset && point . y <= area . bottom + offset ; }
judge if an point in the area or not
23,647
private static double threePointsAngle ( Point vertex , Point A , Point B ) { double b = pointsDistance ( vertex , A ) ; double c = pointsDistance ( A , B ) ; double a = pointsDistance ( B , vertex ) ; return Math . toDegrees ( Math . acos ( ( a * a + b * b - c * c ) / ( 2 * a * b ) ) ) ; }
calculate the point a s angle of rectangle consist of point a point b point c ;
23,648
private static double pointsDistance ( Point a , Point b ) { int dx = b . x - a . x ; int dy = b . y - a . y ; return Math . sqrt ( dx * dx + dy * dy ) ; }
calculate distance of two points
23,649
private void calculateMenuItemPosition ( ) { float itemRadius = ( expandedRadius + collapsedRadius ) / 2 , f ; RectF area = new RectF ( center . x - itemRadius , center . y - itemRadius , center . x + itemRadius , center . y + itemRadius ) ; Path path = new Path ( ) ; path . addArc ( area , ( float ) fromAngle , ( floa...
calculate and set position to menu items
23,650
private boolean isClockwise ( Point center , Point a , Point b ) { double cross = ( a . x - center . x ) * ( b . y - center . y ) - ( b . x - center . x ) * ( a . y - center . y ) ; return cross > 0 ; }
judge a - > b is ordered clockwise
23,651
public void inputValues ( boolean ... values ) { for ( boolean value : values ) { InputValue inputValue = new InputValue ( ) ; inputValue . setChecked ( value ) ; this . inputValues . add ( inputValue ) ; } }
Sets the values of this input field . Only Applicable check - boxes and a radio buttons .
23,652
public void clearTmpData ( ) { for ( Enumeration < ? > e = breadthFirstEnumeration ( ) ; e . hasMoreElements ( ) ; ) { ( ( LblTree ) e . nextElement ( ) ) . setTmpData ( null ) ; } }
Clear tmpData in subtree rooted in this node .
23,653
public static String getXPathExpression ( Node node ) { Object xpathCache = node . getUserData ( FULL_XPATH_CACHE ) ; if ( xpathCache != null ) { return xpathCache . toString ( ) ; } Node parent = node . getParentNode ( ) ; if ( ( parent == null ) || parent . getNodeName ( ) . contains ( "#document" ) ) { String xPath ...
Reverse Engineers an XPath Expression of a given Node in the DOM .
23,654
public static List < Node > getSiblings ( Node parent , Node element ) { List < Node > result = new ArrayList < > ( ) ; NodeList list = parent . getChildNodes ( ) ; for ( int i = 0 ; i < list . getLength ( ) ; i ++ ) { Node el = list . item ( i ) ; if ( el . getNodeName ( ) . equals ( element . getNodeName ( ) ) ) { re...
Get siblings of the same type as element from parent .
23,655
public static NodeList evaluateXpathExpression ( String domStr , String xpathExpr ) throws XPathExpressionException , IOException { Document dom = DomUtils . asDocument ( domStr ) ; return evaluateXpathExpression ( dom , xpathExpr ) ; }
Returns the list of nodes which match the expression xpathExpr in the String domStr .
23,656
public static NodeList evaluateXpathExpression ( Document dom , String xpathExpr ) throws XPathExpressionException { XPathFactory factory = XPathFactory . newInstance ( ) ; XPath xpath = factory . newXPath ( ) ; XPathExpression expr = xpath . compile ( xpathExpr ) ; Object result = expr . evaluate ( dom , XPathConstant...
Returns the list of nodes which match the expression xpathExpr in the Document dom .
23,657
public static int getXPathLocation ( String dom , String xpath ) { String dom_lower = dom . toLowerCase ( ) ; String xpath_lower = xpath . toLowerCase ( ) ; String [ ] elements = xpath_lower . split ( "/" ) ; int pos = 0 ; int temp ; int number ; for ( String element : elements ) { if ( ! element . isEmpty ( ) && ! ele...
returns position of xpath element which match the expression xpath in the String dom .
23,658
double getThreshold ( String x , String y , double p ) { return 2 * Math . max ( x . length ( ) , y . length ( ) ) * ( 1 - p ) ; }
Calculate a threshold .
23,659
public boolean check ( EmbeddedBrowser browser ) { String js = "try{ if(" + expression + "){return '1';}else{" + "return '0';}}catch(e){" + " return '0';}" ; try { Object object = browser . executeJavaScript ( js ) ; if ( object == null ) { return false ; } return object . toString ( ) . equals ( "1" ) ; } catch ( Craw...
Check invariant .
23,660
public static void objectToXML ( Object object , String fileName ) throws FileNotFoundException { FileOutputStream fo = new FileOutputStream ( fileName ) ; XMLEncoder encoder = new XMLEncoder ( fo ) ; encoder . writeObject ( object ) ; encoder . close ( ) ; }
Converts an object to an XML file .
23,661
public static Object xmlToObject ( String fileName ) throws FileNotFoundException { FileInputStream fi = new FileInputStream ( fileName ) ; XMLDecoder decoder = new XMLDecoder ( fi ) ; Object object = decoder . readObject ( ) ; decoder . close ( ) ; return object ; }
Converts an XML file to an object .
23,662
public By getWebDriverBy ( ) { switch ( how ) { case name : return By . name ( this . value ) ; case xpath : return By . xpath ( this . value . replaceAll ( "/BODY\\[1\\]/" , "/BODY/" ) ) ; case id : return By . id ( this . value ) ; case tag : return By . tagName ( this . value ) ; case text : return By . linkText ( t...
Convert a Identification to a By used in WebDriver Drivers .
23,663
protected String escapeApostrophes ( String text ) { String resultString ; if ( text . contains ( "'" ) ) { StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder . append ( "concat('" ) ; stringBuilder . append ( text . replace ( "'" , "',\"'\",'" ) ) ; stringBuilder . append ( "')" ) ; resultString = str...
Returns a string to resolve apostrophe issue in xpath
23,664
public CrawlSession call ( ) { setMaximumCrawlTimeIfNeeded ( ) ; plugins . runPreCrawlingPlugins ( config ) ; CrawlTaskConsumer firstConsumer = consumerFactory . get ( ) ; StateVertex firstState = firstConsumer . crawlIndex ( ) ; crawlSessionProvider . setup ( firstState ) ; plugins . runOnNewStatePlugins ( firstConsum...
Run the configured crawl . This method blocks until the crawl is done .
23,665
public ImmutableList < CandidateElement > extract ( StateVertex currentState ) throws CrawljaxException { LinkedList < CandidateElement > results = new LinkedList < > ( ) ; if ( ! checkedElements . checkCrawlCondition ( browser ) ) { LOG . info ( "State {} did not satisfy the CrawlConditions." , currentState . getName ...
This method extracts candidate elements from the current DOM tree in the browser based on the crawl tags defined by the user .
23,666
private ImmutableList < Element > getNodeListForTagElement ( Document dom , CrawlElement crawlElement , EventableConditionChecker eventableConditionChecker ) { Builder < Element > result = ImmutableList . builder ( ) ; if ( crawlElement . getTagName ( ) == null ) { return result . build ( ) ; } EventableCondition event...
Returns a list of Elements form the DOM tree matching the tag element .
23,667
public void runOnInvariantViolationPlugins ( Invariant invariant , CrawlerContext context ) { LOGGER . debug ( "Running OnInvariantViolationPlugins..." ) ; counters . get ( OnInvariantViolationPlugin . class ) . inc ( ) ; for ( Plugin plugin : plugins . get ( OnInvariantViolationPlugin . class ) ) { if ( plugin instanc...
Run the OnInvariantViolation plugins when an Invariant is violated . Invariant are checked when the state machine is updated that is when the dom is changed after a click on a clickable . When a invariant fails this kind of plugins are executed . Warning the session is not a clone changing the session can cause strange...
23,668
public void runOnBrowserCreatedPlugins ( EmbeddedBrowser newBrowser ) { LOGGER . debug ( "Running OnBrowserCreatedPlugins..." ) ; counters . get ( OnBrowserCreatedPlugin . class ) . inc ( ) ; for ( Plugin plugin : plugins . get ( OnBrowserCreatedPlugin . class ) ) { if ( plugin instanceof OnBrowserCreatedPlugin ) { LOG...
Load and run the OnBrowserCreatedPlugins this call has been made from the browser pool when a new browser has been created and ready to be used by the Crawler . The PreCrawling plugins are executed before these plugins are executed except that the pre - crawling plugins are only executed on the first created browser .
23,669
public boolean equalId ( Element otherElement ) { if ( getElementId ( ) == null || otherElement . getElementId ( ) == null ) { return false ; } return getElementId ( ) . equalsIgnoreCase ( otherElement . getElementId ( ) ) ; }
Are both Id s the same?
23,670
public String getElementId ( ) { for ( Entry < String , String > attribute : attributes . entrySet ( ) ) { if ( attribute . getKey ( ) . equalsIgnoreCase ( "id" ) ) { return attribute . getValue ( ) ; } } return null ; }
Search for the attribute id and return the value .
23,671
public boolean checkXpathStartsWithXpathEventableCondition ( Document dom , EventableCondition eventableCondition , String xpath ) throws XPathExpressionException { if ( eventableCondition == null || Strings . isNullOrEmpty ( eventableCondition . getInXPath ( ) ) ) { throw new CrawljaxException ( "Eventable has no XPat...
Checks whether an XPath expression starts with an XPath eventable condition .
23,672
public static double getRobustTreeEditDistance ( String dom1 , String dom2 ) { LblTree domTree1 = null , domTree2 = null ; try { domTree1 = getDomTree ( dom1 ) ; domTree2 = getDomTree ( dom2 ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } double DD = 0.0 ; RTED_InfoTree_Opt rted ; double ted ; rted = new RT...
Get a scalar value for the DOM diversity using the Robust Tree Edit Distance
23,673
private static LblTree createTree ( TreeWalker walker ) { Node parent = walker . getCurrentNode ( ) ; LblTree node = new LblTree ( parent . getNodeName ( ) , - 1 ) ; for ( Node n = walker . firstChild ( ) ; n != null ; n = walker . nextSibling ( ) ) { node . add ( createTree ( walker ) ) ; } walker . setCurrentNode ( p...
Recursively construct a LblTree from DOM tree
23,674
public ExcludeByParentBuilder dontClickChildrenOf ( String tagName ) { checkNotRead ( ) ; Preconditions . checkNotNull ( tagName ) ; ExcludeByParentBuilder exclude = new ExcludeByParentBuilder ( tagName . toUpperCase ( ) ) ; crawlParentsExcluded . add ( exclude ) ; return exclude ; }
Click no children of the specified parent element .
23,675
public FormInput inputField ( InputType type , Identification identification ) { FormInput input = new FormInput ( type , identification ) ; this . formInputs . add ( input ) ; return input ; }
Specifies an input field to assign a value to . Crawljax first tries to match the found HTML input element s id and then the name attribute .
23,676
private Options getOptions ( ) { Options options = new Options ( ) ; options . addOption ( "h" , HELP , false , "print this message" ) ; options . addOption ( VERSION , false , "print the version information and exit" ) ; options . addOption ( "b" , BROWSER , true , "browser type: " + availableBrowsers ( ) + ". Default...
Create the CML Options .
23,677
public static void directoryCheck ( String dir ) throws IOException { final File file = new File ( dir ) ; if ( ! file . exists ( ) ) { FileUtils . forceMkdir ( file ) ; } }
Checks the existence of the directory . If it does not exist the method creates it .
23,678
public static void checkFolderForFile ( String fileName ) throws IOException { if ( fileName . lastIndexOf ( File . separator ) > 0 ) { String folder = fileName . substring ( 0 , fileName . lastIndexOf ( File . separator ) ) ; directoryCheck ( folder ) ; } }
Checks whether the folder exists for fileName and creates it if necessary .
23,679
@ GuardedBy ( "elementsLock" ) public boolean markChecked ( CandidateElement element ) { String generalString = element . getGeneralString ( ) ; String uniqueString = element . getUniqueString ( ) ; synchronized ( elementsLock ) { if ( elements . contains ( uniqueString ) ) { return false ; } else { elements . add ( ge...
Mark a given element as checked to prevent duplicate work . A elements is only added when it is not already in the set of checked elements .
23,680
private void readFormDataFromFile ( ) { List < FormInput > formInputList = FormInputValueHelper . deserializeFormInputs ( config . getSiteDir ( ) ) ; if ( formInputList != null ) { InputSpecification inputSpecs = config . getCrawlRules ( ) . getInputSpecification ( ) ; for ( FormInput input : formInputList ) { inputSpe...
Reads input data from a JSON file in the output directory .
23,681
public CrawlSession call ( ) { Injector injector = Guice . createInjector ( new CoreModule ( config ) ) ; controller = injector . getInstance ( CrawlController . class ) ; CrawlSession session = controller . call ( ) ; reason = controller . getReason ( ) ; return session ; }
Runs Crawljax with the given configuration .
23,682
public static Integer distance ( String h1 , String h2 ) { HammingDistance distance = new HammingDistance ( ) ; return distance . apply ( h1 , h2 ) ; }
Calculate the Hamming distance between two hashes
23,683
public static synchronized FormInputValueHelper getInstance ( InputSpecification inputSpecification , FormFillMode formFillMode ) { if ( instance == null ) instance = new FormInputValueHelper ( inputSpecification , formFillMode ) ; return instance ; }
Creates or returns the instance of the helper class .
23,684
private FormInput formInputMatchingNode ( Node element ) { NamedNodeMap attributes = element . getAttributes ( ) ; Identification id ; if ( attributes . getNamedItem ( "id" ) != null && formFillMode != FormFillMode . XPATH_TRAINING ) { id = new Identification ( Identification . How . id , attributes . getNamedItem ( "i...
return the list of FormInputs that match this element
23,685
public void reset ( ) { CrawlSession session = context . getSession ( ) ; if ( crawlpath != null ) { session . addCrawlPath ( crawlpath ) ; } List < StateVertex > onURLSetTemp = new ArrayList < > ( ) ; if ( stateMachine != null ) onURLSetTemp = stateMachine . getOnURLSet ( ) ; stateMachine = new StateMachine ( graphPro...
Reset the crawler to its initial state .
23,686
private boolean fireEvent ( Eventable eventable ) { Eventable eventToFire = eventable ; if ( eventable . getIdentification ( ) . getHow ( ) . toString ( ) . equals ( "xpath" ) && eventable . getRelatedFrame ( ) . equals ( "" ) ) { eventToFire = resolveByXpath ( eventable , eventToFire ) ; } boolean isFired = false ; tr...
Try to fire a given event on the Browser .
23,687
public StateVertex crawlIndex ( ) { LOG . debug ( "Setting up vertex of the index page" ) ; if ( basicAuthUrl != null ) { browser . goToUrl ( basicAuthUrl ) ; } browser . goToUrl ( url ) ; plugins . runOnUrlFirstLoadPlugins ( context ) ; plugins . runOnUrlLoadPlugins ( context ) ; StateVertex index = vertexFactory . cr...
This method calls the index state . It should be called once per crawl in order to setup the crawl .
23,688
public double nonNormalizedTreeDist ( LblTree t1 , LblTree t2 ) { init ( t1 , t2 ) ; STR = new int [ size1 ] [ size2 ] ; computeOptimalStrategy ( ) ; return computeDistUsingStrArray ( it1 , it2 ) ; }
Computes the tree edit distance between trees t1 and t2 .
23,689
public void init ( LblTree t1 , LblTree t2 ) { LabelDictionary ld = new LabelDictionary ( ) ; it1 = new InfoTree ( t1 , ld ) ; it2 = new InfoTree ( t2 , ld ) ; size1 = it1 . getSize ( ) ; size2 = it2 . getSize ( ) ; IJ = new int [ Math . max ( size1 , size2 ) ] [ Math . max ( size1 , size2 ) ] ; delta = new double [ si...
Initialization method .
23,690
public boolean changeState ( StateVertex nextState ) { if ( nextState == null ) { LOGGER . info ( "nextState given is null" ) ; return false ; } LOGGER . debug ( "Trying to change to state: '{}' from: '{}'" , nextState . getName ( ) , currentState . getName ( ) ) ; if ( stateFlowGraph . canGoTo ( currentState , nextSta...
Change the currentState to the nextState if possible . The next state should already be present in the graph .
23,691
private StateVertex addStateToCurrentState ( StateVertex newState , Eventable eventable ) { LOGGER . debug ( "addStateToCurrentState currentState: {} newState {}" , currentState . getName ( ) , newState . getName ( ) ) ; StateVertex cloneState = stateFlowGraph . putIfAbsent ( newState ) ; if ( cloneState != null ) { LO...
Adds the newState and the edge between the currentState and the newState on the SFG .
23,692
public boolean switchToStateAndCheckIfClone ( final Eventable event , StateVertex newState , CrawlerContext context ) { StateVertex cloneState = this . addStateToCurrentState ( newState , event ) ; runOnInvariantViolationPlugins ( context ) ; if ( cloneState == null ) { changeState ( newState ) ; plugins . runOnNewStat...
Adds an edge between the current and new state .
23,693
@ SuppressWarnings ( "unchecked" ) static void logToFile ( String filename ) { Logger rootLogger = ( Logger ) LoggerFactory . getLogger ( org . slf4j . Logger . ROOT_LOGGER_NAME ) ; FileAppender < ILoggingEvent > fileappender = new FileAppender < > ( ) ; fileappender . setContext ( rootLogger . getLoggerContext ( ) ) ;...
Configure file logging and stop console logging .
23,694
public static void main ( String [ ] args ) { try { JarRunner runner = new JarRunner ( args ) ; runner . runIfConfigured ( ) ; } catch ( NumberFormatException e ) { System . err . println ( "Could not parse number " + e . getMessage ( ) ) ; System . exit ( 1 ) ; } catch ( RuntimeException e ) { System . err . println (...
Main executable method of Crawljax CLI .
23,695
public static String toPrettyJson ( Object o ) { try { return MAPPER . writerWithDefaultPrettyPrinter ( ) . writeValueAsString ( o ) ; } catch ( JsonProcessingException e ) { LoggerFactory . getLogger ( Serializer . class ) . error ( "Could not serialize the object. This will be ignored and the error will be written in...
Serialize the object JSON . When an error occures return a string with the given error .
23,696
private void postTraversalProcessing ( ) { int nc1 = treeSize ; info [ KR ] = new int [ leafCount ] ; info [ RKR ] = new int [ leafCount ] ; int lc = leafCount ; int i = 0 ; for ( i = 0 ; i < treeSize ; i ++ ) { if ( paths [ LEFT ] [ i ] == - 1 ) { info [ POST2_LLD ] [ i ] = i ; } else { info [ POST2_LLD ] [ i ] = info...
Gathers information that couldn t be collected while tree traversal .
23,697
static int [ ] toIntArray ( List < Integer > integers ) { int [ ] ints = new int [ integers . size ( ) ] ; int i = 0 ; for ( Integer n : integers ) { ints [ i ++ ] = n ; } return ints ; }
Transforms a list of Integer objects to an array of primitive int values .
23,698
public void onNewState ( CrawlerContext context , StateVertex vertex ) { LOG . debug ( "onNewState" ) ; StateBuilder state = outModelCache . addStateIfAbsent ( vertex ) ; visitedStates . putIfAbsent ( state . getName ( ) , vertex ) ; saveScreenshot ( context . getBrowser ( ) , state . getName ( ) , vertex ) ; outputBui...
Saves a screenshot of every new state .
23,699
public void preStateCrawling ( CrawlerContext context , ImmutableList < CandidateElement > candidateElements , StateVertex state ) { LOG . debug ( "preStateCrawling" ) ; List < CandidateElementPosition > newElements = Lists . newLinkedList ( ) ; LOG . info ( "Prestate found new state {} with {} candidates" , state . ge...
Logs all the canidate elements so that the plugin knows which elements were the candidate elements .