idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
147,000 | protected void processStart ( Endpoint endpoint , EventTypeEnum eventType ) { if ( ! sendLifecycleEvent ) { return ; } Event event = createEvent ( endpoint , eventType ) ; queue . add ( event ) ; } | Process start . | 50 | 3 |
147,001 | protected void processStop ( Endpoint endpoint , EventTypeEnum eventType ) { if ( ! sendLifecycleEvent ) { return ; } Event event = createEvent ( endpoint , eventType ) ; monitoringServiceClient . putEvents ( Collections . singletonList ( event ) ) ; if ( LOG . isLoggable ( Level . INFO ) ) { LOG . info ( "Send " + eventType + " event to SAM Server successful!" ) ; } } | Process stop . | 96 | 3 |
147,002 | private Event createEvent ( Endpoint endpoint , EventTypeEnum type ) { Event event = new Event ( ) ; MessageInfo messageInfo = new MessageInfo ( ) ; Originator originator = new Originator ( ) ; event . setMessageInfo ( messageInfo ) ; event . setOriginator ( originator ) ; Date date = new Date ( ) ; event . setTimestamp ( date ) ; event . setEventType ( type ) ; messageInfo . setPortType ( endpoint . getBinding ( ) . getBindingInfo ( ) . getService ( ) . getInterface ( ) . getName ( ) . toString ( ) ) ; String transportType = null ; if ( endpoint . getBinding ( ) instanceof SoapBinding ) { SoapBinding soapBinding = ( SoapBinding ) endpoint . getBinding ( ) ; if ( soapBinding . getBindingInfo ( ) instanceof SoapBindingInfo ) { SoapBindingInfo soapBindingInfo = ( SoapBindingInfo ) soapBinding . getBindingInfo ( ) ; transportType = soapBindingInfo . getTransportURI ( ) ; } } messageInfo . setTransportType ( ( transportType != null ) ? transportType : "Unknown transport type" ) ; originator . setProcessId ( Converter . getPID ( ) ) ; try { InetAddress inetAddress = InetAddress . getLocalHost ( ) ; originator . setIp ( inetAddress . getHostAddress ( ) ) ; originator . setHostname ( inetAddress . getHostName ( ) ) ; } catch ( UnknownHostException e ) { originator . setHostname ( "Unknown hostname" ) ; originator . setIp ( "Unknown ip address" ) ; } String address = endpoint . getEndpointInfo ( ) . getAddress ( ) ; event . getCustomInfo ( ) . put ( "address" , address ) ; return event ; } | Creates the event for endpoint with specific type . | 419 | 10 |
147,003 | public void useOldRESTService ( ) throws Exception { List < Object > providers = createJAXRSProviders ( ) ; com . example . customerservice . CustomerService customerService = JAXRSClientFactory . createFromModel ( "http://localhost:" + port + "/examples/direct/rest" , com . example . customerservice . CustomerService . class , "classpath:/model/CustomerService-jaxrs.xml" , providers , null ) ; System . out . println ( "Using old RESTful CustomerService with old client" ) ; customer . v1 . Customer customer = createOldCustomer ( "Smith Old REST" ) ; customerService . updateCustomer ( customer ) ; customer = customerService . getCustomerByName ( "Smith Old REST" ) ; printOldCustomerDetails ( customer ) ; } | Old REST client uses old REST service | 175 | 7 |
147,004 | public void useNewRESTService ( String address ) throws Exception { List < Object > providers = createJAXRSProviders ( ) ; org . customer . service . CustomerService customerService = JAXRSClientFactory . createFromModel ( address , org . customer . service . CustomerService . class , "classpath:/model/CustomerService-jaxrs.xml" , providers , null ) ; System . out . println ( "Using new RESTful CustomerService with new client" ) ; customer . v2 . Customer customer = createNewCustomer ( "Smith New REST" ) ; customerService . updateCustomer ( customer ) ; customer = customerService . getCustomerByName ( "Smith New REST" ) ; printNewCustomerDetails ( customer ) ; } | New REST client uses new REST service | 158 | 7 |
147,005 | public void useNewRESTServiceWithOldClient ( ) throws Exception { List < Object > providers = createJAXRSProviders ( ) ; com . example . customerservice . CustomerService customerService = JAXRSClientFactory . createFromModel ( "http://localhost:" + port + "/examples/direct/new-rest" , com . example . customerservice . CustomerService . class , "classpath:/model/CustomerService-jaxrs.xml" , providers , null ) ; // The outgoing old Customer data needs to be transformed for // the new service to understand it and the response from the new service // needs to be transformed for this old client to understand it. ClientConfiguration config = WebClient . getConfig ( customerService ) ; addTransformInterceptors ( config . getInInterceptors ( ) , config . getOutInterceptors ( ) , false ) ; System . out . println ( "Using new RESTful CustomerService with old Client" ) ; customer . v1 . Customer customer = createOldCustomer ( "Smith Old to New REST" ) ; customerService . updateCustomer ( customer ) ; customer = customerService . getCustomerByName ( "Smith Old to New REST" ) ; printOldCustomerDetails ( customer ) ; } | Old REST client uses new REST service | 265 | 7 |
147,006 | @ PostConstruct public void init ( ) { //init Bus and LifeCycle listeners if ( bus != null && sendLifecycleEvent ) { ServerLifeCycleManager slcm = bus . getExtension ( ServerLifeCycleManager . class ) ; if ( null != slcm ) { ServiceListenerImpl svrListener = new ServiceListenerImpl ( ) ; svrListener . setSendLifecycleEvent ( sendLifecycleEvent ) ; svrListener . setQueue ( queue ) ; svrListener . setMonitoringServiceClient ( monitoringServiceClient ) ; slcm . registerListener ( svrListener ) ; } ClientLifeCycleManager clcm = bus . getExtension ( ClientLifeCycleManager . class ) ; if ( null != clcm ) { ClientListenerImpl cltListener = new ClientListenerImpl ( ) ; cltListener . setSendLifecycleEvent ( sendLifecycleEvent ) ; cltListener . setQueue ( queue ) ; cltListener . setMonitoringServiceClient ( monitoringServiceClient ) ; clcm . registerListener ( cltListener ) ; } } if ( executorQueueSize == 0 ) { executor = Executors . newFixedThreadPool ( this . executorPoolSize ) ; } else { executor = new ThreadPoolExecutor ( executorPoolSize , executorPoolSize , 0 , TimeUnit . SECONDS , new LinkedBlockingQueue < Runnable > ( executorQueueSize ) , Executors . defaultThreadFactory ( ) , new RejectedExecutionHandlerImpl ( ) ) ; } scheduler = new Timer ( ) ; scheduler . scheduleAtFixedRate ( new TimerTask ( ) { public void run ( ) { sendEventsFromQueue ( ) ; } } , 0 , getDefaultInterval ( ) ) ; } | Instantiates a new event collector . | 383 | 8 |
147,007 | public void setDefaultInterval ( long defaultInterval ) { if ( defaultInterval <= 0 ) { LOG . severe ( "collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is " + defaultInterval ) ; throw new IllegalArgumentException ( "collector.scheduler.interval must be greater than 0. Recommended value is 500-1000. Current value is " + defaultInterval ) ; } this . defaultInterval = defaultInterval ; } | Set default interval for sending events to monitoring service . DefaultInterval will be used by scheduler . | 111 | 20 |
147,008 | 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 && ! queue . isEmpty ( ) ) { Event event = queue . remove ( ) ; if ( event != null && ! filter ( event ) ) { list . add ( event ) ; i ++ ; } } if ( list . size ( ) > 0 ) { executor . execute ( new Runnable ( ) { public void run ( ) { try { sendEvents ( list ) ; } catch ( MonitoringException e ) { e . logException ( Level . SEVERE ) ; } } } ) ; } } } | Method will be executed asynchronously . | 197 | 8 |
147,009 | 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 ) { EventAdminPublisher . publish ( events ) ; } else { monitoringServiceClient . putEvents ( events ) ; } } catch ( MonitoringException e ) { throw e ; } catch ( Exception e ) { throw new MonitoringException ( "002" , "Unknown error while execute put events to Monitoring Server" , e ) ; } } | Sends the events to monitoring service client . | 148 | 9 |
147,010 | @ Override 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 . | 62 | 25 |
147,011 | 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 ( "HTTP header '" + CORRELATIONID_HTTP_HEADER_NAME + "' set to: " + correlationId ) ; } } | Write correlation id . | 114 | 4 |
147,012 | 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 . isLoggable ( Level . FINE ) ) { LOG . fine ( "HTTP header '" + FLOWID_HTTP_HEADER_NAME + "' found: " + flowId ) ; } } else { if ( LOG . isLoggable ( Level . FINE ) ) { LOG . fine ( "No HTTP header '" + FLOWID_HTTP_HEADER_NAME + "' found" ) ; } } return flowId ; } | Read flow id from message . | 193 | 6 |
147,013 | 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_HTTP_HEADER_NAME + "' set to: " + flowId ) ; } } | Write flow id . | 111 | 4 |
147,014 | 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 . getInFaultInterceptors ( ) . add ( new DemoInterceptor ( p . getName ( ) ) ) ; } for ( Phase p : phases . getOutPhases ( ) ) { provider . getOutInterceptors ( ) . add ( new DemoInterceptor ( p . getName ( ) ) ) ; provider . getOutFaultInterceptors ( ) . add ( new DemoInterceptor ( p . getName ( ) ) ) ; } } | This method will add a DemoInterceptor into every in and every out phase of the interceptor chains . | 178 | 21 |
147,015 | 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 DemoInterceptor ) { return false ; } return true ; } last = cur ; } return true ; } | as we know nothing has changed . | 103 | 7 |
147,016 | 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 DemoInterceptor ) { continue ; } if ( interceptor instanceof PhaseInterceptor ) { PhaseInterceptor pi = ( PhaseInterceptor ) interceptor ; if ( ! phase . equals ( pi . getPhase ( ) ) ) { if ( builder != null ) { System . out . println ( builder . toString ( ) ) ; } else { builder = new StringBuilder ( 100 ) ; } builder . setLength ( 0 ) ; builder . append ( " " ) ; builder . append ( pi . getPhase ( ) ) ; builder . append ( ": " ) ; phase = pi . getPhase ( ) ; } String id = pi . getId ( ) ; int idx = id . lastIndexOf ( ' ' ) ; if ( idx != - 1 ) { id = id . substring ( idx + 1 ) ; } builder . append ( id ) ; builder . append ( ' ' ) ; } } } | 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 . | 269 | 43 |
147,017 | public com . squareup . okhttp . Call getCharactersCharacterIdShipCall ( Integer characterId , String datasource , String ifNoneMatch , String token , final ApiCallback callback ) throws ApiException { Object localVarPostBody = new Object ( ) ; // create path and map variables String localVarPath = "/v1/characters/{character_id}/ship/" . replaceAll ( "\\{" + "character_id" + "\\}" , apiClient . escapeString ( characterId . toString ( ) ) ) ; List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; List < Pair > localVarCollectionQueryParams = new ArrayList < Pair > ( ) ; if ( datasource != null ) { localVarQueryParams . addAll ( apiClient . parameterToPair ( "datasource" , datasource ) ) ; } if ( token != null ) { localVarQueryParams . addAll ( apiClient . parameterToPair ( "token" , token ) ) ; } Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; if ( ifNoneMatch != null ) { localVarHeaderParams . put ( "If-None-Match" , apiClient . parameterToString ( ifNoneMatch ) ) ; } Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; if ( localVarAccept != null ) { localVarHeaderParams . put ( "Accept" , localVarAccept ) ; } final String [ ] localVarContentTypes = { } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; localVarHeaderParams . put ( "Content-Type" , localVarContentType ) ; String [ ] localVarAuthNames = new String [ ] { "evesso" } ; return apiClient . buildCall ( localVarPath , "GET" , localVarQueryParams , localVarCollectionQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAuthNames , callback ) ; } | Build call for getCharactersCharacterIdShip | 499 | 8 |
147,018 | 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 builder = new StringBuilder ( ) ; builder . append ( URI_AUTHENTICATION ) ; builder . append ( "?" ) ; builder . append ( "response_type=" ) ; builder . append ( encode ( "code" ) ) ; builder . append ( "&redirect_uri=" ) ; builder . append ( encode ( redirectUri ) ) ; builder . append ( "&client_id=" ) ; builder . append ( encode ( account . getClientId ( ) ) ) ; builder . append ( "&scope=" ) ; builder . append ( encode ( getScopesString ( scopes ) ) ) ; builder . append ( "&state=" ) ; builder . append ( encode ( state ) ) ; builder . append ( "&code_challenge" ) ; builder . append ( getCodeChallenge ( ) ) ; // Already url encoded builder . append ( "&code_challenge_method=" ) ; builder . append ( encode ( "S256" ) ) ; return builder . toString ( ) ; } | Get the authorization uri where the user logs in . | 297 | 11 |
147,019 | 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 IllegalArgumentException ( "client_id is not set" ) ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( "grant_type=" ) ; builder . append ( encode ( "authorization_code" ) ) ; builder . append ( "&client_id=" ) ; builder . append ( encode ( account . getClientId ( ) ) ) ; builder . append ( "&code=" ) ; builder . append ( encode ( code ) ) ; builder . append ( "&code_verifier=" ) ; builder . append ( encode ( codeVerifier ) ) ; update ( account , builder . toString ( ) ) ; } | Finish the oauth flow after the user was redirected back . | 217 | 12 |
147,020 | 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 | 77 | 7 |
147,021 | public ApiClient setHttpClient ( OkHttpClient newHttpClient ) { if ( ! httpClient . equals ( newHttpClient ) ) { newHttpClient . networkInterceptors ( ) . addAll ( httpClient . networkInterceptors ( ) ) ; httpClient . networkInterceptors ( ) . clear ( ) ; newHttpClient . interceptors ( ) . addAll ( httpClient . interceptors ( ) ) ; httpClient . interceptors ( ) . clear ( ) ; this . httpClient = newHttpClient ; } return this ; } | Set HTTP client | 116 | 3 |
147,022 | private void addProgressInterceptor ( ) { httpClient . networkInterceptors ( ) . add ( new Interceptor ( ) { @ Override public Response intercept ( Interceptor . Chain chain ) throws IOException { final Request request = chain . request ( ) ; final Response originalResponse = chain . proceed ( request ) ; if ( request . tag ( ) instanceof ApiCallback ) { final ApiCallback callback = ( ApiCallback ) request . tag ( ) ; return originalResponse . newBuilder ( ) . body ( new ProgressResponseBody ( originalResponse . body ( ) , callback ) ) . build ( ) ; } return originalResponse ; } } ) ; } | Add network interceptor to httpClient to track download progress for async requests . | 138 | 15 |
147,023 | 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 ( ) ; // create path and map variables String localVarPath = "/v2/ui/autopilot/waypoint/" ; List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; List < Pair > localVarCollectionQueryParams = new ArrayList < Pair > ( ) ; if ( addToBeginning != null ) { localVarQueryParams . addAll ( apiClient . parameterToPair ( "add_to_beginning" , addToBeginning ) ) ; } if ( clearOtherWaypoints != null ) { localVarQueryParams . addAll ( apiClient . parameterToPair ( "clear_other_waypoints" , clearOtherWaypoints ) ) ; } if ( datasource != null ) { localVarQueryParams . addAll ( apiClient . parameterToPair ( "datasource" , datasource ) ) ; } if ( destinationId != null ) { localVarQueryParams . addAll ( apiClient . parameterToPair ( "destination_id" , destinationId ) ) ; } if ( token != null ) { localVarQueryParams . addAll ( apiClient . parameterToPair ( "token" , token ) ) ; } Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; final String [ ] localVarAccepts = { } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; if ( localVarAccept != null ) { localVarHeaderParams . put ( "Accept" , localVarAccept ) ; } final String [ ] localVarContentTypes = { } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; localVarHeaderParams . put ( "Content-Type" , localVarContentType ) ; String [ ] localVarAuthNames = new String [ ] { "evesso" } ; return apiClient . buildCall ( localVarPath , "POST" , localVarQueryParams , localVarCollectionQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAuthNames , callback ) ; } | Build call for postUiAutopilotWaypoint | 553 | 11 |
147,024 | 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 . | 95 | 34 |
147,025 | 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 . | 66 | 14 |
147,026 | 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 ) == ' ' ) { nibble += 8 ; } break ; case 1 : if ( binaryString . charAt ( i ) == ' ' ) { nibble += 4 ; } break ; case 2 : if ( binaryString . charAt ( i ) == ' ' ) { nibble += 2 ; } break ; case 3 : if ( binaryString . charAt ( i ) == ' ' ) { nibble += 1 ; } encodeInfo += Integer . toHexString ( nibble ) ; nibble = 0 ; break ; } } if ( ( binaryString . length ( ) % 4 ) != 0 ) { encodeInfo += Integer . toHexString ( nibble ) ; } encodeInfo += "\n" ; } | Logs binary string as hexadecimal | 242 | 9 |
147,027 | private int combineSubsetBlocks ( Mode [ ] mode_type , int [ ] mode_length , int index_point ) { /* bring together same type blocks */ if ( index_point > 1 ) { for ( int i = 1 ; i < index_point ; i ++ ) { if ( mode_type [ i - 1 ] == mode_type [ i ] ) { /* bring together */ mode_length [ i - 1 ] = mode_length [ i - 1 ] + mode_length [ i ] ; /* decrease the list */ for ( int j = i + 1 ; j < index_point ; j ++ ) { mode_length [ j - 1 ] = mode_length [ j ] ; mode_type [ j - 1 ] = mode_type [ j ] ; } index_point -- ; i -- ; } } } return index_point ; } | Modifies the specified mode and length arrays to combine adjacent modes of the same type returning the updated index point . | 182 | 22 |
147,028 | 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 ) { System . out . println ( "An error occurred" ) ; } } } | Starts the Okapi Barcode UI . | 110 | 9 |
147,029 | 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 ++ ) { /* check that country code and service are numeric */ if ( primaryData . charAt ( i ) < ' ' || primaryData . charAt ( i ) > ' ' ) { throw new OkapiException ( "Invalid Primary String" ) ; } } String postcode ; if ( mode == 2 ) { postcode = primaryData . substring ( 0 , 9 ) ; int index = postcode . indexOf ( ' ' ) ; if ( index != - 1 ) { postcode = postcode . substring ( 0 , index ) ; } } else { // if (mode == 3) postcode = primaryData . substring ( 0 , 6 ) ; } int country = Integer . parseInt ( primaryData . substring ( 9 , 12 ) ) ; int service = Integer . parseInt ( primaryData . substring ( 12 , 15 ) ) ; if ( debug ) { System . out . println ( "Using mode " + mode ) ; System . out . println ( " Postcode: " + postcode ) ; System . out . println ( " Country Code: " + country ) ; System . out . println ( " Service: " + service ) ; } if ( mode == 2 ) { return getMode2PrimaryCodewords ( postcode , country , service ) ; } else { // mode == 3 return getMode3PrimaryCodewords ( postcode , country , service ) ; } } | Extracts the postal code country code and service code from the primary data and returns the corresponding primary message codewords . | 355 | 25 |
147,030 | private static int [ ] getMode2PrimaryCodewords ( String postcode , int country , int service ) { for ( int i = 0 ; i < postcode . length ( ) ; i ++ ) { if ( postcode . charAt ( i ) < ' ' || postcode . charAt ( i ) > ' ' ) { postcode = postcode . substring ( 0 , i ) ; break ; } } int postcodeNum = Integer . parseInt ( postcode ) ; int [ ] primary = new int [ 10 ] ; primary [ 0 ] = ( ( postcodeNum & 0x03 ) << 4 ) | 2 ; primary [ 1 ] = ( ( postcodeNum & 0xfc ) >> 2 ) ; primary [ 2 ] = ( ( postcodeNum & 0x3f00 ) >> 8 ) ; primary [ 3 ] = ( ( postcodeNum & 0xfc000 ) >> 14 ) ; primary [ 4 ] = ( ( postcodeNum & 0x3f00000 ) >> 20 ) ; primary [ 5 ] = ( ( postcodeNum & 0x3c000000 ) >> 26 ) | ( ( postcode . length ( ) & 0x3 ) << 4 ) ; primary [ 6 ] = ( ( postcode . length ( ) & 0x3c ) >> 2 ) | ( ( country & 0x3 ) << 4 ) ; primary [ 7 ] = ( country & 0xfc ) >> 2 ; primary [ 8 ] = ( ( country & 0x300 ) >> 8 ) | ( ( service & 0xf ) << 2 ) ; primary [ 9 ] = ( ( service & 0x3f0 ) >> 4 ) ; return primary ; } | Returns the primary message codewords for mode 2 . | 355 | 11 |
147,031 | 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 . charAt ( i ) >= ' ' && postcode . charAt ( i ) <= ' ' ) { // (Capital) letters shifted to Code Set A values postcodeNums [ i ] -= 64 ; } if ( postcodeNums [ i ] == 27 || postcodeNums [ i ] == 31 || postcodeNums [ i ] == 33 || postcodeNums [ i ] >= 59 ) { // Not a valid postal code character, use space instead postcodeNums [ i ] = 32 ; } // Input characters lower than 27 (NUL - SUB) in postal code are interpreted as capital // letters in Code Set A (e.g. LF becomes 'J') } int [ ] primary = new int [ 10 ] ; primary [ 0 ] = ( ( postcodeNums [ 5 ] & 0x03 ) << 4 ) | 3 ; primary [ 1 ] = ( ( postcodeNums [ 4 ] & 0x03 ) << 4 ) | ( ( postcodeNums [ 5 ] & 0x3c ) >> 2 ) ; primary [ 2 ] = ( ( postcodeNums [ 3 ] & 0x03 ) << 4 ) | ( ( postcodeNums [ 4 ] & 0x3c ) >> 2 ) ; primary [ 3 ] = ( ( postcodeNums [ 2 ] & 0x03 ) << 4 ) | ( ( postcodeNums [ 3 ] & 0x3c ) >> 2 ) ; primary [ 4 ] = ( ( postcodeNums [ 1 ] & 0x03 ) << 4 ) | ( ( postcodeNums [ 2 ] & 0x3c ) >> 2 ) ; primary [ 5 ] = ( ( postcodeNums [ 0 ] & 0x03 ) << 4 ) | ( ( postcodeNums [ 1 ] & 0x3c ) >> 2 ) ; primary [ 6 ] = ( ( postcodeNums [ 0 ] & 0x3c ) >> 2 ) | ( ( country & 0x3 ) << 4 ) ; primary [ 7 ] = ( country & 0xfc ) >> 2 ; primary [ 8 ] = ( ( country & 0x300 ) >> 8 ) | ( ( service & 0xf ) << 2 ) ; primary [ 9 ] = ( ( service & 0x3f0 ) >> 4 ) ; return primary ; } | Returns the primary message codewords for mode 3 . | 591 | 11 |
147,032 | private int bestSurroundingSet ( int index , int length , int ... valid ) { int option1 = set [ index - 1 ] ; if ( index + 1 < length ) { // we have two options to check int option2 = set [ index + 1 ] ; if ( contains ( valid , option1 ) && contains ( valid , option2 ) ) { return Math . min ( option1 , option2 ) ; } else if ( contains ( valid , option1 ) ) { return option1 ; } else if ( contains ( valid , option2 ) ) { return option2 ; } else { return valid [ 0 ] ; } } else { // we only have one option to check if ( contains ( valid , option1 ) ) { return option1 ; } else { return valid [ 0 ] ; } } } | 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 . | 170 | 58 |
147,033 | 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 . | 59 | 16 |
147,034 | 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 . getResult ( results . length - 1 - i ) ; } return results ; } | Returns the error correction codewords for the specified data codewords . | 124 | 15 |
147,035 | 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 . | 81 | 52 |
147,036 | private void addErrorCorrection ( StringBuilder adjustedString , int codewordSize , int dataBlocks , int eccBlocks ) { int x , poly , startWeight ; /* Split into codewords and calculate Reed-Solomon error correction codes */ switch ( codewordSize ) { case 6 : x = 32 ; poly = 0x43 ; startWeight = 0x20 ; break ; case 8 : x = 128 ; poly = 0x12d ; startWeight = 0x80 ; break ; case 10 : x = 512 ; poly = 0x409 ; startWeight = 0x200 ; break ; case 12 : x = 2048 ; poly = 0x1069 ; startWeight = 0x800 ; break ; default : throw new OkapiException ( "Unrecognized codeword size: " + codewordSize ) ; } ReedSolomon rs = new ReedSolomon ( ) ; int [ ] data = new int [ dataBlocks + 3 ] ; int [ ] ecc = new int [ eccBlocks + 3 ] ; for ( int i = 0 ; i < dataBlocks ; i ++ ) { for ( int weight = 0 ; weight < codewordSize ; weight ++ ) { if ( adjustedString . charAt ( ( i * codewordSize ) + weight ) == ' ' ) { data [ i ] += ( x >> weight ) ; } } } rs . init_gf ( poly ) ; rs . init_code ( eccBlocks , 1 ) ; rs . encode ( dataBlocks , data ) ; for ( int i = 0 ; i < eccBlocks ; i ++ ) { ecc [ i ] = rs . getResult ( i ) ; } for ( int i = ( eccBlocks - 1 ) ; i >= 0 ; i -- ) { for ( int weight = startWeight ; weight > 0 ; weight = weight >> 1 ) { if ( ( ecc [ i ] & weight ) != 0 ) { adjustedString . append ( ' ' ) ; } else { adjustedString . append ( ' ' ) ; } } } } | Adds error correction data to the specified binary string which already contains the primary data | 426 | 15 |
147,037 | 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 . | 39 | 18 |
147,038 | 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 . | 72 | 12 |
147,039 | 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 ( original , index , modified , index + inserted . length , modified . length - index - inserted . length ) ; return modified ; } | Inserts the specified array into the specified original array at the specified index . | 105 | 15 |
147,040 | 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 ; // ZINT NOTE: in Zint, this call modifies the input mode array directly; here, we leave // the original array alone so that subsequent binary length checks don't irrevocably // optimize the mode array for the wrong QR Code version QrMode [ ] inputMode = applyOptimisation ( version , inputModeUnoptimized ) ; currentMode = QrMode . NULL ; if ( gs1 ) { count += 4 ; } if ( eciMode != 3 ) { count += 12 ; } for ( i = 0 ; i < inputLength ; i ++ ) { if ( inputMode [ i ] != currentMode ) { count += 4 ; switch ( inputMode [ i ] ) { case KANJI : count += tribus ( version , 8 , 10 , 12 ) ; count += ( blockLength ( i , inputMode ) * 13 ) ; break ; case BINARY : count += tribus ( version , 8 , 16 , 16 ) ; for ( j = i ; j < ( i + blockLength ( i , inputMode ) ) ; j ++ ) { if ( inputData [ j ] > 0xff ) { count += 16 ; } else { count += 8 ; } } break ; case ALPHANUM : count += tribus ( version , 9 , 11 , 13 ) ; alphaLength = blockLength ( i , inputMode ) ; // In alphanumeric mode % becomes %% if ( gs1 ) { for ( j = i ; j < ( i + alphaLength ) ; j ++ ) { // TODO: need to do this only if in GS1 mode? or is the other code wrong? https://sourceforge.net/p/zint/tickets/104/#227b if ( inputData [ j ] == ' ' ) { percent ++ ; } } } alphaLength += percent ; switch ( alphaLength % 2 ) { case 0 : count += ( alphaLength / 2 ) * 11 ; break ; case 1 : count += ( ( alphaLength - 1 ) / 2 ) * 11 ; count += 6 ; break ; } break ; case NUMERIC : count += tribus ( version , 10 , 12 , 14 ) ; switch ( blockLength ( i , inputMode ) % 3 ) { case 0 : count += ( blockLength ( i , inputMode ) / 3 ) * 10 ; break ; case 1 : count += ( ( blockLength ( i , inputMode ) - 1 ) / 3 ) * 10 ; count += 4 ; break ; case 2 : count += ( ( blockLength ( i , inputMode ) - 2 ) / 3 ) * 10 ; count += 7 ; break ; } break ; } currentMode = inputMode [ i ] ; } } return count ; } | Calculate the actual bit length of the proposed binary string . | 647 | 13 |
147,041 | 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 . | 77 | 10 |
147,042 | 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 . | 53 | 8 |
147,043 | 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 ecc_block_length = ecc_cw / blocks ; int i , j , length_this_block , posn ; int [ ] data_block = new int [ short_data_block_length + 2 ] ; int [ ] ecc_block = new int [ ecc_block_length + 2 ] ; int [ ] interleaved_data = new int [ data_cw + 2 ] ; int [ ] interleaved_ecc = new int [ ecc_cw + 2 ] ; posn = 0 ; for ( i = 0 ; i < blocks ; i ++ ) { if ( i < qty_short_blocks ) { length_this_block = short_data_block_length ; } else { length_this_block = short_data_block_length + 1 ; } for ( j = 0 ; j < ecc_block_length ; j ++ ) { ecc_block [ j ] = 0 ; } for ( j = 0 ; j < length_this_block ; j ++ ) { data_block [ j ] = datastream [ posn + j ] ; } ReedSolomon rs = new ReedSolomon ( ) ; rs . init_gf ( 0x11d ) ; rs . init_code ( ecc_block_length , 0 ) ; rs . encode ( length_this_block , data_block ) ; for ( j = 0 ; j < ecc_block_length ; j ++ ) { ecc_block [ j ] = rs . getResult ( j ) ; } for ( j = 0 ; j < short_data_block_length ; j ++ ) { interleaved_data [ ( j * blocks ) + i ] = data_block [ j ] ; } if ( i >= qty_short_blocks ) { interleaved_data [ ( short_data_block_length * blocks ) + ( i - qty_short_blocks ) ] = data_block [ short_data_block_length ] ; } for ( j = 0 ; j < ecc_block_length ; j ++ ) { interleaved_ecc [ ( j * blocks ) + i ] = ecc_block [ ecc_block_length - j - 1 ] ; } posn += length_this_block ; } for ( j = 0 ; j < data_cw ; j ++ ) { fullstream [ j ] = interleaved_data [ j ] ; } for ( j = 0 ; j < ecc_cw ; j ++ ) { fullstream [ j + data_cw ] = interleaved_ecc [ j ] ; } } | Splits data into blocks adds error correction and then interleaves the blocks and error correction data . | 667 | 20 |
147,044 | 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 < 6 ; i ++ ) { eval [ ( i * size ) + 8 ] = ( byte ) ( ( ( ( seq >> i ) & 0x01 ) != 0 ) ? ( 0x01 >> pattern ) : 0x00 ) ; } for ( i = 0 ; i < 8 ; i ++ ) { eval [ ( 8 * size ) + ( size - i - 1 ) ] = ( byte ) ( ( ( ( seq >> i ) & 0x01 ) != 0 ) ? ( 0x01 >> pattern ) : 0x00 ) ; } for ( i = 0 ; i < 6 ; i ++ ) { eval [ ( 8 * size ) + ( 5 - i ) ] = ( byte ) ( ( ( ( seq >> ( i + 9 ) ) & 0x01 ) != 0 ) ? ( 0x01 >> pattern ) : 0x00 ) ; } for ( i = 0 ; i < 7 ; i ++ ) { eval [ ( ( ( size - 7 ) + i ) * size ) + 8 ] = ( byte ) ( ( ( ( seq >> ( i + 8 ) ) & 0x01 ) != 0 ) ? ( 0x01 >> pattern ) : 0x00 ) ; } eval [ ( 7 * size ) + 8 ] = ( byte ) ( ( ( ( seq >> 6 ) & 0x01 ) != 0 ) ? ( 0x01 >> pattern ) : 0x00 ) ; eval [ ( 8 * size ) + 8 ] = ( byte ) ( ( ( ( seq >> 7 ) & 0x01 ) != 0 ) ? ( 0x01 >> pattern ) : 0x00 ) ; eval [ ( 8 * size ) + 7 ] = ( byte ) ( ( ( ( seq >> 8 ) & 0x01 ) != 0 ) ? ( 0x01 >> pattern ) : 0x00 ) ; } | Adds format information to eval . | 486 | 6 |
147,045 | private static void addVersionInfo ( byte [ ] grid , int size , int version ) { // TODO: Zint masks with 0x41 instead of 0x01; which is correct? https://sourceforge.net/p/zint/tickets/110/ 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 ) ) & 0x01 ; grid [ ( ( size - 9 ) * size ) + i ] += ( version_data >> ( ( i * 3 ) + 2 ) ) & 0x01 ; grid [ ( i * size ) + ( size - 11 ) ] += ( version_data >> ( i * 3 ) ) & 0x01 ; grid [ ( i * size ) + ( size - 10 ) ] += ( version_data >> ( ( i * 3 ) + 1 ) ) & 0x01 ; grid [ ( i * size ) + ( size - 9 ) ] += ( version_data >> ( ( i * 3 ) + 2 ) ) & 0x01 ; } } | Adds version information . | 293 | 4 |
147,046 | 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 . NUM || current . length < MAX_NUMERIC_COMPACTION_BLOCK_SIZE ) ) { current . length ++ ; } else { current = new Block ( mode ) ; blocks . add ( current ) ; } } if ( debug ) { System . out . println ( "Initial block pattern: " + blocks ) ; } smoothBlocks ( blocks ) ; if ( debug ) { System . out . println ( "Final block pattern: " + blocks ) ; } return blocks ; } | Determines the encoding block groups for the specified data . | 191 | 12 |
147,047 | 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 ) ) { b1 . length += b2 . length ; blocks . remove ( i ) ; i -- ; } } } | Combines adjacent blocks of the same type . | 132 | 9 |
147,048 | 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 , "ISO8859_8" , 10 ) . or ( content , "ISO8859_9" , 11 ) . or ( content , "ISO8859_10" , 12 ) . or ( content , "ISO8859_11" , 13 ) . or ( content , "ISO8859_13" , 15 ) . or ( content , "ISO8859_14" , 16 ) . or ( content , "ISO8859_15" , 17 ) . or ( content , "ISO8859_16" , 18 ) . or ( content , "Windows_1250" , 21 ) . or ( content , "Windows_1251" , 22 ) . or ( content , "Windows_1252" , 23 ) . or ( content , "Windows_1256" , 24 ) . or ( content , "SJIS" , 20 ) . or ( content , "UTF8" , 26 ) ; if ( EciMode . NONE . equals ( eci ) ) { throw new OkapiException ( "Unable to determine ECI mode." ) ; } eciMode = eci . mode ; inputData = toBytes ( content , eci . charset ) ; encodeInfo += "ECI Mode: " + eci . mode + "\n" ; encodeInfo += "ECI Charset: " + eci . charset . name ( ) + "\n" ; } | Chooses the ECI mode most suitable for the content of this symbol . | 428 | 15 |
147,049 | 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 , secondRect . x ) && roughlyEqual ( firstRect . width , secondRect . width ) ) { if ( roughlyEqual ( firstRect . y + firstRect . height , secondRect . y ) ) { firstRect . height += secondRect . height ; rectangles . set ( i , firstRect ) ; rectangles . remove ( j ) ; } } } } } | 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 . | 177 | 34 |
147,050 | private String hibcProcess ( String source ) { // HIBC 2.6 allows up to 110 characters, not including the "+" prefix or the check digit 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 ; for ( int i = 0 ; i < source . length ( ) ; i ++ ) { counter += positionOf ( source . charAt ( i ) , HIBC_CHAR_TABLE ) ; } counter = counter % 43 ; char checkDigit = HIBC_CHAR_TABLE [ counter ] ; encodeInfo += "HIBC Check Digit Counter: " + counter + "\n" ; encodeInfo += "HIBC Check Digit: " + checkDigit + "\n" ; return "+" + source + checkDigit ; } | Adds the HIBC prefix and check digit to the specified data returning the resultant data string . | 232 | 18 |
147,051 | 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 ( pattern [ 0 ] . length ( ) / ( double ) size ) ; int [ ] codewords = new int [ pattern . length * count ] ; for ( int i = 0 ; i < pattern . length ; i ++ ) { String row = pattern [ i ] ; for ( int j = 0 ; j < count ; j ++ ) { int substringStart = j * size ; int substringEnd = Math . min ( ( j + 1 ) * size , row . length ( ) ) ; codewords [ ( i * count ) + j ] = Integer . parseInt ( row . substring ( substringStart , substringEnd ) ) ; } } return codewords ; } } | Returns this bar code s pattern converted into a set of corresponding codewords . Useful for bar codes that encode their content as a pattern . | 232 | 28 |
147,052 | 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 distance = pointsDistance ( midInsectPoint , innerPoint ) ; if ( distance > radius ) { return 360 - angle ; } return angle ; } | calculate arc angle between point a and point b | 124 | 11 |
147,053 | private static Point findMidnormalPoint ( Point center , Point a , Point b , Rect area , int radius ) { if ( a . y == b . y ) { //top if ( a . y < center . y ) { return new Point ( ( a . x + b . x ) / 2 , center . y + radius ) ; } //bottom return new Point ( ( a . x + b . x ) / 2 , center . y - radius ) ; } if ( a . x == b . x ) { //left if ( a . x < center . x ) { return new Point ( center . x + radius , ( a . y + b . y ) / 2 ) ; } //right return new Point ( center . x - radius , ( a . y + b . y ) / 2 ) ; } //slope of line ab double abSlope = ( a . y - b . y ) / ( a . x - b . x * 1.0 ) ; //slope of midnormal double midnormalSlope = - 1.0 / abSlope ; double radian = Math . tan ( midnormalSlope ) ; int dy = ( int ) ( radius * Math . sin ( radian ) ) ; int dx = ( int ) ( radius * Math . cos ( radian ) ) ; Point point = new Point ( center . x + dx , center . y + dy ) ; if ( ! inArea ( point , area , 0 ) ) { point = new Point ( center . x - dx , center . y - dy ) ; } return point ; } | find the middle point of two intersect points in circle only one point will be correct | 334 | 16 |
147,054 | 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 | 78 | 10 |
147,055 | 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 ; | 89 | 19 |
147,056 | 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 | 51 | 7 |
147,057 | 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 , ( float ) ( toAngle - fromAngle ) ) ; PathMeasure measure = new PathMeasure ( path , false ) ; float len = measure . getLength ( ) ; int divisor = getChildCount ( ) ; float divider = len / divisor ; for ( int i = 0 ; i < getChildCount ( ) ; i ++ ) { float [ ] coords = new float [ 2 ] ; measure . getPosTan ( i * divider + divider * .5f , coords , null ) ; FilterMenu . Item item = ( FilterMenu . Item ) getChildAt ( i ) . getTag ( ) ; item . setX ( ( int ) coords [ 0 ] - item . getView ( ) . getMeasuredWidth ( ) / 2 ) ; item . setY ( ( int ) coords [ 1 ] - item . getView ( ) . getMeasuredHeight ( ) / 2 ) ; } } | calculate and set position to menu items | 292 | 9 |
147,058 | 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 | 65 | 10 |
147,059 | 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 . | 52 | 20 |
147,060 | public void clearTmpData ( ) { for ( Enumeration < ? > e = breadthFirstEnumeration ( ) ; e . hasMoreElements ( ) ; ) { ( ( LblTree ) e . nextElement ( ) ) . setTmpData ( null ) ; } } | Clear tmpData in subtree rooted in this node . | 62 | 11 |
147,061 | 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 = "/" + node . getNodeName ( ) + "[1]" ; node . setUserData ( FULL_XPATH_CACHE , xPath , null ) ; return xPath ; } if ( node . hasAttributes ( ) && node . getAttributes ( ) . getNamedItem ( "id" ) != null ) { String xPath = "//" + node . getNodeName ( ) + "[@id = '" + node . getAttributes ( ) . getNamedItem ( "id" ) . getNodeValue ( ) + "']" ; node . setUserData ( FULL_XPATH_CACHE , xPath , null ) ; return xPath ; } StringBuffer buffer = new StringBuffer ( ) ; if ( parent != node ) { buffer . append ( getXPathExpression ( parent ) ) ; buffer . append ( "/" ) ; } buffer . append ( node . getNodeName ( ) ) ; List < Node > mySiblings = getSiblings ( parent , node ) ; for ( int i = 0 ; i < mySiblings . size ( ) ; i ++ ) { Node el = mySiblings . get ( i ) ; if ( el . equals ( node ) ) { buffer . append ( ' ' ) . append ( Integer . toString ( i + 1 ) ) . append ( ' ' ) ; // Found so break; break ; } } String xPath = buffer . toString ( ) ; node . setUserData ( FULL_XPATH_CACHE , xPath , null ) ; return xPath ; } | Reverse Engineers an XPath Expression of a given Node in the DOM . | 425 | 16 |
147,062 | 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 ( ) ) ) { result . add ( el ) ; } } return result ; } | Get siblings of the same type as element from parent . | 109 | 11 |
147,063 | 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 . | 60 | 19 |
147,064 | 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 , XPathConstants . NODESET ) ; return ( NodeList ) result ; } | Returns the list of nodes which match the expression xpathExpr in the Document dom . | 98 | 18 |
147,065 | 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 ( ) && ! element . startsWith ( "@" ) && ! element . contains ( "()" ) ) { if ( element . contains ( "[" ) ) { try { number = Integer . parseInt ( element . substring ( element . indexOf ( "[" ) + 1 , element . indexOf ( "]" ) ) ) ; } catch ( NumberFormatException e ) { return - 1 ; } } else { number = 1 ; } for ( int i = 0 ; i < number ; i ++ ) { // find new open element temp = dom_lower . indexOf ( "<" + stripEndSquareBrackets ( element ) , pos ) ; if ( temp > - 1 ) { pos = temp + 1 ; // if depth>1 then goto end of current element if ( number > 1 && i < number - 1 ) { pos = getCloseElementLocation ( dom_lower , pos , stripEndSquareBrackets ( element ) ) ; } } } } } return pos - 1 ; } | returns position of xpath element which match the expression xpath in the String dom . | 295 | 18 |
147,066 | double getThreshold ( String x , String y , double p ) { return 2 * Math . max ( x . length ( ) , y . length ( ) ) * ( 1 - p ) ; } | Calculate a threshold . | 42 | 6 |
147,067 | @ Override 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 ( CrawljaxException e ) { // Exception is caught, check failed so return false; return false ; } } | Check invariant . | 120 | 4 |
147,068 | 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 . | 70 | 9 |
147,069 | 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 . | 67 | 9 |
147,070 | public By getWebDriverBy ( ) { switch ( how ) { case name : return By . name ( this . value ) ; case xpath : // Work around HLWK driver bug 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 ( this . value ) ; case partialText : return By . partialLinkText ( this . value ) ; default : return null ; } } | Convert a Identification to a By used in WebDriver Drivers . | 133 | 13 |
147,071 | protected String escapeApostrophes ( String text ) { String resultString ; if ( text . contains ( "'" ) ) { StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder . append ( "concat('" ) ; stringBuilder . append ( text . replace ( "'" , "',\"'\",'" ) ) ; stringBuilder . append ( "')" ) ; resultString = stringBuilder . toString ( ) ; } else { resultString = "'" + text + "'" ; } return resultString ; } | Returns a string to resolve apostrophe issue in xpath | 112 | 11 |
147,072 | @ Override public CrawlSession call ( ) { setMaximumCrawlTimeIfNeeded ( ) ; plugins . runPreCrawlingPlugins ( config ) ; CrawlTaskConsumer firstConsumer = consumerFactory . get ( ) ; StateVertex firstState = firstConsumer . crawlIndex ( ) ; crawlSessionProvider . setup ( firstState ) ; plugins . runOnNewStatePlugins ( firstConsumer . getContext ( ) , firstState ) ; executeConsumers ( firstConsumer ) ; return crawlSessionProvider . get ( ) ; } | Run the configured crawl . This method blocks until the crawl is done . | 111 | 14 |
147,073 | 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 ( ) ) ; return ImmutableList . of ( ) ; } LOG . debug ( "Looking in state: {} for candidate elements" , currentState . getName ( ) ) ; try { Document dom = DomUtils . asDocument ( browser . getStrippedDomWithoutIframeContent ( ) ) ; extractElements ( dom , results , "" ) ; } catch ( IOException e ) { LOG . error ( e . getMessage ( ) , e ) ; throw new CrawljaxException ( e ) ; } if ( randomizeElementsOrder ) { Collections . shuffle ( results ) ; } currentState . setElementsFound ( results ) ; LOG . debug ( "Found {} new candidate elements to analyze!" , results . size ( ) ) ; return ImmutableList . copyOf ( results ) ; } | This method extracts candidate elements from the current DOM tree in the browser based on the crawl tags defined by the user . | 250 | 23 |
147,074 | private ImmutableList < Element > getNodeListForTagElement ( Document dom , CrawlElement crawlElement , EventableConditionChecker eventableConditionChecker ) { Builder < Element > result = ImmutableList . builder ( ) ; if ( crawlElement . getTagName ( ) == null ) { return result . build ( ) ; } EventableCondition eventableCondition = eventableConditionChecker . getEventableCondition ( crawlElement . getId ( ) ) ; // TODO Stefan; this part of the code should be re-factored, Hack-ed it this way to prevent // performance problems. ImmutableList < String > expressions = getFullXpathForGivenXpath ( dom , eventableCondition ) ; NodeList nodeList = dom . getElementsByTagName ( crawlElement . getTagName ( ) ) ; for ( int k = 0 ; k < nodeList . getLength ( ) ; k ++ ) { Element element = ( Element ) nodeList . item ( k ) ; boolean matchesXpath = elementMatchesXpath ( eventableConditionChecker , eventableCondition , expressions , element ) ; LOG . debug ( "Element {} matches Xpath={}" , DomUtils . getElementString ( element ) , matchesXpath ) ; /* * TODO Stefan This is a possible Thread-Interleaving problem, as / isChecked can return * false and when needed to add it can return true. / check if element is a candidate */ String id = element . getNodeName ( ) + ": " + DomUtils . getAllElementAttributes ( element ) ; if ( matchesXpath && ! checkedElements . isChecked ( id ) && ! isExcluded ( dom , element , eventableConditionChecker ) ) { addElement ( element , result , crawlElement ) ; } else { LOG . debug ( "Element {} was not added" , element ) ; } } return result . build ( ) ; } | Returns a list of Elements form the DOM tree matching the tag element . | 409 | 14 |
147,075 | 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 instanceof OnInvariantViolationPlugin ) { try { LOGGER . debug ( "Calling plugin {}" , plugin ) ; ( ( OnInvariantViolationPlugin ) plugin ) . onInvariantViolation ( invariant , context ) ; } catch ( RuntimeException e ) { reportFailingPlugin ( plugin , e ) ; } } } } | 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 behaviour of Crawljax . | 160 | 75 |
147,076 | 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 ) { LOGGER . debug ( "Calling plugin {}" , plugin ) ; try { ( ( OnBrowserCreatedPlugin ) plugin ) . onBrowserCreated ( newBrowser ) ; } catch ( RuntimeException e ) { reportFailingPlugin ( plugin , e ) ; } } } } | 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 . | 132 | 63 |
147,077 | public boolean equalId ( Element otherElement ) { if ( getElementId ( ) == null || otherElement . getElementId ( ) == null ) { return false ; } return getElementId ( ) . equalsIgnoreCase ( otherElement . getElementId ( ) ) ; } | Are both Id s the same? | 59 | 7 |
147,078 | 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 . | 60 | 10 |
147,079 | public boolean checkXpathStartsWithXpathEventableCondition ( Document dom , EventableCondition eventableCondition , String xpath ) throws XPathExpressionException { if ( eventableCondition == null || Strings . isNullOrEmpty ( eventableCondition . getInXPath ( ) ) ) { throw new CrawljaxException ( "Eventable has no XPath condition" ) ; } List < String > expressions = XPathHelper . getXpathForXPathExpressions ( dom , eventableCondition . getInXPath ( ) ) ; return checkXPathUnderXPaths ( xpath , expressions ) ; } | Checks whether an XPath expression starts with an XPath eventable condition . | 133 | 16 |
147,080 | 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 RTED_InfoTree_Opt ( 1 , 1 , 1 ) ; // compute tree edit distance rted . init ( domTree1 , domTree2 ) ; int maxSize = Math . max ( domTree1 . getNodeCount ( ) , domTree2 . getNodeCount ( ) ) ; rted . computeOptimalStrategy ( ) ; ted = rted . nonNormalizedTreeDist ( ) ; ted /= ( double ) maxSize ; DD = ted ; return DD ; } | Get a scalar value for the DOM diversity using the Robust Tree Edit Distance | 206 | 16 |
147,081 | private static LblTree createTree ( TreeWalker walker ) { Node parent = walker . getCurrentNode ( ) ; LblTree node = new LblTree ( parent . getNodeName ( ) , - 1 ) ; // treeID = -1 for ( Node n = walker . firstChild ( ) ; n != null ; n = walker . nextSibling ( ) ) { node . add ( createTree ( walker ) ) ; } walker . setCurrentNode ( parent ) ; return node ; } | Recursively construct a LblTree from DOM tree | 110 | 11 |
147,082 | 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 . | 73 | 9 |
147,083 | 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 . | 42 | 32 |
147,084 | 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 is Firefox" ) ; options . addOption ( BROWSER_REMOTE_URL , true , "The remote url if you have configured a remote browser" ) ; options . addOption ( "d" , DEPTH , true , "crawl depth level. Default is 2" ) ; options . addOption ( "s" , MAXSTATES , true , "max number of states to crawl. Default is 0 (unlimited)" ) ; options . addOption ( "p" , PARALLEL , true , "Number of browsers to use for crawling. Default is 1" ) ; options . addOption ( "o" , OVERRIDE , false , "Override the output directory if non-empty" ) ; options . addOption ( "a" , CRAWL_HIDDEN_ANCHORS , false , "Crawl anchors even if they are not visible in the browser." ) ; options . addOption ( "t" , TIME_OUT , true , "Specify the maximum crawl time in minutes" ) ; options . addOption ( CLICK , true , "a comma separated list of HTML tags that should be clicked. Default is A and BUTTON" ) ; options . addOption ( WAIT_AFTER_EVENT , true , "the time to wait after an event has been fired in milliseconds. Default is " + CrawlRules . DEFAULT_WAIT_AFTER_EVENT ) ; options . addOption ( WAIT_AFTER_RELOAD , true , "the time to wait after an URL has been loaded in milliseconds. Default is " + CrawlRules . DEFAULT_WAIT_AFTER_RELOAD ) ; options . addOption ( "v" , VERBOSE , false , "Be extra verbose" ) ; options . addOption ( LOG_FILE , true , "Log to this file instead of the console" ) ; return options ; } | Create the CML Options . | 486 | 6 |
147,085 | 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 . | 47 | 18 |
147,086 | 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 . | 67 | 15 |
147,087 | @ GuardedBy ( "elementsLock" ) @ Override public boolean markChecked ( CandidateElement element ) { String generalString = element . getGeneralString ( ) ; String uniqueString = element . getUniqueString ( ) ; synchronized ( elementsLock ) { if ( elements . contains ( uniqueString ) ) { return false ; } else { elements . add ( generalString ) ; elements . add ( uniqueString ) ; return true ; } } } | 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 . | 94 | 28 |
147,088 | private void readFormDataFromFile ( ) { List < FormInput > formInputList = FormInputValueHelper . deserializeFormInputs ( config . getSiteDir ( ) ) ; if ( formInputList != null ) { InputSpecification inputSpecs = config . getCrawlRules ( ) . getInputSpecification ( ) ; for ( FormInput input : formInputList ) { inputSpecs . inputField ( input ) ; } } } | Reads input data from a JSON file in the output directory . | 96 | 13 |
147,089 | @ Override 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 . | 72 | 11 |
147,090 | public static Integer distance ( String h1 , String h2 ) { HammingDistance distance = new HammingDistance ( ) ; return distance . apply ( h1 , h2 ) ; } | Calculate the Hamming distance between two hashes | 39 | 10 |
147,091 | 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 . | 52 | 11 |
147,092 | 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 ( "id" ) . getNodeValue ( ) ) ; FormInput input = this . formInputs . get ( id ) ; if ( input != null ) { return input ; } } if ( attributes . getNamedItem ( "name" ) != null && formFillMode != FormFillMode . XPATH_TRAINING ) { id = new Identification ( Identification . How . name , attributes . getNamedItem ( "name" ) . getNodeValue ( ) ) ; FormInput input = this . formInputs . get ( id ) ; if ( input != null ) { return input ; } } String xpathExpr = XPathHelper . getXPathExpression ( element ) ; if ( xpathExpr != null && ! xpathExpr . equals ( "" ) ) { id = new Identification ( Identification . How . xpath , xpathExpr ) ; FormInput input = this . formInputs . get ( id ) ; if ( input != null ) { return input ; } } return null ; } | return the list of FormInputs that match this element | 297 | 11 |
147,093 | 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 ( graphProvider . get ( ) , crawlRules . getInvariants ( ) , plugins , stateComparator , onURLSetTemp ) ; context . setStateMachine ( stateMachine ) ; crawlpath = new CrawlPath ( ) ; context . setCrawlPath ( crawlpath ) ; browser . handlePopups ( ) ; browser . goToUrl ( url ) ; // Checks the landing page for URL and sets the current page accordingly checkOnURLState ( ) ; plugins . runOnUrlLoadPlugins ( context ) ; crawlDepth . set ( 0 ) ; } | Reset the crawler to its initial state . | 208 | 10 |
147,094 | 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 ; try { isFired = browser . fireEventAndWait ( eventToFire ) ; } catch ( ElementNotVisibleException | NoSuchElementException e ) { if ( crawlRules . isCrawlHiddenAnchors ( ) && eventToFire . getElement ( ) != null && "A" . equals ( eventToFire . getElement ( ) . getTag ( ) ) ) { isFired = visitAnchorHrefIfPossible ( eventToFire ) ; } else { LOG . debug ( "Ignoring invisible element {}" , eventToFire . getElement ( ) ) ; } } catch ( InterruptedException e ) { LOG . debug ( "Interrupted during fire event" ) ; interruptThread ( ) ; return false ; } LOG . debug ( "Event fired={} for eventable {}" , isFired , eventable ) ; if ( isFired ) { // Let the controller execute its specified wait operation on the browser thread safe. waitConditionChecker . wait ( browser ) ; browser . closeOtherWindows ( ) ; return true ; } else { /* * Execute the OnFireEventFailedPlugins with the current crawlPath with the crawlPath * removed 1 state to represent the path TO here. */ plugins . runOnFireEventFailedPlugins ( context , eventable , crawlpath . immutableCopyWithoutLast ( ) ) ; return false ; // no event fired } } | Try to fire a given event on the Browser . | 385 | 10 |
147,095 | public StateVertex crawlIndex ( ) { LOG . debug ( "Setting up vertex of the index page" ) ; if ( basicAuthUrl != null ) { browser . goToUrl ( basicAuthUrl ) ; } browser . goToUrl ( url ) ; // Run url first load plugin to clear the application state plugins . runOnUrlFirstLoadPlugins ( context ) ; plugins . runOnUrlLoadPlugins ( context ) ; StateVertex index = vertexFactory . createIndex ( url . toString ( ) , browser . getStrippedDom ( ) , stateComparator . getStrippedDom ( browser ) , browser ) ; Preconditions . checkArgument ( index . getId ( ) == StateVertex . INDEX_ID , "It seems some the index state is crawled more than once." ) ; LOG . debug ( "Parsing the index for candidate elements" ) ; ImmutableList < CandidateElement > extract = candidateExtractor . extract ( index ) ; plugins . runPreStateCrawlingPlugins ( context , extract , index ) ; candidateActionCache . addActions ( extract , index ) ; return index ; } | This method calls the index state . It should be called once per crawl in order to setup the crawl . | 241 | 21 |
147,096 | 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 . | 66 | 14 |
147,097 | 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 [ size1 ] [ size2 ] ; deltaBit = new byte [ size1 ] [ size2 ] ; costV = new long [ 3 ] [ size1 ] [ size2 ] ; costW = new long [ 3 ] [ size2 ] ; // Calculate delta between every leaf in G (empty tree) and all the nodes in F. // Calculate it both sides: leafs of F and nodes of G & leafs of G and nodes of // F. int [ ] labels1 = it1 . getInfoArray ( POST2_LABEL ) ; int [ ] labels2 = it2 . getInfoArray ( POST2_LABEL ) ; int [ ] sizes1 = it1 . getInfoArray ( POST2_SIZE ) ; int [ ] sizes2 = it2 . getInfoArray ( POST2_SIZE ) ; for ( int x = 0 ; x < sizes1 . length ; x ++ ) { // for all nodes of initially left tree for ( int y = 0 ; y < sizes2 . length ; y ++ ) { // for all nodes of initially right tree // This is an attempt for distances of single-node subtree and anything alse // The differences between pairs of labels are stored if ( labels1 [ x ] == labels2 [ y ] ) { deltaBit [ x ] [ y ] = 0 ; } else { deltaBit [ x ] [ y ] = 1 ; // if this set, the labels differ, cost of relabeling is set // to costMatch } if ( sizes1 [ x ] == 1 && sizes2 [ y ] == 1 ) { // both nodes are leafs delta [ x ] [ y ] = 0 ; } else { if ( sizes1 [ x ] == 1 ) { delta [ x ] [ y ] = sizes2 [ y ] - 1 ; } if ( sizes2 [ y ] == 1 ) { delta [ x ] [ y ] = sizes1 [ x ] - 1 ; } } } } } | Initialization method . | 528 | 4 |
147,098 | 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 , nextState ) ) { LOGGER . debug ( "Changed to state: '{}' from: '{}'" , nextState . getName ( ) , currentState . getName ( ) ) ; setCurrentState ( nextState ) ; return true ; } else { LOGGER . info ( "Cannot go to state: '{}' from: '{}'" , nextState . getName ( ) , currentState . getName ( ) ) ; return false ; } } | Change the currentState to the nextState if possible . The next state should already be present in the graph . | 194 | 22 |
147,099 | private StateVertex addStateToCurrentState ( StateVertex newState , Eventable eventable ) { LOGGER . debug ( "addStateToCurrentState currentState: {} newState {}" , currentState . getName ( ) , newState . getName ( ) ) ; // Add the state to the stateFlowGraph. Store the result StateVertex cloneState = stateFlowGraph . putIfAbsent ( newState ) ; // Is there a clone detected? if ( cloneState != null ) { LOGGER . info ( "CLONE State detected: {} and {} are the same." , newState . getName ( ) , cloneState . getName ( ) ) ; LOGGER . debug ( "CLONE CURRENT STATE: {}" , currentState . getName ( ) ) ; LOGGER . debug ( "CLONE STATE: {}" , cloneState . getName ( ) ) ; LOGGER . debug ( "CLONE CLICKABLE: {}" , eventable ) ; boolean added = stateFlowGraph . addEdge ( currentState , cloneState , eventable ) ; if ( ! added ) { LOGGER . debug ( "Clone edge !! Need to fix the crawlPath??" ) ; } } else { stateFlowGraph . addEdge ( currentState , newState , eventable ) ; LOGGER . info ( "State {} added to the StateMachine." , newState . getName ( ) ) ; } return cloneState ; } | Adds the newState and the edge between the currentState and the newState on the SFG . | 303 | 20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.