idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
2,800
public void addInt16 ( final int key , final short s ) { PebbleTuple t = PebbleTuple . create ( key , PebbleTuple . TupleType . INT , PebbleTuple . Width . SHORT , s ) ; addTuple ( t ) ; }
Associate the specified signed short with the provided key in the dictionary . If another key - value pair with the same key is already present in the dictionary it will be replaced .
2,801
public void addUint16 ( final int key , final short s ) { PebbleTuple t = PebbleTuple . create ( key , PebbleTuple . TupleType . UINT , PebbleTuple . Width . SHORT , s ) ; addTuple ( t ) ; }
Associate the specified unsigned short with the provided key in the dictionary . If another key - value pair with the same key is already present in the dictionary it will be replaced .
2,802
public void addInt32 ( final int key , final int i ) { PebbleTuple t = PebbleTuple . create ( key , PebbleTuple . TupleType . INT , PebbleTuple . Width . WORD , i ) ; addTuple ( t ) ; }
Associate the specified signed int with the provided key in the dictionary . If another key - value pair with the same key is already present in the dictionary it will be replaced .
2,803
public void addUint32 ( final int key , final int i ) { PebbleTuple t = PebbleTuple . create ( key , PebbleTuple . TupleType . UINT , PebbleTuple . Width . WORD , i ) ; addTuple ( t ) ; }
Associate the specified unsigned int with the provided key in the dictionary . If another key - value pair with the same key is already present in the dictionary it will be replaced .
2,804
public Long getInteger ( int key ) { PebbleTuple tuple = getTuple ( key , PebbleTuple . TupleType . INT ) ; if ( tuple == null ) { return null ; } return ( Long ) tuple . value ; }
Returns the signed integer to which the specified key is mapped or null if the key does not exist in this dictionary .
2,805
public Long getUnsignedIntegerAsLong ( int key ) { PebbleTuple tuple = getTuple ( key , PebbleTuple . TupleType . UINT ) ; if ( tuple == null ) { return null ; } return ( Long ) tuple . value ; }
Returns the unsigned integer as a long to which the specified key is mapped or null if the key does not exist in this dictionary . We are using the Long type here so that we can remove the guava dependency . This is done so that we dont have incompatibility issues with the UnsignedInteger class from the Holo application which uses a newer version of Guava .
2,806
public byte [ ] getBytes ( int key ) { PebbleTuple tuple = getTuple ( key , PebbleTuple . TupleType . BYTES ) ; if ( tuple == null ) { return null ; } return ( byte [ ] ) tuple . value ; }
Returns the byte array to which the specified key is mapped or null if the key does not exist in this dictionary .
2,807
public String getString ( int key ) { PebbleTuple tuple = getTuple ( key , PebbleTuple . TupleType . STRING ) ; if ( tuple == null ) { return null ; } return ( String ) tuple . value ; }
Returns the string to which the specified key is mapped or null if the key does not exist in this dictionary .
2,808
public String toJsonString ( ) { try { JSONArray array = new JSONArray ( ) ; for ( PebbleTuple t : tuples . values ( ) ) { array . put ( serializeTuple ( t ) ) ; } return array . toString ( ) ; } catch ( JSONException je ) { je . printStackTrace ( ) ; } return null ; }
Returns a JSON representation of this dictionary .
2,809
public static PebbleDictionary fromJson ( String jsonString ) throws JSONException { PebbleDictionary d = new PebbleDictionary ( ) ; JSONArray elements = new JSONArray ( jsonString ) ; for ( int idx = 0 ; idx < elements . length ( ) ; ++ idx ) { JSONObject o = elements . getJSONObject ( idx ) ; final int key = o . getInt ( KEY ) ; final PebbleTuple . TupleType type = PebbleTuple . TYPE_NAMES . get ( o . getString ( TYPE ) ) ; final PebbleTuple . Width width = PebbleTuple . WIDTH_MAP . get ( o . getInt ( LENGTH ) ) ; switch ( type ) { case BYTES : byte [ ] bytes = Base64 . decode ( o . getString ( VALUE ) , Base64 . NO_WRAP ) ; d . addBytes ( key , bytes ) ; break ; case STRING : d . addString ( key , o . getString ( VALUE ) ) ; break ; case INT : if ( width == PebbleTuple . Width . BYTE ) { d . addInt8 ( key , ( byte ) o . getInt ( VALUE ) ) ; } else if ( width == PebbleTuple . Width . SHORT ) { d . addInt16 ( key , ( short ) o . getInt ( VALUE ) ) ; } else if ( width == PebbleTuple . Width . WORD ) { d . addInt32 ( key , o . getInt ( VALUE ) ) ; } break ; case UINT : if ( width == PebbleTuple . Width . BYTE ) { d . addUint8 ( key , ( byte ) o . getInt ( VALUE ) ) ; } else if ( width == PebbleTuple . Width . SHORT ) { d . addUint16 ( key , ( short ) o . getInt ( VALUE ) ) ; } else if ( width == PebbleTuple . Width . WORD ) { d . addUint32 ( key , o . getInt ( VALUE ) ) ; } break ; } } return d ; }
Deserializes a JSON representation of a PebbleDictionary .
2,810
protected void processInput ( String input ) { String command = input . trim ( ) ; if ( ! command . isEmpty ( ) ) { runCommand ( command ) ; } }
Process an input line entered through the console .
2,811
public void start ( ) { try { final Terminal terminal = TerminalConsoleAppender . getTerminal ( ) ; if ( terminal != null ) { readCommands ( terminal ) ; } else { readCommands ( System . in ) ; } } catch ( IOException e ) { LogManager . getLogger ( "TerminalConsole" ) . error ( "Failed to read console input" , e ) ; } }
Start reading commands from the console .
2,812
public void setPaceInSec ( int paceInSec ) { this . speed = null ; this . paceInSec = Math . max ( 0 , Math . min ( paceInSec , 3599 ) ) ; }
Set the current pace in seconds per kilometer or seconds per mile .
2,813
public void setSpeed ( float speed ) { this . paceInSec = null ; this . speed = Math . max ( 0 , Math . min ( speed , 99.9 ) ) ; }
Set the current speed in kilometers per hour or miles per hour .
2,814
public void synchronize ( final Context context ) { SportsState previousState = this . previousState ; boolean firstMessage = false ; if ( previousState == null ) { previousState = this . previousState = new SportsState ( ) ; firstMessage = true ; } PebbleDictionary message = new PebbleDictionary ( ) ; if ( getTimeInSec ( ) != previousState . getTimeInSec ( ) || firstMessage ) { previousState . setTimeInSec ( getTimeInSec ( ) ) ; message . addString ( Constants . SPORTS_TIME_KEY , convertSecondsToString ( getTimeInSec ( ) ) ) ; } if ( getDistance ( ) != previousState . getDistance ( ) || firstMessage ) { previousState . setDistance ( getDistance ( ) ) ; message . addString ( Constants . SPORTS_DISTANCE_KEY , convertDistanceToString ( getDistance ( ) ) ) ; } if ( this . paceInSec != null ) { message . addUint8 ( Constants . SPORTS_LABEL_KEY , ( byte ) Constants . SPORTS_DATA_PACE ) ; if ( getPaceInSec ( ) != previousState . getPaceInSec ( ) ) { previousState . setPaceInSec ( getPaceInSec ( ) ) ; message . addString ( Constants . SPORTS_DATA_KEY , convertSecondsToString ( getPaceInSec ( ) ) ) ; } } if ( this . speed != null ) { message . addUint8 ( Constants . SPORTS_LABEL_KEY , ( byte ) Constants . SPORTS_DATA_SPEED ) ; if ( getSpeed ( ) != previousState . getSpeed ( ) ) { previousState . setSpeed ( getSpeed ( ) ) ; message . addString ( Constants . SPORTS_DATA_KEY , convertDistanceToString ( getSpeed ( ) ) ) ; } } if ( this . heartBPM != null ) { if ( getHeartBPM ( ) != previousState . getHeartBPM ( ) ) { previousState . setHeartBPM ( getHeartBPM ( ) ) ; message . addUint8 ( Constants . SPORTS_HR_BPM_KEY , getHeartBPM ( ) ) ; } } if ( getCustomLabel ( ) != null && getCustomValue ( ) != null ) { if ( ! getCustomLabel ( ) . equals ( previousState . getCustomLabel ( ) ) ) { previousState . setCustomLabel ( getCustomLabel ( ) ) ; message . addString ( Constants . SPORTS_CUSTOM_LABEL_KEY , getCustomLabel ( ) ) ; } if ( ! getCustomValue ( ) . equals ( previousState . getCustomValue ( ) ) ) { previousState . setCustomValue ( getCustomValue ( ) ) ; message . addString ( Constants . SPORTS_CUSTOM_VALUE_KEY , getCustomValue ( ) ) ; } } PebbleKit . sendDataToPebble ( context , Constants . SPORTS_UUID , message ) ; }
Synchronizes the current state of the Sports App to the connected watch .
2,815
public BaseAttacher start ( ) { if ( mAdapterView == null ) { throw new IllegalStateException ( "Adapter View cannot be null" ) ; } if ( mMugenCallbacks == null ) { throw new IllegalStateException ( "MugenCallbacks cannot be null" ) ; } if ( mLoadMoreOffset <= 0 ) { throw new IllegalStateException ( "Trigger Offset must be > 0" ) ; } mIsLoadMoreEnabled = true ; init ( ) ; return this ; }
Begin load more on the attached Adapter View
2,816
public static < T > MatcherDecoratorsBuilder < T > should ( final Matcher < ? super T > matcher ) { return MatcherDecoratorsBuilder . should ( matcher ) ; }
Factory method for decorating matcher with action condition or waiter .
2,817
private boolean nextWithoutLimit ( ) throws SQLException { if ( maxRows > 0 && rowsFetched >= maxRows ) { System . out . println ( "Reach max rows " + maxRows ) ; return false ; } if ( ( recordItr == null || ! recordItr . hasNext ( ) ) && ! emptyResultSet ) { TSFetchResultsReq req = new TSFetchResultsReq ( sql , fetchSize ) ; try { TSFetchResultsResp resp = client . fetchResults ( req ) ; Utils . verifySuccess ( resp . getStatus ( ) ) ; if ( ! resp . hasResultSet ) { emptyResultSet = true ; } else { TSQueryDataSet tsQueryDataSet = resp . getQueryDataSet ( ) ; List < RowRecord > records = Utils . convertRowRecords ( tsQueryDataSet ) ; recordItr = records . iterator ( ) ; } } catch ( TException e ) { throw new SQLException ( "Cannot fetch result from server, because of network connection" ) ; } } if ( emptyResultSet ) { return false ; } record = recordItr . next ( ) ; rowsFetched ++ ; return true ; }
the next record rule without considering the LIMIT&SLIMIT constraints
2,818
public QueryAtomGroupImpl pop ( ) { QueryAtomGroupImpl group = new QueryAtomGroupImpl ( ) ; boolean first = true ; for ( QueryAtom atom : atoms ) { if ( first ) { first = false ; } else { group . addAtom ( atom ) ; } } return group ; }
A convenience method to clone the atom group instance and pop the first atom . Only the instance itself will be cloned not the atoms .
2,819
public QueryAtomGroupImpl bind ( QueryBinding binding ) { QueryAtomGroupImpl group = new QueryAtomGroupImpl ( ) ; for ( QueryAtom atom : atoms ) { group . addAtom ( atom . bind ( binding ) ) ; } return group ; }
A convenience method to clone the atom group instance while inserting a new binding to all atoms of the group . The instance and the atoms will be cloned .
2,820
public void addResultVar ( QueryArgument arg ) { if ( arg . getType ( ) == QueryArgumentType . VAR ) { resultVars . add ( arg ) ; } }
Add a result variable to the query .
2,821
public boolean isCommandInstalled ( String command , String failureMessage ) { List < String > output = getProcessManager ( ) . executeAndJoinOutput ( command ) ; return output . size ( ) > 0 && ! output . get ( 0 ) . contains ( failureMessage ) ; }
True if the given command is installed in the shell false otherwise .
2,822
public boolean confirmInstalled ( String packageName , List < String > output ) { if ( output != null ) { return output . stream ( ) . anyMatch ( s -> s != null && s . contains ( getInstallSuccess ( ) ) ) ; } else { return true ; } }
Checks the output to confirm the package is installed .
2,823
protected boolean isPermissionDenied ( List < String > output ) { return output . stream ( ) . anyMatch ( s -> s != null && s . contains ( PERMISSION_DENIED_MESSAGE ) ) ; }
Returns true if permission was denied .
2,824
public static void premain ( String agentArgs , Instrumentation inst ) throws YamlConvertException , IllegalTestScriptException , IOException , ClassNotFoundException , InstantiationException , IllegalAccessException { String configFilePath ; String propValue = System . getProperty ( "sahagin.configPath" ) ; if ( ! StringUtils . isBlank ( propValue ) ) { configFilePath = propValue ; } else if ( agentArgs != null ) { configFilePath = agentArgs ; } else { configFilePath = "sahagin.yml" ; } JavaConfig config = JavaConfig . generateFromYamlConfig ( new File ( configFilePath ) ) ; Logging . setLoggerEnabled ( config . isOutputLog ( ) ) ; AcceptableLocales locales = AcceptableLocales . getInstance ( config . getUserLocale ( ) ) ; JavaAdapterContainer . globalInitialize ( locales , config . getTestFramework ( ) ) ; SysMessages . globalInitialize ( locales ) ; new JavaSystemAdapter ( ) . initialSetAdapter ( ) ; new JUnit3Adapter ( ) . initialSetAdapter ( ) ; new JUnit4Adapter ( ) . initialSetAdapter ( ) ; new TestNGAdapter ( ) . initialSetAdapter ( ) ; new JavaLibAdapter ( ) . initialSetAdapter ( ) ; new WebDriverAdapter ( ) . initialSetAdapter ( ) ; new AppiumAdapter ( ) . initialSetAdapter ( ) ; new SelendroidAdapter ( ) . initialSetAdapter ( ) ; new IOSDriverAdapter ( ) . initialSetAdapter ( ) ; new FluentLeniumAdapter ( ) . initialSetAdapter ( ) ; for ( String adapterClassName : config . getAdapterClassNames ( ) ) { Class < ? > adapterClass = Class . forName ( adapterClassName ) ; assert adapterClass != null ; Object adapterObj = adapterClass . newInstance ( ) ; assert adapterObj != null ; assert adapterObj instanceof Adapter ; Adapter adapter = ( Adapter ) adapterObj ; adapter . initialSetAdapter ( ) ; } if ( ! JavaAdapterContainer . globalInstance ( ) . isRootMethodAdapterSet ( ) ) { throw new RuntimeException ( String . format ( MSG_TEST_FRAMEWORK_NOT_FOUND , config . getTestFramework ( ) ) ) ; } if ( config . getRootBaseRunOutputIntermediateDataDir ( ) . exists ( ) ) { FileUtils . deleteDirectory ( config . getRootBaseRunOutputIntermediateDataDir ( ) ) ; } SrcTree srcTree = generateAndDumpSrcTree ( config , locales ) ; RunResultsGenerateHookSetter transformer = new RunResultsGenerateHookSetter ( configFilePath , srcTree ) ; inst . addTransformer ( transformer ) ; }
agentArgs is configuration YAML file path
2,825
public static int getUInt16 ( byte [ ] src , int offset ) { final int v0 = src [ offset + 0 ] & 0xFF ; final int v1 = src [ offset + 1 ] & 0xFF ; return ( ( v1 << 8 ) | v0 ) ; }
Gets a 16 - bit unsigned integer from the given byte array at the given offset .
2,826
public static void setInt16 ( byte [ ] dst , int offset , int value ) { assert ( value & 0xffff ) == value : "value out of range" ; dst [ offset + 0 ] = ( byte ) ( value & 0xFF ) ; dst [ offset + 1 ] = ( byte ) ( ( value >>> 8 ) & 0xFF ) ; }
Sets a 16 - bit integer in the given byte array at the given offset .
2,827
public static void setInt32 ( byte [ ] dst , int offset , long value ) throws IllegalArgumentException { assert value <= Integer . MAX_VALUE : "value out of range" ; dst [ offset + 0 ] = ( byte ) ( value & 0xFF ) ; dst [ offset + 1 ] = ( byte ) ( ( value >>> 8 ) & 0xFF ) ; dst [ offset + 2 ] = ( byte ) ( ( value >>> 16 ) & 0xFF ) ; dst [ offset + 3 ] = ( byte ) ( ( value >>> 24 ) & 0xFF ) ; }
Sets a 32 - bit integer in the given byte array at the given offset .
2,828
public FatFileSystem format ( ) throws IOException { final int sectorSize = device . getSectorSize ( ) ; final int totalSectors = ( int ) ( device . getSize ( ) / sectorSize ) ; final FsInfoSector fsi ; final BootSector bs ; if ( sectorsPerCluster == 0 ) throw new AssertionError ( ) ; if ( fatType == FatType . FAT32 ) { bs = new Fat32BootSector ( device ) ; initBootSector ( bs ) ; final Fat32BootSector f32bs = ( Fat32BootSector ) bs ; f32bs . setFsInfoSectorNr ( 1 ) ; f32bs . setSectorsPerFat ( sectorsPerFat ( 0 , totalSectors ) ) ; final Random rnd = new Random ( System . currentTimeMillis ( ) ) ; f32bs . setFileSystemId ( rnd . nextInt ( ) ) ; f32bs . setVolumeLabel ( label ) ; fsi = FsInfoSector . create ( f32bs ) ; } else { bs = new Fat16BootSector ( device ) ; initBootSector ( bs ) ; final Fat16BootSector f16bs = ( Fat16BootSector ) bs ; final int rootDirEntries = rootDirectorySize ( device . getSectorSize ( ) , totalSectors ) ; f16bs . setRootDirEntryCount ( rootDirEntries ) ; f16bs . setSectorsPerFat ( sectorsPerFat ( rootDirEntries , totalSectors ) ) ; if ( label != null ) f16bs . setVolumeLabel ( label ) ; fsi = null ; } final Fat fat = Fat . create ( bs , 0 ) ; final AbstractDirectory rootDirStore ; if ( fatType == FatType . FAT32 ) { rootDirStore = ClusterChainDirectory . createRoot ( fat ) ; fsi . setFreeClusterCount ( fat . getFreeClusterCount ( ) ) ; fsi . setLastAllocatedCluster ( fat . getLastAllocatedCluster ( ) ) ; fsi . write ( ) ; } else { rootDirStore = Fat16RootDirectory . create ( ( Fat16BootSector ) bs ) ; } final FatLfnDirectory rootDir = new FatLfnDirectory ( rootDirStore , fat , false ) ; rootDir . flush ( ) ; for ( int i = 0 ; i < bs . getNrFats ( ) ; i ++ ) { fat . writeCopy ( bs . getFatOffset ( i ) ) ; } bs . write ( ) ; if ( fatType == FatType . FAT32 ) { Fat32BootSector f32bs = ( Fat32BootSector ) bs ; f32bs . writeCopy ( device ) ; } FatFileSystem fs = FatFileSystem . read ( device , false ) ; if ( label != null ) { fs . setVolumeLabel ( label ) ; } fs . flush ( ) ; return fs ; }
Initializes the boot sector and file system for the device . The file system created by this method will always be in read - write mode .
2,829
public boolean matchesStackLines ( List < StackLine > targetStackLines ) { if ( targetStackLines . size ( ) != getStackLines ( ) . size ( ) ) { return false ; } for ( int i = 0 ; i < targetStackLines . size ( ) ; i ++ ) { StackLine targetLine = targetStackLines . get ( i ) ; StackLine line = getStackLines ( ) . get ( i ) ; if ( ! targetLine . getMethod ( ) . getKey ( ) . equals ( line . getMethod ( ) . getKey ( ) ) ) { return false ; } if ( targetLine . getCodeBodyIndex ( ) != line . getCodeBodyIndex ( ) ) { return false ; } } return true ; }
check if stack line for this instance matches targetStackLines
2,830
public Webcam getWebcam ( String name , Dimension dimension ) { if ( name == null ) { return getWebcam ( dimension ) ; } Webcam webcam = webcams . get ( name ) ; openWebcam ( webcam , dimension ) ; return webcam ; }
Returns the webcam by name null if not found .
2,831
public Webcam getWebcam ( Dimension dimension ) { if ( webcams . size ( ) == 0 ) { throw new IllegalStateException ( "No webcams found" ) ; } Webcam webcam = webcams . values ( ) . iterator ( ) . next ( ) ; openWebcam ( webcam , dimension ) ; return webcam ; }
Returns the first webcam .
2,832
public void beforeMethodHook ( String hookedClassQualifiedName , String hookedMethodSimpleName , String actualHookedMethodSimpleName ) { if ( currentRunResult != null ) { return ; } List < TestMethod > rootMethods = srcTree . getRootMethodTable ( ) . getByName ( hookedClassQualifiedName , hookedMethodSimpleName ) ; if ( rootMethods . size ( ) == 0 ) { return ; } assert rootMethods . size ( ) == 1 ; TestMethod rootMethod = rootMethods . get ( 0 ) ; logger . info ( "beforeMethodHook: " + hookedMethodSimpleName ) ; currentCaptureNo = 1 ; currentRunResult = new RootMethodRunResult ( ) ; currentRunResult . setRootMethodKey ( rootMethod . getKey ( ) ) ; currentRunResult . setRootMethod ( rootMethod ) ; currentActualRootMethodSimpleName = actualHookedMethodSimpleName ; startMethodTime = System . currentTimeMillis ( ) ; }
initialize runResult information if the method for the arguments is root method
2,833
public void methodErrorHook ( String hookedClassQualifiedName , String hookedMethodSimpleName , Throwable e ) { if ( currentRunResult == null ) { return ; } TestMethod rootMethod = currentRunResult . getRootMethod ( ) ; if ( ! rootMethod . getTestClassKey ( ) . equals ( hookedClassQualifiedName ) || ! rootMethod . getSimpleName ( ) . equals ( hookedMethodSimpleName ) ) { return ; } RunFailure runFailure = new RunFailure ( ) ; runFailure . setMessage ( e . getClass ( ) . getCanonicalName ( ) + ": " + e . getLocalizedMessage ( ) ) ; runFailure . setStackTrace ( ExceptionUtils . getStackTrace ( e ) ) ; LineReplacer replacer = new LineReplacer ( ) { public void replace ( String classQualifiedName , String methodSimpleName , int line ) { super . replace ( classQualifiedName , methodSimpleName , line ) ; if ( StringUtils . equals ( methodSimpleName , currentActualRootMethodSimpleName ) ) { replaceMethodSimpleName ( currentRunResult . getRootMethod ( ) . getSimpleName ( ) ) ; } } } ; List < StackLine > stackLines = StackLineUtils . getStackLines ( srcTree , e . getStackTrace ( ) , replacer ) ; for ( StackLine stackLine : stackLines ) { runFailure . addStackLine ( stackLine ) ; } currentRunResult . addRunFailure ( runFailure ) ; captureScreenForStackLines ( rootMethod , Arrays . asList ( stackLines ) , Arrays . asList ( - 1 ) ) ; }
This method must be called before afterMethodHook is called
2,834
public void afterMethodHook ( String hookedClassQualifiedName , String hookedMethodSimpleName ) { if ( currentRunResult == null ) { return ; } TestMethod rootMethod = currentRunResult . getRootMethod ( ) ; if ( ! rootMethod . getTestClassKey ( ) . equals ( hookedClassQualifiedName ) || ! rootMethod . getSimpleName ( ) . equals ( hookedMethodSimpleName ) ) { return ; } long currentTime = System . currentTimeMillis ( ) ; currentRunResult . setExecutionTime ( ( int ) ( currentTime - startMethodTime ) ) ; logger . info ( "afterMethodHook: " + hookedMethodSimpleName ) ; File runResultFile = new File ( String . format ( "%s/%s/%s" , runResultsRootDir , CommonUtils . encodeToSafeAsciiFileNameString ( hookedClassQualifiedName , StandardCharsets . UTF_8 ) , CommonUtils . encodeToSafeAsciiFileNameString ( hookedMethodSimpleName , StandardCharsets . UTF_8 ) ) ) ; if ( runResultFile . getParentFile ( ) != null ) { runResultFile . getParentFile ( ) . mkdirs ( ) ; } YamlUtils . dump ( currentRunResult . toYamlObject ( ) , runResultFile ) ; currentCaptureNo = - 1 ; currentRunResult = null ; currentActualRootMethodSimpleName = null ; }
write runResult to YAML file if the method for the arguments is root method
2,835
private List < StackLine > getCodeLineHookedStackLines ( final String hookedMethodSimpleName , final String actualHookedMethodSimpleName , final int hookedLine , final int actualHookedLine ) { LineReplacer replacer = new LineReplacer ( ) { public void replace ( String classQualifiedName , String methodSimpleName , int line ) { super . replace ( classQualifiedName , methodSimpleName , line ) ; if ( StringUtils . equals ( methodSimpleName , currentActualRootMethodSimpleName ) ) { replaceMethodSimpleName ( currentRunResult . getRootMethod ( ) . getSimpleName ( ) ) ; } if ( StringUtils . equals ( methodSimpleName , actualHookedMethodSimpleName ) && ( line == actualHookedLine ) ) { replaceMethodSimpleName ( hookedMethodSimpleName ) ; replaceLine ( hookedLine ) ; } } } ; List < StackLine > result = StackLineUtils . getStackLines ( srcTree , Thread . currentThread ( ) . getStackTrace ( ) , replacer ) ; assert result . size ( ) > 0 ; return result ; }
get the stackLines for the hook method code line .
2,836
private String getCodeLineKey ( final String hookedClassQualifiedName , final String hookedMethodSimpleName , String hookedArgClassesStr , final int hookedLine ) { return String . format ( "%s_%s_%s_%d_%d" , hookedClassQualifiedName , hookedMethodSimpleName , hookedArgClassesStr , hookedLine , Thread . currentThread ( ) . getStackTrace ( ) . length ) ; }
Calculate unique key for each code line hook
2,837
private File captureScreen ( TestMethod rootMethod ) { byte [ ] screenData = AdapterContainer . globalInstance ( ) . captureScreen ( ) ; if ( screenData == null ) { return null ; } File captureFile = new File ( String . format ( "%s/%s/%s/%03d.png" , captureRootDir , CommonUtils . encodeToSafeAsciiFileNameString ( rootMethod . getTestClass ( ) . getQualifiedName ( ) , StandardCharsets . UTF_8 ) , CommonUtils . encodeToSafeAsciiFileNameString ( rootMethod . getSimpleName ( ) , StandardCharsets . UTF_8 ) , currentCaptureNo ) ) ; currentCaptureNo ++ ; if ( captureFile . getParentFile ( ) != null ) { captureFile . getParentFile ( ) . mkdirs ( ) ; } FileOutputStream stream = null ; try { stream = new FileOutputStream ( captureFile ) ; stream . write ( screenData ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } finally { IOUtils . closeQuietly ( stream ) ; } return captureFile ; }
returns null if not executed
2,838
private File captureScreenForStackLines ( TestMethod rootMethod , List < List < StackLine > > stackLinesList , List < Integer > executionTimes ) { if ( stackLinesList == null ) { throw new NullPointerException ( ) ; } if ( stackLinesList . size ( ) == 0 ) { throw new IllegalArgumentException ( "empty list" ) ; } if ( stackLinesList . size ( ) != executionTimes . size ( ) ) { throw new IllegalArgumentException ( "size mismatch" ) ; } File captureFile = captureScreen ( rootMethod ) ; if ( captureFile == null ) { return null ; } for ( int i = 0 ; i < stackLinesList . size ( ) ; i ++ ) { LineScreenCapture capture = new LineScreenCapture ( ) ; capture . setPath ( new File ( captureFile . getAbsolutePath ( ) ) ) ; capture . addAllStackLines ( stackLinesList . get ( i ) ) ; capture . setExecutionTime ( executionTimes . get ( i ) ) ; currentRunResult . addLineScreenCapture ( capture ) ; } return captureFile ; }
- returns null if fails to capture
2,839
private boolean canStepInCaptureTo ( List < StackLine > stackLines ) { for ( int i = 0 ; i < stackLines . size ( ) - 1 ; i ++ ) { StackLine stackLine = stackLines . get ( i ) ; CaptureStyle style = stackLine . getMethod ( ) . getCaptureStyle ( ) ; if ( style != CaptureStyle . STEP_IN && style != CaptureStyle . STEP_IN_ONLY ) { return false ; } } return true ; }
if method is called from not stepInCapture line then returns false .
2,840
public String getAPIAccessMode ( ) { String apiAccessMode = ( String ) getScenarioGlobals ( ) . getAttribute ( API_ACCESS_MODE_KEY ) ; return apiAccessMode == null ? HTTP_API_ACCESS_MODE : apiAccessMode ; }
When the api is accessed though the browser selenium is used though straight HTTP calls we can choose to POST or GET the api
2,841
private void setRequestHeaders ( HttpURLConnection ucon , GenericUser authenticationUser , String [ ] requestHedaers ) { if ( authenticationUser != null ) { String authenticationString = authenticationUser . getUserName ( ) + ":" + authenticationUser . getPassword ( ) ; byte [ ] encodedAuthentication = Base64 . encodeBase64 ( authenticationString . getBytes ( ) ) ; String authenticationHeaderValue = "Basic " + new String ( encodedAuthentication ) ; ucon . setRequestProperty ( "Authorization" , authenticationHeaderValue ) ; } for ( int i = 0 ; i < requestHedaers . length ; i = i + 2 ) { ucon . setRequestProperty ( getReferenceService ( ) . namespaceString ( requestHedaers [ i ] ) , getReferenceService ( ) . namespaceString ( requestHedaers [ i + 1 ] ) ) ; } }
Add the request headers to the request
2,842
private static Map < Locale , String > getAllPageDocs ( IAnnotationBinding [ ] annotations ) { List < IAnnotationBinding > allPageAnnotations = new ArrayList < > ( 2 ) ; List < Class < ? > > singlePageAnnotationClasses = new ArrayList < > ( 2 ) ; singlePageAnnotationClasses . add ( PageDoc . class ) ; singlePageAnnotationClasses . add ( Page . class ) ; for ( Class < ? > annotationClass : singlePageAnnotationClasses ) { IAnnotationBinding annotation = getAnnotationBinding ( annotations , annotationClass ) ; if ( annotation == null ) { continue ; } if ( allPageAnnotations . size ( ) > 0 ) { throw new RuntimeException ( "don't use multiple page annoations at the same place" ) ; } allPageAnnotations . add ( annotation ) ; } List < Class < ? > > multiplePageAnnotationClasses = new ArrayList < > ( 2 ) ; multiplePageAnnotationClasses . add ( PageDocs . class ) ; multiplePageAnnotationClasses . add ( Pages . class ) ; for ( Class < ? > annotationClass : multiplePageAnnotationClasses ) { IAnnotationBinding annotation = getAnnotationBinding ( annotations , annotationClass ) ; if ( annotation == null ) { continue ; } if ( allPageAnnotations . size ( ) > 0 ) { throw new RuntimeException ( "don't use multiple page annoations at the same place" ) ; } Object value = getAnnotationValue ( annotation , "value" ) ; Object [ ] values = ( Object [ ] ) value ; for ( Object element : values ) { allPageAnnotations . add ( ( IAnnotationBinding ) element ) ; } } Map < Locale , String > resultPageMap = new HashMap < > ( allPageAnnotations . size ( ) ) ; for ( IAnnotationBinding eachPageAnnotation : allPageAnnotations ) { Object value = getAnnotationValue ( eachPageAnnotation , "value" ) ; Locale locale = getAnnotationLocaleValue ( eachPageAnnotation , "locale" ) ; resultPageMap . put ( locale , ( String ) value ) ; } return resultPageMap ; }
return empty list if no Page is found
2,843
private static String getPageDoc ( IAnnotationBinding [ ] annotations , AcceptableLocales locales ) { Map < Locale , String > allPages = getAllPageDocs ( annotations ) ; if ( allPages . isEmpty ( ) ) { return null ; } for ( Locale locale : locales . getLocales ( ) ) { String value = allPages . get ( locale ) ; if ( value != null ) { return value ; } } return "" ; }
return null if no Page found
2,844
private void read ( ) throws IOException { final byte [ ] data = new byte [ sectorCount * sectorSize ] ; device . read ( offset , ByteBuffer . wrap ( data ) ) ; for ( int i = 0 ; i < entries . length ; i ++ ) entries [ i ] = fatType . readEntry ( data , i ) ; }
Read the contents of this FAT from the given device at the given offset .
2,845
public void writeCopy ( long offset ) throws IOException { final byte [ ] data = new byte [ sectorCount * sectorSize ] ; for ( int index = 0 ; index < entries . length ; index ++ ) { fatType . writeEntry ( data , index , entries [ index ] ) ; } device . write ( offset , ByteBuffer . wrap ( data ) ) ; }
Write the contents of this FAT to the given device at the given offset .
2,846
public long getNextCluster ( long cluster ) { testCluster ( cluster ) ; long entry = entries [ ( int ) cluster ] ; if ( isEofCluster ( entry ) ) { return - 1 ; } else { return entry ; } }
Gets the cluster after the given cluster
2,847
public long allocNew ( ) throws IOException { int i ; int entryIndex = - 1 ; for ( i = lastAllocatedCluster ; i < lastClusterIndex ; i ++ ) { if ( isFreeCluster ( i ) ) { entryIndex = i ; break ; } } if ( entryIndex < 0 ) { for ( i = FIRST_CLUSTER ; i < lastAllocatedCluster ; i ++ ) { if ( isFreeCluster ( i ) ) { entryIndex = i ; break ; } } } if ( entryIndex < 0 ) { throw new IOException ( "FAT Full (" + ( lastClusterIndex - FIRST_CLUSTER ) + ", " + i + ")" ) ; } entries [ entryIndex ] = fatType . getEofMarker ( ) ; lastAllocatedCluster = entryIndex % lastClusterIndex ; if ( lastAllocatedCluster < FIRST_CLUSTER ) lastAllocatedCluster = FIRST_CLUSTER ; return entryIndex ; }
Allocate a cluster for a new file
2,848
public long [ ] allocNew ( int nrClusters ) throws IOException { final long rc [ ] = new long [ nrClusters ] ; rc [ 0 ] = allocNew ( ) ; for ( int i = 1 ; i < nrClusters ; i ++ ) { rc [ i ] = allocAppend ( rc [ i - 1 ] ) ; } return rc ; }
Allocate a series of clusters for a new file .
2,849
public long allocAppend ( long cluster ) throws IOException { testCluster ( cluster ) ; while ( ! isEofCluster ( entries [ ( int ) cluster ] ) ) { cluster = entries [ ( int ) cluster ] ; } long newCluster = allocNew ( ) ; entries [ ( int ) cluster ] = newCluster ; return newCluster ; }
Allocate a cluster to append to a new file
2,850
public static void consumeTPVObject ( TPVObject tpv , Processor processor , GpsdEndpoint endpoint , ExceptionHandler exceptionHandler ) { LOG . debug ( "About to consume TPV object {},{} from {}" , tpv . getLatitude ( ) , tpv . getLongitude ( ) , endpoint ) ; Validate . notNull ( tpv ) ; Validate . notNull ( processor ) ; Validate . notNull ( endpoint ) ; GpsCoordinates coordinates = gpsCoordinates ( new Date ( new Double ( tpv . getTimestamp ( ) ) . longValue ( ) ) , tpv . getLatitude ( ) , tpv . getLongitude ( ) ) ; Exchange exchange = anExchange ( endpoint . getCamelContext ( ) ) . withPattern ( OutOnly ) . withHeader ( TPV_HEADER , tpv ) . withBody ( coordinates ) . build ( ) ; try { processor . process ( exchange ) ; } catch ( Exception e ) { exceptionHandler . handleException ( e ) ; } }
Process the TPVObject all params required .
2,851
public String namespaceString ( String plainString ) throws RuntimeException { if ( plainString . startsWith ( NAME_SPACE_PREFIX ) ) { return ( plainString . replace ( NAME_SPACE_PREFIX , nameSpaceThreadLocale . get ( ) ) ) ; } if ( plainString . startsWith ( SCENARIO_NAME_SPACE_PREFIX ) ) { if ( cucumberManager . getCurrentScenarioGlobals ( ) == null ) { throw new ScenarioNameSpaceAccessOutsideScenarioScopeException ( "You cannot fetch a Scneario namespace outside the scope of a scenario" ) ; } return ( plainString . replace ( SCENARIO_NAME_SPACE_PREFIX , cucumberManager . getCurrentScenarioGlobals ( ) . getNameSpace ( ) ) ) ; } else { return plainString ; } }
Extends the name space prefix with the actual name space All tests that need to ensure privacy i . e . no other test shall mess up their data shall use name spacing . Data that can be messed up by other tests and there fore needs to be unique shall contain the name space prefix that will be replaced at run time .
2,852
public WebElement findExpectedElement ( By by , boolean includeHiddenElements ) { log . debug ( "findExpectedElement() called with: " + by ) ; waitForLoaders ( ) ; try { WebElement foundElement = new WebDriverWait ( getWebDriver ( ) , getSeleniumManager ( ) . getTimeout ( ) ) . until ( ExpectedConditions . presenceOfElementLocated ( by ) ) ; if ( includeHiddenElements || foundElement . isDisplayed ( ) ) { return foundElement ; } else { try { new WebDriverWait ( getWebDriver ( ) , getSeleniumManager ( ) . getTimeout ( ) ) . until ( ExpectedConditions . visibilityOfElementLocated ( by ) ) ; return foundElement ; } catch ( WebDriverException toe ) { fail ( "Element: " + by . toString ( ) + " is found but not visible" ) ; } } } catch ( WebDriverException wde ) { log . error ( "Expected element not found: " , wde ) ; fail ( "Element: " + by . toString ( ) + " not found after waiting for " + getSeleniumManager ( ) . getTimeout ( ) + " seconds. Webdriver though exception: " + wde . getClass ( ) . getCanonicalName ( ) + " with error message: " + wde . getMessage ( ) ) ; } return null ; }
Find an element that is expected to be on the page
2,853
public List < WebElement > findExpectedElements ( By by ) { waitForLoaders ( ) ; try { return new WebDriverWait ( getWebDriver ( ) , getSeleniumManager ( ) . getTimeout ( ) ) . until ( ExpectedConditions . presenceOfAllElementsLocatedBy ( by ) ) ; } catch ( WebDriverException wde ) { log . error ( "Expected elements not found: " , wde ) ; fail ( "Element: " + by . toString ( ) + " not found after waiting for " + getSeleniumManager ( ) . getTimeout ( ) + " seconds. Webdriver though exception: " + wde . getClass ( ) . getCanonicalName ( ) + " with error message: " + wde . getMessage ( ) ) ; } return null ; }
Find all elements expected on the page
2,854
public boolean getElementExists ( By locator ) { waitForLoaders ( ) ; List < WebElement > foundElements = getWebDriver ( ) . findElements ( locator ) ; return ( foundElements . size ( ) > 0 ) ; }
Tells whether the passed element exists
2,855
public void viewShouldNotShowElement ( String viewName , String elementName ) throws IllegalAccessException , InterruptedException { boolean pass = false ; long startOfLookup = System . currentTimeMillis ( ) ; int timeoutInMillies = getSeleniumManager ( ) . getTimeout ( ) * 1000 ; while ( ! pass ) { WebElement found = getElementFromReferencedView ( viewName , elementName ) ; try { pass = ! found . isDisplayed ( ) ; } catch ( NoSuchElementException e ) { pass = true ; } if ( ! pass ) { Thread . sleep ( 100 ) ; } if ( System . currentTimeMillis ( ) - startOfLookup > timeoutInMillies ) { String foundLocator = getElementLocatorFromReferencedView ( viewName , elementName ) ; fail ( "The element \"" + foundLocator + "\" referenced by \"" + elementName + "\" on view/page \"" + viewName + "\" is still found where it is not expected after " + getSeleniumManager ( ) . getTimeout ( ) + " seconds." ) ; break ; } } }
The referenced view should not show the element identified by elementName
2,856
public static double convertDdmCoordinatesToDecimal ( String ddmCoordinate ) { checkArgument ( isNotBlank ( ddmCoordinate ) , "Coordinate to convert can't be null nor blank." ) ; int dotIndex = ddmCoordinate . indexOf ( '.' ) ; double degrees = parseDouble ( ddmCoordinate . substring ( 0 , dotIndex - 2 ) ) ; double minutes = parseDouble ( ddmCoordinate . substring ( dotIndex - 2 ) ) ; double decimalCoordinates = degrees + minutes / 60 ; LOG . debug ( "Converted NMEA DDM degree coordinate {} (degrees/minutes: {}/{}) to decimal coordinate {}." , ddmCoordinate , degrees , minutes , decimalCoordinates ) ; return decimalCoordinates ; }
Converts Degrees Decimal Minutes GPS coordinate string into the decimal value .
2,857
public static Map < String , Object > getYamlObjectValue ( Map < String , Object > yamlObject , String key , boolean allowsEmpty ) throws YamlConvertException { Object obj = getObjectValue ( yamlObject , key , allowsEmpty ) ; @ SuppressWarnings ( "unchecked" ) Map < String , Object > result = ( Map < String , Object > ) obj ; return result ; }
returns null for empty
2,858
public static Map < String , Object > getYamlObjectValue ( Map < String , Object > yamlObject , String key ) throws YamlConvertException { return getYamlObjectValue ( yamlObject , key , false ) ; }
for null or not found returns null
2,859
public static List < String > getStrListValue ( Map < String , Object > yamlObject , String key , boolean allowsEmpty ) throws YamlConvertException { Object obj = getObjectValue ( yamlObject , key , allowsEmpty ) ; @ SuppressWarnings ( "unchecked" ) List < String > result = ( List < String > ) obj ; if ( result == null ) { if ( ! allowsEmpty ) { throw new YamlConvertException ( MSG_LIST_MUST_NOT_BE_NULL ) ; } result = new ArrayList < > ( 0 ) ; } return result ; }
for null or not found key returns empty list
2,860
public static Map < String , Object > load ( InputStream input ) { Yaml yaml = new Yaml ( ) ; Object rawYamlObj = yaml . load ( input ) ; @ SuppressWarnings ( "unchecked" ) Map < String , Object > yamlObj = ( Map < String , Object > ) rawYamlObj ; return yamlObj ; }
this method does not close the stream
2,861
public static Query create ( String query ) throws QueryParserException { QueryTokenizer tokenizer = new QueryTokenizerImpl ( ) ; QueryParser parser = new QueryParserImpl ( ) ; return parser . parse ( tokenizer . tokenize ( query ) ) ; }
A factory method to create a query from string .
2,862
public String getVolumeLabel ( ) { final StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < MAX_VOLUME_LABEL_LENGTH ; i ++ ) { final char c = ( char ) get8 ( VOLUME_LABEL_OFFSET + i ) ; if ( c != 0 ) { sb . append ( c ) ; } else { break ; } } return sb . toString ( ) ; }
Returns the volume label that is stored in this boot sector .
2,863
public void setVolumeLabel ( String label ) throws IllegalArgumentException { if ( label . length ( ) > MAX_VOLUME_LABEL_LENGTH ) throw new IllegalArgumentException ( "volume label too long" ) ; for ( int i = 0 ; i < MAX_VOLUME_LABEL_LENGTH ; i ++ ) { set8 ( VOLUME_LABEL_OFFSET + i , i < label . length ( ) ? label . charAt ( i ) : 0 ) ; } }
Sets the volume label that is stored in this boot sector .
2,864
public void setRootDirEntryCount ( int v ) throws IllegalArgumentException { if ( v < 0 ) throw new IllegalArgumentException ( ) ; if ( v == getRootDirEntryCount ( ) ) return ; set16 ( ROOT_DIR_ENTRIES_OFFSET , v ) ; }
Sets the number of entries in the root directory
2,865
public void setEntries ( List < FatDirectoryEntry > newEntries ) { if ( newEntries . size ( ) > capacity ) throw new IllegalArgumentException ( "too many entries" ) ; this . entries . clear ( ) ; this . entries . addAll ( newEntries ) ; }
Replaces all entries in this directory .
2,866
public void flush ( ) throws IOException { final ByteBuffer data = ByteBuffer . allocate ( getCapacity ( ) * FatDirectoryEntry . SIZE + ( volumeLabel != null ? FatDirectoryEntry . SIZE : 0 ) ) ; for ( FatDirectoryEntry entry : this . entries ) { if ( entry != null ) { entry . write ( data ) ; } } if ( this . volumeLabel != null ) { final FatDirectoryEntry labelEntry = FatDirectoryEntry . createVolumeLabel ( type , volumeLabel ) ; labelEntry . write ( data ) ; } if ( data . hasRemaining ( ) ) { FatDirectoryEntry . writeNullEntry ( data ) ; } data . flip ( ) ; write ( data ) ; resetDirty ( ) ; }
Flush the contents of this directory to the persistent storage
2,867
public void setLabel ( String label ) throws IllegalArgumentException , UnsupportedOperationException , IOException { checkRoot ( ) ; if ( label != null && label . length ( ) > MAX_LABEL_LENGTH ) throw new IllegalArgumentException ( "label too long" ) ; if ( this . volumeLabel != null ) { if ( label == null ) { changeSize ( getSize ( ) - 1 ) ; this . volumeLabel = null ; } else { ShortName . checkValidChars ( label . getBytes ( ShortName . ASCII ) ) ; this . volumeLabel = label ; } } else { if ( label != null ) { changeSize ( getSize ( ) + 1 ) ; ShortName . checkValidChars ( label . getBytes ( ShortName . ASCII ) ) ; this . volumeLabel = label ; } } this . dirty = true ; }
Sets the volume label that is stored in this directory . Setting the volume label is supported on the root directory only .
2,868
public String getFileSystemTypeLabel ( ) { final StringBuilder sb = new StringBuilder ( FILE_SYSTEM_TYPE_LENGTH ) ; for ( int i = 0 ; i < FILE_SYSTEM_TYPE_LENGTH ; i ++ ) { sb . append ( ( char ) get8 ( getFileSystemTypeLabelOffset ( ) + i ) ) ; } return sb . toString ( ) ; }
Returns the file system type label string .
2,869
public String getOemName ( ) { StringBuilder b = new StringBuilder ( 8 ) ; for ( int i = 0 ; i < 8 ; i ++ ) { int v = get8 ( 0x3 + i ) ; if ( v == 0 ) break ; b . append ( ( char ) v ) ; } return b . toString ( ) ; }
Gets the OEM name
2,870
public void setOemName ( String name ) { if ( name . length ( ) > 8 ) throw new IllegalArgumentException ( "only 8 characters are allowed" ) ; for ( int i = 0 ; i < 8 ; i ++ ) { char ch ; if ( i < name . length ( ) ) { ch = name . charAt ( i ) ; } else { ch = ( char ) 0 ; } set8 ( 0x3 + i , ch ) ; } }
Sets the OEM name must be at most 8 characters long .
2,871
public static int compare ( String left , String right ) { if ( left == null ) { if ( right == null ) { return 0 ; } else { return 1 ; } } else if ( right == null ) { return - 1 ; } return left . compareTo ( right ) ; }
0 if equals
2,872
public static String encodeToSafeAsciiFileNameString ( String str , Charset strCharset ) { if ( str == null ) { return str ; } if ( ! SAFE_ASCII_PATTERN . matcher ( str ) . matches ( ) ) { return calcSHA1Digest ( str , strCharset ) ; } if ( SHA1_DIGEST_PATTERN . matcher ( str ) . matches ( ) ) { return calcSHA1Digest ( str , strCharset ) ; } return str ; }
- character which will be encoded by URL encoding
2,873
public static Manifest readManifestFromExternalJar ( File jarFile ) { if ( ! jarFile . getName ( ) . endsWith ( ".jar" ) ) { throw new IllegalArgumentException ( "not jar file : " + jarFile ) ; } InputStream in = null ; String urlStr = "jar:file:" + jarFile . getAbsolutePath ( ) + "!/META-INF/MANIFEST.MF" ; try { URL inputURL = new URL ( urlStr ) ; JarURLConnection conn = ( JarURLConnection ) inputURL . openConnection ( ) ; in = conn . getInputStream ( ) ; return new Manifest ( in ) ; } catch ( FileNotFoundException e ) { return null ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } finally { IOUtils . closeQuietly ( in ) ; } }
returns null if no manifest found
2,874
public void afterScenario ( Scenario scenario ) throws InterruptedException { log . debug ( "Scenarion finished" ) ; ScenarioGlobals scenarioGlobals = getCucumberManager ( ) . getCurrentScenarioGlobals ( ) ; TestEnvironment testNev = getSeleniumManager ( ) . getAssociatedTestEnvironment ( ) ; if ( testNev != null && scenarioGlobals != null ) { boolean scenarioUsedSelenium = testNev . isWebDriverAccessedSince ( scenarioGlobals . getScenarioStart ( ) ) ; if ( scenarioUsedSelenium ) { if ( scenario . isFailed ( ) ) { log . debug ( "Scenarion failed while using selenium, so capture screenshot" ) ; TakesScreenshot seleniumDriver = ( TakesScreenshot ) SenBotContext . getSeleniumDriver ( ) ; byte [ ] screenshotAs = seleniumDriver . getScreenshotAs ( OutputType . BYTES ) ; scenario . embed ( screenshotAs , "image/png" ) ; } } } getCucumberManager ( ) . stopNewScenario ( ) ; }
Capture a selenium screenshot when a test fails and add it to the Cucumber generated report if the scenario has accessed selenium in its lifetime
2,875
private Dimension getDefaultResolution ( ) { if ( getResolution ( ) != null ) { WebcamResolution res = WebcamResolution . valueOf ( getResolution ( ) ) ; return res . getSize ( ) ; } else { return new Dimension ( getWidth ( ) , getHeight ( ) ) ; } }
Returns the default resolution by name if provided eg HD720 otherwise the width and height .
2,876
static Exchange createOutOnlyExchangeWithBodyAndHeaders ( WebcamEndpoint endpoint , BufferedImage image ) throws IOException { Exchange exchange = endpoint . createExchange ( ExchangePattern . OutOnly ) ; Message message = exchange . getIn ( ) ; try ( ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ) { ImageIO . write ( image , endpoint . getFormat ( ) , output ) ; message . setBody ( new BufferedInputStream ( new ByteArrayInputStream ( output . toByteArray ( ) ) ) ) ; message . setHeader ( Exchange . FILE_NAME , message . getMessageId ( ) + "" + endpoint . getFormat ( ) ) ; } return exchange ; }
Creates an OutOnly exchange with the BufferedImage .
2,877
public static void consumeBufferedImage ( BufferedImage image , Processor processor , WebcamEndpoint endpoint , ExceptionHandler exceptionHandler ) { Validate . notNull ( image ) ; Validate . notNull ( processor ) ; Validate . notNull ( endpoint ) ; try { Exchange exchange = createOutOnlyExchangeWithBodyAndHeaders ( endpoint , image ) ; processor . process ( exchange ) ; } catch ( Exception e ) { exceptionHandler . handleException ( e ) ; } }
Consume the java . awt . BufferedImage from the webcam all params required .
2,878
public static void consumeWebcamMotionEvent ( WebcamMotionEvent motionEvent , Processor processor , WebcamEndpoint endpoint , ExceptionHandler exceptionHandler ) { Validate . notNull ( motionEvent ) ; Validate . notNull ( processor ) ; Validate . notNull ( endpoint ) ; try { Exchange exchange = createOutOnlyExchangeWithBodyAndHeaders ( endpoint , motionEvent . getCurrentImage ( ) ) ; exchange . getIn ( ) . setHeader ( WebcamConstants . WEBCAM_MOTION_EVENT_HEADER , motionEvent ) ; processor . process ( exchange ) ; } catch ( Exception e ) { exceptionHandler . handleException ( e ) ; } }
Consume the motion event from the webcam all params required . The event is stored in the header while the latest image is available as the body .
2,879
public static boolean isWebcamPresent ( ) { try { Webcam . getDefault ( WebcamConstants . DEFAULT_WEBCAM_LOOKUP_TIMEOUT ) ; return true ; } catch ( Throwable exception ) { LOG . debug ( "Problem occurred when detecting the webcam. Returning false." , exception ) ; return false ; } }
Returns true if there s a webcam available false otherwise .
2,880
public ShortName generateShortName ( String longFullName ) throws IllegalStateException { longFullName = stripLeadingPeriods ( longFullName ) . toUpperCase ( Locale . ROOT ) ; final String longName ; final String longExt ; final int dotIdx = longFullName . lastIndexOf ( '.' ) ; final boolean forceSuffix ; if ( dotIdx == - 1 ) { forceSuffix = ! cleanString ( longFullName ) ; longName = tidyString ( longFullName ) ; longExt = "" ; } else { forceSuffix = ! cleanString ( longFullName . substring ( 0 , dotIdx ) ) ; longName = tidyString ( longFullName . substring ( 0 , dotIdx ) ) ; longExt = tidyString ( longFullName . substring ( dotIdx + 1 ) ) ; } final String shortExt = ( longExt . length ( ) > 3 ) ? longExt . substring ( 0 , 3 ) : longExt ; if ( forceSuffix || ( longName . length ( ) > 8 ) || usedNames . contains ( new ShortName ( longName , shortExt ) . asSimpleString ( ) . toLowerCase ( Locale . ROOT ) ) ) { final int maxLongIdx = Math . min ( longName . length ( ) , 8 ) ; for ( int i = 1 ; i < 99999 ; i ++ ) { final String serial = "~" + i ; final int serialLen = serial . length ( ) ; final String shortName = longName . substring ( 0 , Math . min ( maxLongIdx , 8 - serialLen ) ) + serial ; final ShortName result = new ShortName ( shortName , shortExt ) ; if ( ! usedNames . contains ( result . asSimpleString ( ) . toLowerCase ( Locale . ROOT ) ) ) { return result ; } } throw new IllegalStateException ( "could not generate short name for \"" + longFullName + "\"" ) ; } return new ShortName ( longName , shortExt ) ; }
Generates a new unique 8 . 3 file name that is not already contained in the set specified to the constructor .
2,881
public ScenarioGlobals stopNewScenario ( ) { if ( scenarioCreationHook != null ) { scenarioCreationHook . scenarionShutdown ( getCurrentScenarioGlobals ( ) ) ; } return scenarioGlobalsMap . remove ( Thread . currentThread ( ) ) ; }
Called at the end of an scenario?
2,882
public Iterator < QueryBinding > iterator ( ) { List < QueryBinding > iBindings = new ArrayList < QueryBinding > ( ) ; for ( QueryBindingImpl b : bindings ) { iBindings . add ( b ) ; } return iBindings . iterator ( ) ; }
An iterator over the result set .
2,883
public static QueryEngine create ( OWLOntologyManager manager , OWLReasoner reasoner , boolean strict ) { return new QueryEngineImpl ( manager , reasoner , strict ) ; }
Factory method to create a QueryEngine instance .
2,884
public static void initialize ( String configFilePath ) { if ( manager != null ) { return ; } logger . info ( "initialize" ) ; final Config config ; try { config = JavaConfig . generateFromYamlConfig ( new File ( configFilePath ) ) ; } catch ( YamlConvertException e ) { throw new RuntimeException ( e ) ; } final File srcTreeFile = CommonPath . srcTreeFile ( config . getRootBaseRunOutputIntermediateDataDir ( ) ) ; SrcTree srcTree = new SrcTree ( ) ; try { srcTree . fromYamlObject ( YamlUtils . load ( srcTreeFile ) ) ; } catch ( YamlConvertException e ) { throw new RuntimeException ( e ) ; } try { srcTree . resolveKeyReference ( ) ; } catch ( IllegalDataStructureException e ) { throw new RuntimeException ( e ) ; } manager = new HookMethodManager ( srcTree , config ) ; if ( ! config . isRunTestOnly ( ) ) { Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { public void run ( ) { HtmlReport report = new HtmlReport ( ) ; try { report . generate ( config . getRootBaseReportInputIntermediateDataDirs ( ) , config . getRootBaseReportOutputDir ( ) ) ; } catch ( IllegalDataStructureException | IllegalTestScriptException e ) { throw new RuntimeException ( e ) ; } } } ) ; } }
if called multiple times just ignored
2,885
public static String readDeviceMetric ( String deviceId , String metric ) { return format ( "%s.%s.%s" , CHANNEL_DEVICE_METRICS_READ , deviceId , metric ) ; }
Device metrics channel helpers
2,886
public void clickElementWithAttributeValue ( String attributeName , String attributeValue ) { By xpath = By . xpath ( "//*[@" + attributeName + "='" + attributeValue + "']" ) ; WebElement element = seleniumElementService . findExpectedElement ( xpath ) ; assertTrue ( "The element you are trying to click (" + xpath . toString ( ) + ") is not displayed" , element . isDisplayed ( ) ) ; element . click ( ) ; }
Find a Element that has a attribute with a certain value and click it
2,887
public boolean isInitialPageRequested ( ) { String currentUrl = getWebDriver ( ) . getCurrentUrl ( ) ; if ( StringUtils . isBlank ( currentUrl ) || ( ! currentUrl . toLowerCase ( ) . startsWith ( "http" ) && ! currentUrl . toLowerCase ( ) . startsWith ( "file" ) ) ) { return false ; } else { return true ; } }
Has a page been requested for this selenium session . This method is available to prevent scripts for waiting for a cetrain condition if no url has been requested yet . If true you know you can just proceed and not check for any state as none exists
2,888
public void mouseHoverOverElement ( By locator ) { SynchronisationService synchronisationService = new SynchronisationService ( ) ; synchronisationService . waitAndAssertForExpectedCondition ( ExpectedConditions . visibilityOfElementLocated ( locator ) ) ; WebElement element = getWebDriver ( ) . findElement ( locator ) ; Actions builder = new Actions ( getWebDriver ( ) ) ; Actions hoverOverRegistrar = builder . moveToElement ( element ) ; hoverOverRegistrar . perform ( ) ; }
Hovers the mouse over the given element
2,889
public void resolveKeyReference ( ) throws IllegalDataStructureException { for ( TestClass testClass : rootClassTable . getTestClasses ( ) ) { resolveTestMethod ( testClass ) ; resolveTestField ( testClass ) ; resolveDelegateToTestClass ( testClass ) ; } for ( TestClass testClass : subClassTable . getTestClasses ( ) ) { resolveTestMethod ( testClass ) ; resolveTestField ( testClass ) ; resolveDelegateToTestClass ( testClass ) ; } for ( TestMethod testMethod : rootMethodTable . getTestMethods ( ) ) { resolveTestClass ( testMethod ) ; for ( CodeLine codeLine : testMethod . getCodeBody ( ) ) { resolveKeyReferenceInCode ( codeLine . getCode ( ) ) ; } } for ( TestMethod testMethod : subMethodTable . getTestMethods ( ) ) { resolveTestClass ( testMethod ) ; for ( CodeLine codeLine : testMethod . getCodeBody ( ) ) { resolveKeyReferenceInCode ( codeLine . getCode ( ) ) ; } } for ( TestField testField : fieldTable . getTestFields ( ) ) { resolveTestClass ( testField ) ; } }
assume all keys have been set
2,890
private void addLineScreenCaptureForErrorEachStackLine ( List < LineScreenCapture > lineScreenCaptures , RunFailure runFailure ) { if ( runFailure == null ) { return ; } List < StackLine > failureLines = runFailure . getStackLines ( ) ; int failureCaptureIndex = matchedLineScreenCaptureIndex ( lineScreenCaptures , failureLines ) ; if ( failureCaptureIndex == - 1 ) { return ; } LineScreenCapture failureCapture = lineScreenCaptures . get ( failureCaptureIndex ) ; for ( int i = 1 ; i < failureLines . size ( ) ; i ++ ) { List < StackLine > errorEachStackLine = new ArrayList < > ( failureLines . size ( ) - i ) ; for ( int j = i ; j < failureLines . size ( ) ; j ++ ) { errorEachStackLine . add ( failureLines . get ( j ) ) ; } LineScreenCapture newCapture = new LineScreenCapture ( ) ; newCapture . setPath ( failureCapture . getPath ( ) ) ; newCapture . addAllStackLines ( errorEachStackLine ) ; int errEachStackLineCaptureIndex = matchedLineScreenCaptureIndex ( lineScreenCaptures , errorEachStackLine ) ; if ( errEachStackLineCaptureIndex == - 1 ) { lineScreenCaptures . add ( newCapture ) ; } else { lineScreenCaptures . set ( errEachStackLineCaptureIndex , newCapture ) ; } } }
The same capture is used for the all StackLines .
2,891
private List < ReportScreenCapture > generateReportScreenCaptures ( List < LineScreenCapture > lineScreenCaptures , File inputCaptureRootDir , File reportOutputDir , File methodReportParentDir ) { List < ReportScreenCapture > reportCaptures = new ArrayList < > ( lineScreenCaptures . size ( ) ) ; String noImageFilePath = new File ( CommonUtils . relativize ( CommonPath . htmlExternalResourceRootDir ( reportOutputDir ) , methodReportParentDir ) , "images/noImage.png" ) . getPath ( ) ; ReportScreenCapture noImageCapture = new ReportScreenCapture ( ) ; noImageCapture . setPath ( FilenameUtils . separatorsToUnix ( noImageFilePath ) ) ; noImageCapture . setImageId ( "noImage" ) ; noImageCapture . setImageWidth ( NO_IMAGE_WIDTH ) ; noImageCapture . setImageHeight ( NO_IMAGE_HEIGHT ) ; reportCaptures . add ( noImageCapture ) ; for ( LineScreenCapture lineScreenCapture : lineScreenCaptures ) { ReportScreenCapture reportCapture = new ReportScreenCapture ( ) ; File actualPath = new File ( lineScreenCapture . getPath ( ) . getPath ( ) . replace ( "${inputCaptureRootDirForSahaginInternalTest}" , inputCaptureRootDir . getPath ( ) ) ) ; File relInputCapturePath = CommonUtils . relativize ( actualPath , inputCaptureRootDir ) ; File absOutputCapturePath = new File ( CommonPath . htmlReportCaptureRootDir ( reportOutputDir ) , relInputCapturePath . getPath ( ) ) ; File relOutputCapturePath = CommonUtils . relativize ( absOutputCapturePath , methodReportParentDir ) ; reportCapture . setPath ( FilenameUtils . separatorsToUnix ( relOutputCapturePath . getPath ( ) ) ) ; String ttId = generateTtId ( lineScreenCapture . getStackLines ( ) ) ; reportCapture . setImageId ( ttId ) ; reportCapture . setImageSizeFromImageFile ( lineScreenCapture . getPath ( ) ) ; reportCapture . setExecutionTime ( lineScreenCapture . getExecutionTime ( ) ) ; reportCaptures . add ( reportCapture ) ; } return reportCaptures ; }
generate ResportScreenCapture list from lineScreenCaptures and
2,892
private RunFailure getRunFailure ( RootMethodRunResult runResult ) { if ( runResult == null || runResult . getRunFailures ( ) . size ( ) == 0 ) { return null ; } return runResult . getRunFailures ( ) . get ( 0 ) ; }
returns null if no failure
2,893
private List < RunResults > generateRunResultList ( List < File > reportInputDataDirs , SrcTree srcTree ) throws IllegalDataStructureException { List < RunResults > resultsList = new ArrayList < > ( reportInputDataDirs . size ( ) ) ; for ( File reportInputDataDir : reportInputDataDirs ) { RunResults results = new RunResults ( ) ; Collection < File > runResultFiles ; File runResultsRootDir = CommonPath . runResultRootDir ( reportInputDataDir ) ; if ( runResultsRootDir . exists ( ) ) { runResultFiles = FileUtils . listFiles ( runResultsRootDir , null , true ) ; } else { runResultFiles = new ArrayList < > ( 0 ) ; } for ( File runResultFile : runResultFiles ) { Map < String , Object > runResultYamlObj = YamlUtils . load ( runResultFile ) ; RootMethodRunResult rootMethodRunResult = new RootMethodRunResult ( ) ; try { rootMethodRunResult . fromYamlObject ( runResultYamlObj ) ; } catch ( YamlConvertException e ) { throw new IllegalDataStructureException ( e ) ; } results . addRootMethodRunResults ( rootMethodRunResult ) ; } results . resolveKeyReference ( srcTree ) ; resultsList . add ( results ) ; } return resultsList ; }
returns RunResults list for reportInputDataDirs
2,894
public Vertx getVertx ( ) { if ( vertx != null ) { return vertx ; } if ( getComponent ( ) . getVertx ( ) != null ) { vertx = getComponent ( ) . getVertx ( ) ; } else { vertx = Vertx . vertx ( ) ; } return vertx ; }
Getters & setters
2,895
private void configureMessagesExceptionArgumentResolvers ( ) { this . handlerExceptionResolver = this . applicationContext . getBean ( "handlerExceptionResolver" , HandlerExceptionResolver . class ) ; for ( final HandlerExceptionResolver resolver : ( ( HandlerExceptionResolverComposite ) this . handlerExceptionResolver ) . getExceptionResolvers ( ) ) { if ( resolver instanceof ExceptionHandlerExceptionResolver ) { configureCustomHandlerMethodArgumentResolver ( ( ExceptionHandlerExceptionResolver ) resolver ) ; } } }
adds a FlashMessagesMethodArgumentResolver to handlerExceptionResolver s argument resolvers
2,896
public void setVolumeLabel ( String label ) { for ( int i = 0 ; i < 11 ; i ++ ) { final byte c = ( label == null ) ? 0 : ( label . length ( ) > i ) ? ( byte ) label . charAt ( i ) : 0x20 ; set8 ( 0x47 + i , c ) ; } }
Sets the 11 - byte volume label stored at offset 0x47 .
2,897
public void writeCopy ( BlockDevice device ) throws IOException { if ( getBootSectorCopySector ( ) > 0 ) { final long offset = ( long ) getBootSectorCopySector ( ) * SIZE ; buffer . rewind ( ) ; buffer . limit ( buffer . capacity ( ) ) ; device . write ( offset , buffer ) ; } }
Writes a copy of this boot sector to the specified device if a copy is requested .
2,898
public QueryBindingImpl cloneAndFilter ( Set < QueryArgument > args ) { QueryBindingImpl binding = new QueryBindingImpl ( ) ; for ( QueryArgument arg : getBoundArgs ( ) ) { if ( args . contains ( arg ) ) { binding . set ( arg , bindingMap . get ( arg ) ) ; } } return binding ; }
Clone this instance of QueryBinding and filter the binding map given by args . Only query arguments within the set of args will be available in the result . Only the QueryBinding class itself will be cloned but not the query arguments .
2,899
private boolean isLineLastStament ( TestMethod method , int codeLineIndex ) { CodeLine codeLine = method . getCodeBody ( ) . get ( codeLineIndex ) ; if ( codeLineIndex == method . getCodeBody ( ) . size ( ) - 1 ) { return true ; } CodeLine nextCodeLine = method . getCodeBody ( ) . get ( codeLineIndex + 1 ) ; assert codeLine . getEndLine ( ) <= nextCodeLine . getStartLine ( ) ; if ( codeLine . getEndLine ( ) == nextCodeLine . getStartLine ( ) ) { return false ; } return true ; }
This may return false since multiple statement can be found in a line .