idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
37,100
public void setDate ( String date ) { if ( date == null || date . trim ( ) . isEmpty ( ) ) { throw new IllegalArgumentException ( "Date cannot be null or empty." ) ; } try { Date dateToSet = new SimpleDateFormat ( "MM/dd/yyyy" ) . parse ( date ) ; Calendar to = Calendar . getInstance ( ) ; to . setTime ( dateToSet ) ; setDate ( to ) ; } catch ( ParseException e ) { throw new IllegalArgumentException ( e ) ; } }
This function set the date on the DatePicker using the input paramter in the format of MM . dd . yyyy string
37,101
public void datePickerInit ( String prevMonthLocator , String nextMonthLocator , String dateTextLocator ) { this . prevMonthLocator = prevMonthLocator ; this . nextMonthLocator = nextMonthLocator ; this . dateTextLocator = dateTextLocator ; }
DatePicker comes with default locators for widget controls previous button next button and date text . This method gives access to override these default locators .
37,102
public void reset ( ) { this . getElement ( ) . clear ( ) ; Grid . driver ( ) . findElement ( By . tagName ( "body" ) ) . click ( ) ; this . calendar = Calendar . getInstance ( ) ; this . getElement ( ) . click ( ) ; }
Clears the date picker . Some browsers require clicking on an element outside of the date picker field to properly reset the calendar to today s date .
37,103
public int size ( ) { int size = 0 ; try { if ( getParent ( ) != null ) { size = getParent ( ) . locateChildElements ( getLocator ( ) ) . size ( ) ; } else { size = HtmlElementUtils . locateElements ( getLocator ( ) ) . size ( ) ; } } catch ( NoSuchElementException e ) { } return size ; }
Returns the number of containers found on the page .
37,104
public WebElement locateElement ( int index , String childLocator ) { if ( index < 0 ) { throw new IllegalArgumentException ( "index cannot be a negative value" ) ; } setIndex ( index ) ; WebElement locatedElement = null ; if ( getParent ( ) != null ) { locatedElement = getParent ( ) . locateChildElement ( childLocator ) ; } else { locatedElement = HtmlElementUtils . locateElement ( childLocator , this ) ; } return locatedElement ; }
Sets the container index and searches for the descendant element using the child locator .
37,105
public static Object instantiatePrimitiveArray ( Class < ? > type , String [ ] values ) { logger . entering ( new Object [ ] { type , values } ) ; validateParams ( type , values ) ; checkArgument ( isPrimitiveArray ( type ) , type + " is NOT a primitive array type." ) ; Class < ? > componentType = type . getComponentType ( ) ; Object arrayToReturn = Array . newInstance ( componentType , values . length ) ; Method parserMethod = getParserMethod ( componentType ) ; for ( int i = 0 ; i < values . length ; i ++ ) { try { Array . set ( arrayToReturn , i , parserMethod . invoke ( arrayToReturn , values [ i ] ) ) ; } catch ( ArrayIndexOutOfBoundsException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e ) { throw new ReflectionException ( e ) ; } } logger . exiting ( arrayToReturn ) ; return arrayToReturn ; }
This helper method facilitates creation of primitive arrays and pre - populates them with the set of String values provided .
37,106
public static Object instantiatePrimitiveObject ( Class < ? > type , Object objectToInvokeUpon , String valueToAssign ) { logger . entering ( new Object [ ] { type , objectToInvokeUpon , valueToAssign } ) ; validateParams ( type , objectToInvokeUpon , valueToAssign ) ; checkArgument ( type . isPrimitive ( ) , type + " is NOT a primitive data type." ) ; try { Object objectToReturn = getParserMethod ( type ) . invoke ( objectToInvokeUpon , valueToAssign ) ; logger . exiting ( objectToInvokeUpon ) ; return objectToReturn ; } catch ( IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new ReflectionException ( e ) ; } }
This helper method facilitates creation of primitive data type object and initialize it with the provided value .
37,107
public static Object instantiateWrapperObject ( Class < ? > type , Object objectToInvokeUpon , String valueToAssign ) { logger . entering ( new Object [ ] { type , objectToInvokeUpon , valueToAssign } ) ; validateParams ( type , objectToInvokeUpon , valueToAssign ) ; checkArgument ( ClassUtils . isPrimitiveWrapper ( type ) , type . getName ( ) + " is NOT a wrapper data type." ) ; try { Object objectToReturn = type . getConstructor ( new Class < ? > [ ] { String . class } ) . newInstance ( valueToAssign ) ; logger . exiting ( objectToInvokeUpon ) ; return objectToReturn ; } catch ( InstantiationException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new ReflectionException ( e ) ; } }
This helper method facilitates creation of Wrapper data type object and initialize it with the provided value .
37,108
void startProcess ( boolean squelch ) throws IOException { LOGGER . entering ( squelch ) ; if ( ! squelch ) { LOGGER . fine ( "Executing command " + cmdLine . toString ( ) ) ; } watchdog . reset ( ) ; DefaultExecutor executor = new DefaultExecutor ( ) ; executor . setWatchdog ( watchdog ) ; executor . setStreamHandler ( new PumpStreamHandler ( ) ) ; executor . setProcessDestroyer ( new ShutdownHookProcessDestroyer ( ) ) ; handler = new DefaultExecuteResultHandler ( ) ; executor . execute ( cmdLine , handler ) ; LOGGER . exiting ( ) ; }
Start a process based on the commands provided .
37,109
String [ ] getJavaClassPathArguments ( String jarNamePrefix , String mainClass ) { LOGGER . entering ( ) ; Set < String > uniqueClassPathEntries = new LinkedHashSet < > ( ) ; if ( getLauncherOptions ( ) . isIncludeJarsInSeLionHomeDir ( ) ) { Collection < File > homeFiles = FileUtils . listFiles ( new File ( SeLionConstants . SELION_HOME_DIR ) , new String [ ] { "jar" } , false ) ; for ( File file : homeFiles ) { if ( file . getName ( ) . startsWith ( jarNamePrefix ) || StringUtils . isEmpty ( jarNamePrefix ) ) { uniqueClassPathEntries . add ( file . getAbsolutePath ( ) ) ; } } } if ( getLauncherOptions ( ) . isIncludeJarsInPresentWorkingDir ( ) ) { Collection < File > localFiles = FileUtils . listFiles ( SystemUtils . getUserDir ( ) , new String [ ] { "jar" } , false ) ; for ( File file : localFiles ) { uniqueClassPathEntries . add ( file . getName ( ) ) ; } } if ( getLauncherOptions ( ) . isIncludeParentProcessClassPath ( ) ) { String classpath = SystemUtils . JAVA_CLASS_PATH ; uniqueClassPathEntries . addAll ( Arrays . asList ( classpath . split ( SystemUtils . PATH_SEPARATOR ) ) ) ; } StringBuilder buf = new StringBuilder ( ) ; for ( String s : uniqueClassPathEntries ) { buf . append ( s + SystemUtils . PATH_SEPARATOR ) ; } buf . deleteCharAt ( buf . length ( ) - 1 ) ; String [ ] args = new String [ 3 ] ; args [ 0 ] = ( "-cp" ) ; args [ 1 ] = buf . toString ( ) ; args [ 2 ] = mainClass ; LOGGER . exiting ( args ) ; return args ; }
Get the classpath for the child process . Determines all jars from CWD and SELION_HOME_DIR . Does not recurse into sub directories . Filters out duplicates .
37,110
String [ ] getJavaSystemPropertiesArguments ( ) throws IOException { LOGGER . entering ( ) ; List < String > args = new LinkedList < > ( ) ; args . addAll ( Arrays . asList ( getPresentJavaSystemPropertiesArguments ( ) ) ) ; args . addAll ( Arrays . asList ( getLoggingSystemPropertiesArguments ( ) ) ) ; LOGGER . exiting ( args . toString ( ) ) ; return args . toArray ( new String [ args . size ( ) ] ) ; }
Get required system properties to launch the sub process
37,111
public Iterator < Object [ ] > getDataByFilter ( DataProviderFilter dataFilter ) { Preconditions . checkArgument ( resource != null , "File resource cannot be null" ) ; logger . entering ( dataFilter ) ; Class < ? > arrayType ; JsonReader reader = null ; try { reader = new JsonReader ( getReader ( resource ) ) ; arrayType = Array . newInstance ( resource . getCls ( ) , 0 ) . getClass ( ) ; Gson myJson = new Gson ( ) ; Object [ ] mappedData = myJson . fromJson ( reader , arrayType ) ; return prepareDataAsObjectArrayList ( mappedData , dataFilter ) . iterator ( ) ; } catch ( Exception e ) { throw new DataProviderException ( e . getMessage ( ) , e ) ; } finally { IOUtils . closeQuietly ( reader ) ; } }
Gets JSON data from a resource by applying the given filter .
37,112
public Hashtable < String , Object > getDataAsHashtable ( ) { Preconditions . checkArgument ( resource != null , "File resource cannot be null" ) ; logger . entering ( ) ; resource . setCls ( Hashtable [ ] . class ) ; Hashtable < String , Object > dataAsHashTable = null ; JsonReader reader = null ; try { reader = new JsonReader ( getReader ( resource ) ) ; Object [ ] [ ] dataObject = mapJsonData ( reader , resource . getCls ( ) ) ; dataAsHashTable = new Hashtable < > ( ) ; for ( Object [ ] currentData : dataObject ) { Hashtable < ? , ? > value = ( Hashtable < ? , ? > ) currentData [ 0 ] ; dataAsHashTable . put ( ( String ) value . get ( "id" ) , currentData ) ; } } catch ( NullPointerException n ) { throw new DataProviderException ( "Error while parsing Json Data as a Hash table. Root cause: Unable to find a key named id. Please refer Javadoc" , n ) ; } catch ( Exception e ) { throw new DataProviderException ( "Error while parsing Json Data as a Hash table" , e ) ; } finally { IOUtils . closeQuietly ( reader ) ; } logger . exiting ( dataAsHashTable ) ; return dataAsHashTable ; }
A utility method to give out JSON data as HashTable . Please note this method works on the rule that the json object that needs to be parsed MUST contain a key named id .
37,113
protected void startHtml ( PrintWriter out ) { logger . entering ( out ) ; try { Template t = ve . getTemplate ( "/templates/header.part.html" ) ; VelocityContext context = new VelocityContext ( ) ; StringBuilder output = new StringBuilder ( ) ; for ( Entry < String , String > temp : ConfigSummaryData . getConfigSummary ( ) . entrySet ( ) ) { Entry < String , String > formattedTemp = ReporterDateFormatter . formatReportDataForBrowsableReports ( temp ) ; output . append ( formattedTemp . getKey ( ) ) . append ( " : <b>" ) . append ( formattedTemp . getValue ( ) ) . append ( "</b><br>" ) ; } context . put ( "configSummary" , output . toString ( ) ) ; StringWriter writer = new StringWriter ( ) ; t . merge ( context , writer ) ; out . write ( writer . toString ( ) ) ; } catch ( Exception e ) { logger . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } logger . exiting ( ) ; }
Starts HTML stream
37,114
void printUsageInfo ( ) { StringBuilder usage = new StringBuilder ( ) ; usage . append ( " System Properties: \n" ) ; usage . append ( " -DselionHome=<folderPath>: \n" ) ; usage . append ( " Path of SeLion home directory. Defaults to <user.home>/.selion2/ \n" ) ; usage . append ( " -D[property]=[value]: \n" ) ; usage . append ( " Any other System Property you wish to pass to the JVM \n" ) ; System . out . print ( usage . toString ( ) ) ; }
Print the usage of SeLion Grid jar
37,115
public boolean isTextPresent ( String pattern ) { String text = getElement ( ) . getText ( ) ; return ( text != null && ( text . contains ( pattern ) || text . matches ( pattern ) ) ) ; }
It is to check whether the element s text matches with the specified pattern .
37,116
public static void log ( String message , boolean takeScreenshot , boolean saveSrc ) { SeLionReporter reporter = new SeLionReporter ( ) ; BaseLog currentLog = new BaseLog ( ) ; currentLog . setMsg ( message ) ; currentLog . setLocation ( Gatherer . saveGetLocation ( Grid . driver ( ) ) ) ; reporter . setCurrentLog ( currentLog ) ; reporter . generateLog ( takeScreenshot , saveSrc ) ; logger . exiting ( ) ; }
Generates log entry with message provided
37,117
public void shutdownProcesses ( ) throws ProcessHandlerException { LOGGER . info ( "Shutting down all our node processes." ) ; ProcessHandler handler = ProcessHandlerFactory . createInstance ( ) ; List < ProcessInfo > processes = handler . potentialProcessToBeKilled ( ) ; handler . killProcess ( processes ) ; LOGGER . info ( "Successfully shutdown all processes" ) ; }
This method terminates all Node processes that we started .
37,118
public void scrollLeft ( ) { logger . entering ( ) ; WebElement webElement = this . findElement ( By . className ( SCROLLVIEW_CLASS ) ) ; swipeLeft ( webElement ) ; logger . exiting ( ) ; }
Scroll the screen to the left . The underlying application should have atleast one scroll view belonging to the class android . widget . ScrollView .
37,119
public void scrollRight ( ) { logger . entering ( ) ; WebElement webElement = this . findElement ( By . className ( SCROLLVIEW_CLASS ) ) ; swipeRight ( webElement ) ; logger . exiting ( ) ; }
Scroll the screen to the right . The underlying application should have atleast one scroll view belonging to the class android . widget . ScrollView .
37,120
public void scrollUp ( ) { logger . entering ( ) ; WebElement webElement = this . findElement ( By . className ( SCROLLVIEW_CLASS ) ) ; swipeUp ( webElement ) ; logger . exiting ( ) ; }
Scroll the screen up . The underlying application should have atleast one scroll view belonging to the class android . widget . ScrollView .
37,121
public void scrollDown ( ) { logger . entering ( ) ; WebElement webElement = this . findElement ( By . className ( SCROLLVIEW_CLASS ) ) ; swipeDown ( webElement ) ; logger . exiting ( ) ; }
Scroll the screen down . The underlying application should have atleast one scroll view belonging to the class android . widget . ScrollView .
37,122
public void setMaxBrowserInstances ( String browserName , int maxBrowserInstances ) { logger . entering ( new Object [ ] { browserName , maxBrowserInstances } ) ; validateBrowserName ( browserName ) ; BrowserStatistics lStatistics = createStatisticsIfNotPresent ( browserName ) ; lStatistics . setMaxBrowserInstances ( maxBrowserInstances ) ; logger . exiting ( ) ; }
Sets the maximum instances for a particular browser . This call creates a unique statistics for the provided browser name it does not exists .
37,123
public void incrementWaitingRequests ( String browserName ) { logger . entering ( browserName ) ; validateBrowserName ( browserName ) ; BrowserStatistics lStatistics = createStatisticsIfNotPresent ( browserName ) ; lStatistics . incrementWaitingRequests ( ) ; logger . exiting ( ) ; }
Increments the waiting request for the provided browser name . This call creates a unique statistics for the provided browser name it does not exists .
37,124
public static synchronized void printConfiguration ( String testName ) { LocalConfig currentConfig = getConfig ( testName ) ; currentConfig . printConfigValues ( testName ) ; }
A utility method that can dump the configuration for a given &lt ; test&gt ; identified with its name .
37,125
public RemoteWebElement getElement ( ) { RemoteWebElement foundElement = null ; try { if ( parent == null ) { foundElement = HtmlElementUtils . locateElement ( getLocator ( ) ) ; } else { foundElement = parent . locateChildElement ( locator ) ; } } catch ( ParentNotFoundException p ) { throw p ; } catch ( NoSuchElementException n ) { addInfoForNoSuchElementException ( n ) ; } return foundElement ; }
Instance method used to call static class method locateElement .
37,126
public List < WebElement > getElements ( ) { List < WebElement > foundElements = null ; try { if ( parent == null ) { foundElements = HtmlElementUtils . locateElements ( getLocator ( ) ) ; } else { foundElements = parent . locateChildElements ( getLocator ( ) ) ; } } catch ( NoSuchElementException n ) { addInfoForNoSuchElementException ( n ) ; } return foundElements ; }
Instance method used to call static class method locateElements .
37,127
private void addInfoForNoSuchElementException ( NoSuchElementException cause ) { if ( parent == null ) { throw cause ; } BasicPageImpl page = this . parent . getCurrentPage ( ) ; if ( page == null ) { throw cause ; } String resolvedPageName = page . getClass ( ) . getSimpleName ( ) ; boolean pageExists = page . hasExpectedPageTitle ( ) ; if ( ! pageExists ) { throw new ParentNotFoundException ( resolvedPageName + " : With Page Title {" + page . getActualPageTitle ( ) + "} Not Found." , cause ) ; } StringBuilder msg = new StringBuilder ( "Unable to find webElement " ) ; if ( this . controlName != null ) { msg . append ( this . controlName ) . append ( " on " ) ; } if ( resolvedPageName != null ) { msg . append ( resolvedPageName ) ; } msg . append ( " using the locator {" ) . append ( locator ) . append ( "}" ) ; throw new NoSuchElementException ( msg . toString ( ) , cause ) ; }
A utility method to provide additional information to the user when a NoSuchElementException is thrown .
37,128
public Object clickAndExpect ( ExpectedCondition < ? > expectedCondition ) { dispatcher . beforeClick ( this , expectedCondition ) ; getElement ( ) . click ( ) ; if ( Boolean . parseBoolean ( Config . getConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) ) { logUIAction ( UIActions . CLICKED ) ; } if ( parent != null ) { WebDriverWaitUtils . waitUntilPageIsLoaded ( parent . getCurrentPage ( ) ) ; } validatePresenceOfAlert ( ) ; long timeout = Grid . getExecutionTimeoutValue ( ) / 1000 ; WebDriverWait wait = new WebDriverWait ( Grid . driver ( ) , timeout ) ; Object variable = wait . until ( expectedCondition ) ; processScreenShot ( ) ; dispatcher . afterClick ( this , expectedCondition ) ; return variable ; }
The click function and wait based on the ExpectedCondition .
37,129
public void hover ( final Object ... expected ) { dispatcher . beforeHover ( this , expected ) ; new Actions ( Grid . driver ( ) ) . moveToElement ( getElement ( ) ) . perform ( ) ; try { for ( Object expect : expected ) { if ( expect instanceof AbstractElement ) { AbstractElement a = ( AbstractElement ) expect ; WebDriverWaitUtils . waitUntilElementIsVisible ( a . getLocator ( ) ) ; } else if ( expect instanceof String ) { String s = ( String ) expect ; WebDriverWaitUtils . waitUntilElementIsVisible ( s ) ; } } } finally { processScreenShot ( ) ; dispatcher . afterHover ( this , expected ) ; } }
Moves the mouse pointer to the middle of the element . And waits for the expected elements to be visible .
37,130
public Object [ ] [ ] getAllData ( ) { logger . entering ( ) ; Object [ ] [ ] objectArray ; if ( ( null == resource . getCls ( ) ) && ( null != resource . getXpathMap ( ) ) ) { Document doc = getDocument ( ) ; Object [ ] [ ] [ ] multipleObjectDataProviders = new Object [ resource . getXpathMap ( ) . size ( ) ] [ ] [ ] ; int i = 0 ; for ( Entry < String , Class < ? > > entry : resource . getXpathMap ( ) . entrySet ( ) ) { String xml = getFilteredXml ( doc , entry . getKey ( ) ) ; List < ? > object = loadDataFromXml ( xml , entry . getValue ( ) ) ; Object [ ] [ ] objectDataProvider = DataProviderHelper . convertToObjectArray ( object ) ; multipleObjectDataProviders [ i ++ ] = objectDataProvider ; } objectArray = DataProviderHelper . getAllDataMultipleArgs ( multipleObjectDataProviders ) ; } else { List < ? > objectList = loadDataFromXmlFile ( ) ; objectArray = DataProviderHelper . convertToObjectArray ( objectList ) ; } logger . exiting ( ) ; return objectArray ; }
Generates a two dimensional array for TestNG DataProvider from the XML data .
37,131
public Object [ ] [ ] getAllKeyValueData ( ) { logger . entering ( ) ; Object [ ] [ ] objectArray ; try { JAXBContext context = JAXBContext . newInstance ( resource . getCls ( ) ) ; Unmarshaller unmarshaller = context . createUnmarshaller ( ) ; StreamSource xmlStreamSource = new StreamSource ( resource . getInputStream ( ) ) ; Map < String , KeyValuePair > keyValueItems = unmarshaller . unmarshal ( xmlStreamSource , KeyValueMap . class ) . getValue ( ) . getMap ( ) ; objectArray = DataProviderHelper . convertToObjectArray ( keyValueItems ) ; } catch ( JAXBException excp ) { throw new DataProviderException ( "Error unmarshalling XML file." , excp ) ; } logger . exiting ( ) ; return objectArray ; }
Generates a two dimensional array for TestNG DataProvider from the XML data representing a map of name value collection .
37,132
public Object [ ] [ ] getDataByKeys ( String [ ] keys ) { logger . entering ( Arrays . toString ( keys ) ) ; if ( null == resource . getCls ( ) ) { resource . setCls ( KeyValueMap . class ) ; } Object [ ] [ ] objectArray ; try { JAXBContext context = JAXBContext . newInstance ( resource . getCls ( ) ) ; Unmarshaller unmarshaller = context . createUnmarshaller ( ) ; StreamSource xmlStreamSource = new StreamSource ( resource . getInputStream ( ) ) ; Map < String , KeyValuePair > keyValueItems = unmarshaller . unmarshal ( xmlStreamSource , KeyValueMap . class ) . getValue ( ) . getMap ( ) ; objectArray = DataProviderHelper . getDataByKeys ( keyValueItems , keys ) ; } catch ( JAXBException excp ) { logger . exiting ( excp . getMessage ( ) ) ; throw new DataProviderException ( "Error unmarshalling XML file." , excp ) ; } logger . exiting ( ) ; return objectArray ; }
Generates a two dimensional array for TestNG DataProvider from the XML data representing a map of name value collection filtered by keys .
37,133
private List < ? > loadDataFromXmlFile ( ) { logger . entering ( ) ; Preconditions . checkArgument ( resource . getCls ( ) != null , "Please provide a valid type." ) ; List < ? > returned ; try { JAXBContext context = JAXBContext . newInstance ( Wrapper . class , resource . getCls ( ) ) ; Unmarshaller unmarshaller = context . createUnmarshaller ( ) ; StreamSource xmlStreamSource = new StreamSource ( resource . getInputStream ( ) ) ; Wrapper < ? > wrapper = unmarshaller . unmarshal ( xmlStreamSource , Wrapper . class ) . getValue ( ) ; returned = wrapper . getList ( ) ; } catch ( JAXBException excp ) { logger . exiting ( excp . getMessage ( ) ) ; throw new DataProviderException ( "Error unmarshalling XML file." , excp ) ; } logger . exiting ( returned ) ; return returned ; }
Generates a list of the declared type after parsing the XML file .
37,134
private List < ? > loadDataFromXml ( String xml , Class < ? > cls ) { logger . entering ( new Object [ ] { xml , cls } ) ; Preconditions . checkArgument ( cls != null , "Please provide a valid type." ) ; List < ? > returned ; try { JAXBContext context = JAXBContext . newInstance ( Wrapper . class , cls ) ; Unmarshaller unmarshaller = context . createUnmarshaller ( ) ; StringReader xmlStringReader = new StringReader ( xml ) ; StreamSource streamSource = new StreamSource ( xmlStringReader ) ; Wrapper < ? > wrapper = unmarshaller . unmarshal ( streamSource , Wrapper . class ) . getValue ( ) ; returned = wrapper . getList ( ) ; } catch ( JAXBException excp ) { logger . exiting ( excp . getMessage ( ) ) ; throw new DataProviderException ( "Error unmarshalling XML string." , excp ) ; } logger . exiting ( returned ) ; return returned ; }
Generates a list of the declared type after parsing the XML data string .
37,135
@ SuppressWarnings ( "unchecked" ) private String getFilteredXml ( Document document , String xpathExpression ) { logger . entering ( new Object [ ] { document , xpathExpression } ) ; List < Node > nodes = ( List < Node > ) document . selectNodes ( xpathExpression ) ; StringBuilder newDocument = new StringBuilder ( document . asXML ( ) . length ( ) ) ; newDocument . append ( "<root>" ) ; for ( Node n : nodes ) { newDocument . append ( n . asXML ( ) ) ; } newDocument . append ( "</root>" ) ; logger . exiting ( newDocument ) ; return newDocument . toString ( ) ; }
Generates an XML string containing only the nodes filtered by the XPath expression .
37,136
private JsonObject generateConfigSummary ( ) throws JsonParseException { logger . entering ( ) ; if ( jsonConfigSummary == null ) { jsonConfigSummary = new JsonObject ( ) ; for ( Entry < String , String > temp : ConfigSummaryData . getConfigSummary ( ) . entrySet ( ) ) { jsonConfigSummary . addProperty ( temp . getKey ( ) , temp . getValue ( ) ) ; } } logger . exiting ( jsonConfigSummary ) ; return jsonConfigSummary ; }
This method will generate Configuration summary by fetching the details from ReportDataGenerator
37,137
public void generateLocalConfigSummary ( String suiteName , String testName ) { logger . entering ( new Object [ ] { suiteName , testName } ) ; try { Map < String , String > testLocalConfigValues = ConfigSummaryData . getLocalConfigSummary ( testName ) ; JsonObject json = new JsonObject ( ) ; if ( testLocalConfigValues == null ) { json . addProperty ( ReporterDateFormatter . CURRENTDATE , ReporterDateFormatter . getISO8601String ( new Date ( ) ) ) ; } else { for ( Entry < String , String > temp : testLocalConfigValues . entrySet ( ) ) { json . addProperty ( temp . getKey ( ) , temp . getValue ( ) ) ; } } json . addProperty ( "suite" , suiteName ) ; json . addProperty ( "test" , testName ) ; synchronized ( this ) { this . testJsonLocalConfigSummary . add ( json ) ; } } catch ( JsonParseException e ) { logger . log ( Level . SEVERE , e . getMessage ( ) , e ) ; throw new ReporterException ( e ) ; } logger . exiting ( ) ; }
This method will generate local Configuration summary by fetching the details from ReportDataGenerator
37,138
public synchronized void insertConfigMethod ( String suite , String test , String packages , String classname , ITestResult result ) { logger . entering ( new Object [ ] { suite , test , packages , classname , result } ) ; String type = null ; if ( result . getMethod ( ) . isBeforeSuiteConfiguration ( ) ) { type = BEFORE_SUITE ; } else if ( result . getMethod ( ) . isBeforeTestConfiguration ( ) ) { type = BEFORE_TEST ; } else if ( result . getMethod ( ) . isBeforeGroupsConfiguration ( ) ) { type = BEFORE_GROUP ; } else if ( result . getMethod ( ) . isBeforeClassConfiguration ( ) ) { type = BEFORE_CLASS ; } else if ( result . getMethod ( ) . isBeforeMethodConfiguration ( ) ) { type = BEFORE_METHOD ; } else if ( result . getMethod ( ) . isAfterSuiteConfiguration ( ) ) { type = AFTER_SUITE ; } else if ( result . getMethod ( ) . isAfterTestConfiguration ( ) ) { type = AFTER_TEST ; } else if ( result . getMethod ( ) . isAfterGroupsConfiguration ( ) ) { type = AFTER_GROUP ; } else if ( result . getMethod ( ) . isAfterClassConfiguration ( ) ) { type = AFTER_CLASS ; } else if ( result . getMethod ( ) . isAfterMethodConfiguration ( ) ) { type = AFTER_METHOD ; } ConfigMethodInfo config1 = new ConfigMethodInfo ( suite , test , packages , classname , type , result ) ; if ( result . getStatus ( ) == ITestResult . STARTED ) { runningConfig . add ( config1 ) ; return ; } for ( ConfigMethodInfo temp : runningConfig ) { if ( temp . getResult ( ) . getMethod ( ) . equals ( result . getMethod ( ) ) ) { runningConfig . remove ( temp ) ; break ; } } appendFile ( jsonCompletedConfig , config1 . toJson ( ) . concat ( ",\n" ) ) ; logger . exiting ( ) ; }
This method is used to insert configuration method details based on the suite test groups and class name .
37,139
public synchronized void writeJSON ( String outputDirectory , boolean bForceWrite ) { logger . entering ( new Object [ ] { outputDirectory , bForceWrite } ) ; long currentTime = System . currentTimeMillis ( ) ; if ( ! bForceWrite && ( currentTime - previousTime < ONE_MINUTE ) ) { return ; } previousTime = currentTime ; parseCompletedTest ( ) ; generateReports ( outputDirectory ) ; logger . exiting ( ) ; }
Generate the final report . json from the completed test and completed configuration temporary files .
37,140
private void generateReports ( String outputDirectory ) { logger . entering ( outputDirectory ) ; ClassLoader localClassLoader = this . getClass ( ) . getClassLoader ( ) ; try ( BufferedWriter writer = new BufferedWriter ( new FileWriter ( outputDirectory + File . separator + "index.html" ) ) ; BufferedWriter jsonWriter = new BufferedWriter ( new FileWriter ( outputDirectory + File . separator + "report.json" ) ) ; BufferedReader templateReader = new BufferedReader ( new InputStreamReader ( localClassLoader . getResourceAsStream ( "templates/RuntimeReporter/index.html" ) ) ) ; ) { JsonObject reporter = buildJSONReport ( ) ; Gson gson = new GsonBuilder ( ) . setPrettyPrinting ( ) . create ( ) ; String jsonReport = gson . toJson ( reporter ) ; jsonWriter . write ( jsonReport ) ; jsonWriter . newLine ( ) ; generateHTMLReport ( writer , templateReader , jsonReport ) ; } catch ( IOException | JsonParseException e ) { logger . log ( Level . SEVERE , e . getMessage ( ) , e ) ; throw new ReporterException ( e ) ; } logger . exiting ( ) ; }
Generate JSON report and HTML report
37,141
private void generateHTMLReport ( BufferedWriter writer , BufferedReader templateReader , String jsonReport ) throws IOException { logger . entering ( new Object [ ] { writer , templateReader , jsonReport } ) ; String readLine = null ; while ( ( readLine = templateReader . readLine ( ) ) != null ) { if ( readLine . trim ( ) . equals ( "${reports}" ) ) { writer . write ( jsonReport ) ; writer . newLine ( ) ; } else { writer . write ( readLine ) ; writer . newLine ( ) ; } } logger . exiting ( ) ; }
Writing JSON content to HTML file
37,142
private JsonObject buildJSONReport ( ) { logger . entering ( ) ; Gson gson = new GsonBuilder ( ) . setPrettyPrinting ( ) . create ( ) ; JsonArray testObjects = loadJSONArray ( jsonCompletedTest ) ; for ( TestMethodInfo temp : completedTest ) { testObjects . add ( gson . fromJson ( temp . toJson ( ) , JsonElement . class ) ) ; } for ( TestMethodInfo temp : runningTest ) { testObjects . add ( gson . fromJson ( temp . toJson ( ) , JsonElement . class ) ) ; } JsonArray configObjects = loadJSONArray ( jsonCompletedConfig ) ; for ( ConfigMethodInfo temp : runningConfig ) { configObjects . add ( gson . fromJson ( temp . toJson ( ) , JsonElement . class ) ) ; } JsonObject summary = new JsonObject ( ) ; summary . add ( "testMethodsSummary" , getReportSummaryCounts ( testObjects ) ) ; summary . add ( "configurationMethodsSummary" , getReportSummaryCounts ( configObjects ) ) ; JsonElement reportMetadata = gson . fromJson ( ReporterConfigMetadata . toJsonAsString ( ) , JsonElement . class ) ; JsonObject reporter = new JsonObject ( ) ; reporter . add ( "reportSummary" , summary ) ; reporter . add ( "testMethods" , testObjects ) ; reporter . add ( "configurationMethods" , configObjects ) ; reporter . add ( "configSummary" , generateConfigSummary ( ) ) ; reporter . add ( "localConfigSummary" , testJsonLocalConfigSummary ) ; reporter . add ( "reporterMetadata" , reportMetadata ) ; logger . exiting ( reporter ) ; return reporter ; }
Construct the JSON report for report generation
37,143
private JsonObject getReportSummaryCounts ( JsonArray testObjects ) { logger . entering ( testObjects ) ; int runningCount = 0 ; int skippedCount = 0 ; int passedCount = 0 ; int failedCount = 0 ; String result ; for ( JsonElement test : testObjects ) { result = test . getAsJsonObject ( ) . get ( "status" ) . getAsString ( ) ; switch ( result ) { case "Running" : runningCount += 1 ; break ; case "Passed" : passedCount += 1 ; break ; case "Failed" : failedCount += 1 ; break ; case "Skipped" : skippedCount += 1 ; break ; default : logger . warning ( "Found invalid status of the test being run. Status: " + result ) ; } } JsonObject testSummary = new JsonObject ( ) ; if ( 0 < runningCount ) { testSummary . addProperty ( "running" , runningCount ) ; } testSummary . addProperty ( "passed" , passedCount ) ; testSummary . addProperty ( "failed" , failedCount ) ; testSummary . addProperty ( "skipped" , skippedCount ) ; logger . exiting ( testSummary ) ; return testSummary ; }
Provides a JSON object representing the counts of tests passed failed skipped and running .
37,144
private JsonArray loadJSONArray ( File jsonFile ) throws JsonParseException { logger . entering ( jsonFile ) ; String jsonTxt ; try { jsonTxt = FileUtils . readFileToString ( jsonFile , "UTF-8" ) ; } catch ( IOException e ) { logger . log ( Level . SEVERE , e . getMessage ( ) , e ) ; throw new ReporterException ( e ) ; } StringBuilder completeJSONTxt = new StringBuilder ( "[" ) ; completeJSONTxt . append ( StringUtils . removeEnd ( jsonTxt , ",\n" ) ) ; completeJSONTxt . append ( "]" ) ; JsonArray testObjects = ( new JsonParser ( ) ) . parse ( completeJSONTxt . toString ( ) ) . getAsJsonArray ( ) ; logger . exiting ( testObjects ) ; return testObjects ; }
Load the json array for the given file
37,145
private String [ ] getNodeProgramArguments ( ) throws IOException { LOGGER . entering ( ) ; LOGGER . fine ( "This instance is considered a SeLion Grid Node" ) ; List < String > args = new LinkedList < > ( ) ; if ( ! commands . contains ( NODE_CONFIG_ARG ) ) { args . add ( NODE_CONFIG_ARG ) ; args . add ( NODE_CONFIG_FILE ) ; InstallHelper . copyFileFromResources ( NODE_CONFIG_FILE_RESOURCE , NODE_CONFIG_FILE ) ; } LOGGER . exiting ( args . toString ( ) ) ; return args . toArray ( new String [ args . size ( ) ] ) ; }
Get SeLion Node related arguments to pass
37,146
private String [ ] getHubProgramArguments ( ) throws IOException { LOGGER . entering ( ) ; LOGGER . fine ( "This instance is considered a SeLion Grid Hub" ) ; List < String > args = new LinkedList < > ( ) ; if ( ! commands . contains ( HUB_CONFIG_ARG ) ) { String hubConfig = HUB_CONFIG_FILE ; if ( commands . contains ( SeLionGridHubConfiguration . TYPE_ARG ) && commands . contains ( InstanceType . SELION_SAUCE_HUB . getFriendlyName ( ) ) ) { hubConfig = HUB_SAUCE_CONFIG_FILE ; InstallHelper . copyFileFromResources ( HUB_SAUCE_CONFIG_FILE_RESOURCE , HUB_SAUCE_CONFIG_FILE ) ; InstallHelper . copyFileFromResources ( NODE_SAUCE_CONFIG_FILE_RESOURCE , NODE_SAUCE_CONFIG_FILE ) ; InstallHelper . copyFileFromResources ( SAUCE_CONFIG_FILE_RESOURCE , SAUCE_CONFIG_FILE ) ; } else { InstallHelper . copyFileFromResources ( HUB_CONFIG_FILE_RESOURCE , HUB_CONFIG_FILE ) ; } args . add ( HUB_CONFIG_ARG ) ; args . add ( hubConfig ) ; } LOGGER . exiting ( args . toString ( ) ) ; return args . toArray ( new String [ args . size ( ) ] ) ; }
Get SeLion Grid related arguments to pass
37,147
String getHost ( ) { LOGGER . entering ( ) ; String val = "" ; InstanceType type = getType ( ) ; if ( commands . contains ( HOST_ARG ) ) { val = commands . get ( commands . indexOf ( HOST_ARG ) + 1 ) ; LOGGER . exiting ( val ) ; return val ; } try { if ( type . equals ( InstanceType . SELENIUM_NODE ) || type . equals ( InstanceType . SELENIUM_HUB ) ) { val = getSeleniumConfigAsJsonObject ( ) . get ( "host" ) . getAsString ( ) ; } } catch ( JsonParseException | NullPointerException e ) { } val = ( StringUtils . isNotEmpty ( val ) && ! val . equalsIgnoreCase ( "ip" ) ) ? val : "localhost" ; LOGGER . exiting ( val ) ; return val ; }
Get the host for the instance represented by this launcher
37,148
int getPort ( ) { LOGGER . entering ( ) ; int val = - 1 ; InstanceType type = getType ( ) ; if ( commands . contains ( PORT_ARG ) ) { val = Integer . parseInt ( commands . get ( commands . indexOf ( PORT_ARG ) + 1 ) ) ; LOGGER . exiting ( val ) ; return val ; } try { if ( type . equals ( InstanceType . SELENIUM_NODE ) || type . equals ( InstanceType . SELENIUM_HUB ) ) { val = getSeleniumConfigAsJsonObject ( ) . get ( "port" ) . getAsInt ( ) ; } } catch ( JsonParseException | NullPointerException e ) { } val = ( val != - 1 ) ? val : 4444 ; LOGGER . exiting ( val ) ; return val ; }
Get the port for the instance represented by this launcher
37,149
private String getSeleniumConfigFilePath ( ) { LOGGER . entering ( ) ; String result = null ; InstanceType type = getType ( ) ; if ( type . equals ( InstanceType . SELENIUM_NODE ) ) { result = NODE_CONFIG_FILE ; if ( commands . contains ( NODE_CONFIG_ARG ) ) { result = commands . get ( commands . indexOf ( NODE_CONFIG_ARG ) + 1 ) ; } } if ( type . equals ( InstanceType . SELENIUM_HUB ) ) { result = HUB_CONFIG_FILE ; if ( commands . contains ( HUB_CONFIG_ARG ) ) { result = commands . get ( commands . indexOf ( HUB_CONFIG_ARG ) + 1 ) ; } } LOGGER . exiting ( result ) ; return result ; }
Get the config file path for the instance represented by this launcher .
37,150
private boolean matchAgainstMobileNodeType ( Map < String , Object > nodeCapability , String mobileNodeType ) { String nodeValue = ( String ) nodeCapability . get ( MOBILE_NODE_TYPE ) ; return ! StringUtils . isBlank ( nodeValue ) && nodeValue . equalsIgnoreCase ( mobileNodeType ) ; }
Matches requested mobileNodeType against node capabilities .
37,151
public static RemoteNodeInformation getRemoteNodeInfo ( String hostName , int port , SessionId session ) { logger . entering ( new Object [ ] { hostName , port , session } ) ; RemoteNodeInformation node = null ; String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: " ; if ( Config . getBoolConfigProperty ( ConfigProperty . SELENIUM_USE_SAUCELAB_GRID ) ) { logger . exiting ( node ) ; return node ; } try { HttpHost host = new HttpHost ( hostName , port ) ; CloseableHttpClient client = HttpClientBuilder . create ( ) . build ( ) ; URL sessionURL = new URL ( "http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session ) ; BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest ( "POST" , sessionURL . toExternalForm ( ) ) ; CloseableHttpResponse response = client . execute ( host , r ) ; JSONObject object = extractObject ( response ) ; URL myURL = new URL ( object . getString ( "proxyId" ) ) ; if ( ( myURL . getHost ( ) != null ) && ( myURL . getPort ( ) != - 1 ) ) { node = new RemoteNodeInformation ( myURL . getHost ( ) , myURL . getPort ( ) ) ; } } catch ( Exception e ) { logger . log ( Level . FINE , errorMsg , e ) ; } logger . exiting ( node ) ; return node ; }
For a given Session ID against a host on a particular port this method returns the remote webdriver node and the port to which the execution was redirected to by the hub .
37,152
public static String getBuildValue ( SeLionBuildProperty property ) { return getInfo ( ) . getProperty ( property . getPropertyValue ( ) , property . getFallBackValue ( ) ) ; }
Returns values for build time info
37,153
public static SeLionDataProvider getDataProvider ( DataResource resource ) throws IOException { logger . entering ( resource ) ; if ( resource == null ) { return null ; } switch ( resource . getType ( ) . toUpperCase ( ) ) { case "XML" : return new XmlDataProviderImpl ( ( XmlDataSource ) resource ) ; case "JSON" : return new JsonDataProviderImpl ( resource ) ; case "YAML" : case "YML" : return new YamlDataProviderImpl ( resource ) ; case "XLSX" : case "XLS" : return new ExcelDataProviderImpl ( resource ) ; default : return null ; } }
Load the Data provider implementation for the data file type
37,154
private boolean isSupportedOnHub ( Class < ? extends HttpServlet > servlet ) { LOGGER . entering ( ) ; final boolean response = getRegistry ( ) . getHub ( ) . getConfiguration ( ) . servlets . contains ( servlet . getCanonicalName ( ) ) ; LOGGER . exiting ( response ) ; return response ; }
Determine if the hub supports the servlet in question by looking at the registry configuration .
37,155
private boolean isSupportedOnNode ( Class < ? extends HttpServlet > servlet ) { LOGGER . entering ( ) ; RequestConfig requestConfig = RequestConfig . custom ( ) . setConnectTimeout ( CONNECTION_TIMEOUT ) . setSocketTimeout ( CONNECTION_TIMEOUT ) . build ( ) ; CloseableHttpClient client = HttpClientBuilder . create ( ) . setDefaultRequestConfig ( requestConfig ) . build ( ) ; String url = String . format ( "http://%s:%d/extra/%s" , machine , getRemoteHost ( ) . getPort ( ) , servlet . getSimpleName ( ) ) ; try { HttpGet get = new HttpGet ( url ) ; final HttpResponse getResponse = client . execute ( get ) ; if ( getResponse . getStatusLine ( ) . getStatusCode ( ) != HttpStatus . SC_OK ) { proxyLogger . warning ( "Node " + getId ( ) + " does not have or support " + servlet . getSimpleName ( ) ) ; LOGGER . exiting ( false ) ; return false ; } } catch ( IOException e ) { LOGGER . log ( Level . SEVERE , e . getMessage ( ) , e ) ; LOGGER . exiting ( false ) ; return false ; } finally { try { client . close ( ) ; } catch ( IOException e ) { LOGGER . log ( Level . SEVERE , e . getMessage ( ) , e ) ; } } LOGGER . exiting ( true ) ; return true ; }
Determine if the remote proxy supports the servlet in question by sending a http request to the remote . The proxy configuration could also be used to make a similar decision . This approach allows the remote to use a servlet which implements the same functionality as the servlet expected but does not necessarily reside in the same namespace . This method expects the servlet to return HTTP 200 OK as an indication that the remote proxy supports the servlet in question .
37,156
public int getMaxConcurrency ( ) { LOGGER . entering ( ) ; if ( maxTestCase == - 1 ) { try { SauceLabsHttpResponse result = doSauceRequest ( "/limits" ) ; JsonObject obj = result . getEntityAsJsonObject ( ) ; maxTestCase = obj . get ( "concurrency" ) . getAsInt ( ) ; } catch ( JsonSyntaxException | IllegalStateException | IOException e ) { LOGGER . log ( Level . SEVERE , "Unable to get max concurrency." , e ) ; } } LOGGER . exiting ( maxTestCase ) ; return maxTestCase ; }
Get the maximum number of test case that can run in parallel for the primary account .
37,157
public static void assertNotEquals ( Object actual , Object expected , String msg ) { hardAssert . assertNotEquals ( actual , expected , msg ) ; }
assertNotEquals method is used to assert based on actual and expected values and provide a Pass result for a mismatch .
37,158
public static void verifyEquals ( Object actual , Object expected , String msg ) { getSoftAssertInContext ( ) . assertEquals ( actual , expected , msg ) ; }
verifyEquals method is used to assert based on actual and expected values and provide a Pass result for a same match . verifyEquals will yield a Fail result for a mismatch and continue to run the test case .
37,159
public static void verifyNotEquals ( Object actual , Object expected , String msg ) { getSoftAssertInContext ( ) . assertNotEquals ( actual , expected , msg ) ; }
verifyNotEquals method is used to assert based on actual and expected values and provide a Pass result for a mismatch and continue to run the test .
37,160
public static void assertEquals ( Object actual , Object expected , String message ) { hardAssert . assertEquals ( actual , expected , message ) ; }
assertEquals method is used to assert based on actual and expected values and provide a Pass result for a same match . assertEquals will yield a Fail result for a mismatch and abort the test case .
37,161
public static boolean wildCardMatch ( String text , String pattern ) { logger . entering ( new Object [ ] { text , pattern } ) ; Preconditions . checkArgument ( text != null , "The text on which the search is to be run cannot be null." ) ; Preconditions . checkArgument ( pattern != null , "The search pattern cannot be null." ) ; String [ ] cards = pattern . split ( "\\*" ) ; for ( String card : cards ) { int idx = text . indexOf ( card ) ; if ( idx == - 1 ) { logger . exiting ( false ) ; return false ; } text = text . substring ( idx + card . length ( ) ) ; } logger . exiting ( true ) ; return true ; }
Performs a wild - card matching for the text and pattern provided .
37,162
public void setId ( String id ) { logger . entering ( id ) ; this . id = id ; logger . exiting ( ) ; }
Set the id for this page source object
37,163
public byte [ ] getScreenImage ( ) { logger . entering ( ) ; logger . exiting ( this . screenImage ) ; return Arrays . copyOf ( screenImage , screenImage . length ) ; }
Get the image content
37,164
public void setScreenImage ( byte [ ] content ) { logger . entering ( content ) ; this . screenImage = Arrays . copyOf ( content , content . length ) ; logger . exiting ( ) ; }
Set the image content
37,165
public static void addReporterMetadataItem ( String key , String itemType , String value ) { logger . entering ( new Object [ ] { key , itemType , value } ) ; if ( StringUtils . isNotBlank ( value ) && supportedMetaDataProperties . contains ( itemType ) ) { Map < String , String > subMap = reporterMetadata . get ( key ) ; if ( null == subMap ) { subMap = new HashMap < String , String > ( ) ; } subMap . put ( itemType , value ) ; reporterMetadata . put ( key , subMap ) ; } else { String message = "Key/value pair for '" + key + "' for '" + itemType + "' was not inserted into report metadata." ; logger . fine ( message ) ; } }
Adds an new item to the reporter metadata .
37,166
public static String toJsonAsString ( ) { logger . entering ( ) ; Gson gson = new GsonBuilder ( ) . setPrettyPrinting ( ) . create ( ) ; JsonObject configItem = new JsonObject ( ) ; for ( Entry < String , Map < String , String > > entry : ReporterConfigMetadata . getReporterMetaData ( ) . entrySet ( ) ) { Map < String , String > subMap = entry . getValue ( ) ; for ( Entry < String , String > subEntry : subMap . entrySet ( ) ) { JsonObject configSubItem = new JsonObject ( ) ; configSubItem . addProperty ( subEntry . getKey ( ) , subEntry . getValue ( ) ) ; configItem . add ( entry . getKey ( ) , configSubItem ) ; } } String json = gson . toJson ( configItem ) ; logger . exiting ( json ) ; return json ; }
This method will generate JSON string representation of the all items in current ReportConfigMetadata .
37,167
public static String getPackage ( String element ) { Preconditions . checkNotNull ( element , "argument 'element' can not be null" ) ; return element . substring ( 0 , element . lastIndexOf ( '.' ) ) ; }
Extracts the package from a qualified class .
37,168
public static String getClass ( String element ) { Preconditions . checkNotNull ( element , "argument 'element' can not be null" ) ; return element . substring ( element . lastIndexOf ( '.' ) + 1 ) ; }
Extracts the class name from a qualified class .
37,169
public boolean filter ( Object data ) { logger . entering ( new Object [ ] { data } ) ; invocationCount += 1 ; for ( int index : this . indexes ) { if ( invocationCount == index ) { logger . exiting ( true ) ; return true ; } } logger . exiting ( false ) ; return false ; }
This function identifies whether the object falls in the filtering criteria or not based on the indexes provided . For this we are using the invocation count for comparing the index .
37,170
public synchronized static void initConfig ( ISuite suite ) { SeLionLogger . getLogger ( ) . entering ( suite ) ; Map < ConfigProperty , String > initialValues = new HashMap < > ( ) ; for ( ConfigProperty prop : ConfigProperty . values ( ) ) { String paramValue = suite . getParameter ( prop . getName ( ) ) ; if ( paramValue != null ) { initialValues . put ( prop , paramValue ) ; } } initConfig ( initialValues ) ; SeLionLogger . getLogger ( ) . exiting ( ) ; }
Parses suite parameters and generates SeLion Config object
37,171
public synchronized static void initConfig ( ITestContext context ) { SeLionLogger . getLogger ( ) . entering ( context ) ; Map < ConfigProperty , String > initialValues = new HashMap < > ( ) ; Map < String , String > testParams = context . getCurrentXmlTest ( ) . getLocalParameters ( ) ; if ( ! testParams . isEmpty ( ) ) { for ( ConfigProperty prop : ConfigProperty . values ( ) ) { String newValue = testParams . get ( prop . getName ( ) ) ; if ( newValue != null ) { initialValues . put ( prop , newValue ) ; } } } ConfigManager . addConfig ( context . getCurrentXmlTest ( ) . getName ( ) , new LocalConfig ( initialValues ) ) ; SeLionLogger . getLogger ( ) . exiting ( ) ; }
Parses configuration file and extracts values for test environment
37,172
public synchronized static void initConfig ( ) { SeLionLogger . getLogger ( ) . entering ( ) ; Map < ConfigProperty , String > initialValues = new HashMap < > ( ) ; initConfig ( initialValues ) ; SeLionLogger . getLogger ( ) . exiting ( ) ; }
Reads and parses configuration file Initializes the configuration reloading all data
37,173
public static void printSeLionConfigValues ( ) { SeLionLogger . getLogger ( ) . entering ( ) ; StringBuilder builder = new StringBuilder ( "SeLion configuration: {" ) ; boolean isFirst = true ; for ( ConfigProperty configProperty : ConfigProperty . values ( ) ) { if ( ! isFirst ) { builder . append ( ", " ) ; } builder . append ( String . format ( "(%s: %s)" , configProperty , Config . getConfig ( ) . getString ( configProperty . getName ( ) ) ) ) ; isFirst = false ; } builder . append ( "}\n" ) ; SeLionLogger . getLogger ( ) . info ( builder . toString ( ) ) ; SeLionLogger . getLogger ( ) . exiting ( ) ; }
Prints SeLion Config Values
37,174
public static synchronized void setConfigProperty ( ConfigProperty configProperty , Object configPropertyValue ) { checkArgument ( configProperty != null , "Config property cannot be null." ) ; checkArgument ( configPropertyValue != null , "Config property value cannot be null." ) ; getConfig ( ) . setProperty ( configProperty . getName ( ) , configPropertyValue ) ; }
Sets a SeLion configuration value . This is useful when you want to override or set a setting .
37,175
private boolean generateJavaCode ( File baseFile , File dataFile , File extendedFile ) { return ( baseFile . lastModified ( ) < dataFile . lastModified ( ) || ( extendedFile . exists ( ) && baseFile . lastModified ( ) < extendedFile . lastModified ( ) ) ) ; }
3 . Last modified timestamp of the extended java file is greater than that of the corresponding yaml file .
37,176
public static synchronized void spawnLocalHub ( AbstractTestSession testSession ) { LOGGER . entering ( testSession . getPlatform ( ) ) ; if ( ! isRunLocally ( ) ) { LOGGER . exiting ( ) ; return ; } setupToBootList ( ) ; for ( LocalServerComponent eachItem : toBoot ) { try { eachItem . boot ( testSession ) ; } catch ( Exception e ) { LOGGER . log ( Level . SEVERE , e . getMessage ( ) , e ) ; System . exit ( 1 ) ; } } LOGGER . exiting ( ) ; }
This method is responsible for spawning a local hub for supporting local executions
37,177
static synchronized void shutDownHub ( ) { LOGGER . entering ( ) ; if ( ! isRunLocally ( ) ) { LOGGER . exiting ( ) ; return ; } Collections . reverse ( toBoot ) ; for ( LocalServerComponent eachItem : toBoot ) { eachItem . shutdown ( ) ; } clearToBootList ( ) ; LOGGER . exiting ( ) ; }
This method helps shut down the already spawned hub for local runs
37,178
public static void initReportData ( List < ISuite > suites ) { logger . entering ( suites ) ; if ( ! isReportInitialized ) { for ( ISuite suite : suites ) { Map < String , ISuiteResult > r = suite . getResults ( ) ; for ( ISuiteResult r2 : r . values ( ) ) { ITestContext tc = r2 . getTestContext ( ) ; ITestNGMethod [ ] methods = tc . getAllTestMethods ( ) ; for ( ITestNGMethod method : methods ) { method . setId ( UUID . randomUUID ( ) . toString ( ) ) ; } } } isReportInitialized = true ; } logger . exiting ( ) ; }
init the uniques id for the methods needed to create the navigation .
37,179
public static String getStringFromISODateString ( String dateISOString ) { Date date ; String formattedDate ; DateFormat formatter = getFormatter ( ) ; try { date = formatter . parse ( dateISOString ) ; formattedDate = DateFormat . getDateTimeInstance ( DateFormat . MEDIUM , DateFormat . SHORT ) . format ( date ) ; } catch ( ParseException e ) { logger . log ( Level . WARNING , e . getMessage ( ) , e ) ; formattedDate = dateISOString ; } return formattedDate ; }
Return an reader friendly date from ISO 8601 combined date and time string .
37,180
public static Entry < String , String > formatReportDataForBrowsableReports ( Entry < String , String > entryItem ) { String key = entryItem . getKey ( ) ; String value = entryItem . getValue ( ) ; String formattedKey = key ; String formattedValue = value ; switch ( key ) { case ReporterDateFormatter . CURRENTDATE : formattedKey = "Current Date" ; formattedValue = ReporterDateFormatter . getStringFromISODateString ( value ) ; break ; default : break ; } return new AbstractMap . SimpleImmutableEntry < String , String > ( formattedKey , formattedValue ) ; }
Formats specific keys and values into readable form for HTML Reporter .
37,181
public synchronized String getConfigProperty ( Config . ConfigProperty configProperty ) { SeLionLogger . getLogger ( ) . entering ( configProperty ) ; checkArgument ( configProperty != null , "Config property cannot be null" ) ; String propValue = null ; if ( baseConfig . containsKey ( configProperty . getName ( ) ) ) { propValue = baseConfig . getString ( configProperty . getName ( ) ) ; } if ( StringUtils . isBlank ( propValue ) ) { propValue = Config . getConfigProperty ( configProperty ) ; } SeLionLogger . getLogger ( ) . exiting ( propValue ) ; return propValue ; }
Get the configuration property value for configProperty .
37,182
public synchronized void setConfigProperty ( Config . ConfigProperty configProperty , Object configPropertyValue ) { checkArgument ( configProperty != null , "Config property cannot be null" ) ; checkArgument ( checkNotInGlobalScope ( configProperty ) , String . format ( "The configuration property (%s) is not supported in local config." , configProperty ) ) ; checkArgument ( configPropertyValue != null , "Config property value cannot be null" ) ; baseConfig . setProperty ( configProperty . getName ( ) , configPropertyValue ) ; }
Sets the SeLion configuration property value .
37,183
public synchronized boolean isLocalValuePresent ( ConfigProperty configProperty ) { checkArgument ( configProperty != null , "Config property cannot be null" ) ; String value = baseConfig . getString ( configProperty . getName ( ) ) ; return value != null ; }
Answer if local configuration contains a value for specified property .
37,184
private void initSeLionRemoteProxySpecificValues ( RemoteProxy proxy ) { if ( SeLionRemoteProxy . class . getCanonicalName ( ) . equals ( proxy . getOriginalRegistrationRequest ( ) . getConfiguration ( ) . proxy ) ) { SeLionRemoteProxy srp = ( SeLionRemoteProxy ) proxy ; isShuttingDown = srp . isScheduledForRecycle ( ) ; if ( srp . supportsViewLogs ( ) ) { logsLocation = proxy . getRemoteHost ( ) . toExternalForm ( ) + "/extra/" + LogServlet . class . getSimpleName ( ) ; } totalSessionsStarted = srp . getTotalSessionsStarted ( ) ; totalSessionsComplete = srp . getTotalSessionsComplete ( ) ; uptimeInMinutes = srp . getUptimeInMinutes ( ) ; } }
SeLion specific features
37,185
private String appendMoreLogsLink ( final String fileName , String url ) throws IOException { FileBackedStringBuffer buffer = new FileBackedStringBuffer ( ) ; int index = retrieveIndexValueFromFileName ( fileName ) ; index ++ ; File logFileName = retrieveFileFromLogsFolder ( Integer . toString ( index ) ) ; if ( logFileName == null ) { return "" ; } buffer . append ( "<form name ='myform' action=" ) . append ( url ) . append ( " method= 'post'>" ) ; buffer . append ( "<input type='hidden'" ) . append ( " name ='fileName'" ) . append ( " value ='" ) . append ( logFileName . getName ( ) ) . append ( "'>" ) ; buffer . append ( "<a href= 'javascript: submitform();' > More Logs </a>" ) ; buffer . append ( "</form>" ) ; return buffer . toString ( ) ; }
This method helps to display More log information of the node machine .
37,186
private File getLogsDirectory ( ) { if ( logsDirectory != null ) { return logsDirectory ; } logsDirectory = new File ( SeLionGridConstants . LOGS_DIR ) ; if ( ! logsDirectory . exists ( ) ) { logsDirectory . mkdirs ( ) ; } return logsDirectory ; }
This method get the Logs file directory
37,187
protected void process ( HttpServletRequest request , HttpServletResponse response , String fileName ) throws IOException { response . setContentType ( "text/html" ) ; response . setCharacterEncoding ( "UTF-8" ) ; response . setStatus ( 200 ) ; FileBackedStringBuffer buffer = new FileBackedStringBuffer ( ) ; buffer . append ( "<html><head><title>" ) ; buffer . append ( request . getRemoteHost ( ) ) ; buffer . append ( "</title><script type=text/javascript>" ) ; buffer . append ( "function submitform() { document.myform.submit(); } </script>" ) ; buffer . append ( "</head><body><H1>View Logs on - " ) ; buffer . append ( request . getRemoteHost ( ) ) . append ( "</H1>" ) ; if ( isLogsDirectoryEmpty ( ) ) { buffer . append ( "<br>No Logs available.</br></body></html>" ) ; dumpStringToStream ( buffer , response . getOutputStream ( ) ) ; return ; } buffer . append ( appendMoreLogsLink ( fileName , request . getRequestURL ( ) . toString ( ) ) ) ; buffer . append ( renderLogFileContents ( fileName ) ) ; buffer . append ( "</body></html>" ) ; dumpStringToStream ( buffer , response . getOutputStream ( ) ) ; }
This method display the log file content
37,188
private String renderLogFileContents ( String fileName ) throws IOException { FileBackedStringBuffer buffer = new FileBackedStringBuffer ( ) ; int index = retrieveIndexValueFromFileName ( fileName ) ; int runningIndex = 0 ; File eachFile = null ; while ( ( eachFile = retrieveFileFromLogsFolder ( Integer . toString ( runningIndex ) ) ) != null && ( runningIndex <= index ) ) { BufferedReader reader = new BufferedReader ( new FileReader ( eachFile ) ) ; String line = "" ; buffer . append ( "<pre>" ) ; while ( ( line = reader . readLine ( ) ) != null ) { buffer . append ( "<br>" ) . append ( line ) . append ( "</br>" ) ; } buffer . append ( "</pre>" ) ; reader . close ( ) ; runningIndex ++ ; } return buffer . toString ( ) ; }
This method read the content of the file and append into FileBackedStringBuffer
37,189
private File retrieveFileFromLogsFolder ( String index ) { File [ ] logFiles = getLogsDirectory ( ) . listFiles ( new LogFilesFilter ( ) ) ; File fileToReturn = null ; for ( File eachLogFile : logFiles ) { String fileName = eachLogFile . getName ( ) . split ( "\\Q.\\E" ) [ 0 ] ; if ( fileName . endsWith ( index ) ) { fileToReturn = eachLogFile ; break ; } } return fileToReturn ; }
Get the log files from the directory
37,190
public static GuiMapReader getInstance ( String pageDomain , String pageClassName ) throws IOException { logger . entering ( new Object [ ] { pageDomain , pageClassName } ) ; Preconditions . checkArgument ( StringUtils . isNotBlank ( pageClassName ) , "pageClassName can not be null, empty, or whitespace" ) ; String guiDataDir = Config . getConfigProperty ( ConfigProperty . GUI_DATA_DIR ) ; String processedPageDomain = StringUtils . defaultString ( pageDomain , "" ) ; String rawDataFile = guiDataDir + "/" + processedPageDomain + "/" + pageClassName ; if ( processedPageDomain . isEmpty ( ) ) { rawDataFile = guiDataDir + "/" + pageClassName ; } String yamlFile = rawDataFile + ".yaml" ; String ymlFile = rawDataFile + ".yml" ; GuiMapReader dataProvider ; if ( getFilePath ( yamlFile ) != null ) { dataProvider = YamlReaderFactory . createInstance ( yamlFile ) ; } else if ( getFilePath ( ymlFile ) != null ) { dataProvider = YamlReaderFactory . createInstance ( ymlFile ) ; } else { FileNotFoundException e = new FileNotFoundException ( "Data file does not exist for " + rawDataFile + ". Supported file extensions: yaml, yml." ) ; logger . log ( Level . SEVERE , e . getMessage ( ) , e ) ; throw e ; } logger . exiting ( dataProvider ) ; return dataProvider ; }
Method to get the reader instance depending on the input parameters .
37,191
private static String getFilePath ( String file ) { logger . entering ( file ) ; String filePath = null ; URL fileURL = GuiMapReaderFactory . class . getClassLoader ( ) . getResource ( file ) ; if ( fileURL != null ) { filePath = fileURL . getPath ( ) ; } logger . exiting ( filePath ) ; return filePath ; }
Method to get the complete file path .
37,192
public int getNumberOfColumns ( ) { List < WebElement > cells ; String xPath = getXPathBase ( ) + "tr" ; List < WebElement > elements = HtmlElementUtils . locateElements ( xPath ) ; if ( elements . size ( ) > 0 && getDataStartIndex ( ) - 1 < elements . size ( ) ) { cells = elements . get ( getDataStartIndex ( ) - 1 ) . findElements ( By . xpath ( "td" ) ) ; return cells . size ( ) ; } return 0 ; }
Returns the number of columns in a table . If the table is empty column count cannot be determined and 0 will be returned .
37,193
public void clickLinkInCell ( int row , int column ) { String xPath = getXPathBase ( ) + "tr[" + row + "]/td[" + column + "]/a" ; new Link ( xPath ) . click ( ) ; }
Goes to the cell addressed by row and column indices and clicks link in that cell . Performs wait until page would be loaded
37,194
public String getRowText ( int rowIndex ) { String rowText = null ; String xPath = getXPathBase ( ) + "tr[" + rowIndex + "]" ; rowText = HtmlElementUtils . locateElement ( xPath ) . getText ( ) ; return rowText ; }
Returns the single row of a table as a long string of text using the input row index .
37,195
public void checkCheckboxInCell ( int row , int column ) { String checkboxLocator = getXPathBase ( ) + "tr[" + row + "]/td[" + column + "]/input" ; CheckBox cb = new CheckBox ( checkboxLocator ) ; cb . check ( ) ; }
Tick the checkbox in a cell of a table indicated by input row and column indices
37,196
public void uncheckCheckboxInCell ( int row , int column ) { String checkboxLocator = getXPathBase ( ) + "tr[" + row + "]/td[" + column + "]/input" ; CheckBox cb = new CheckBox ( checkboxLocator ) ; cb . uncheck ( ) ; }
Untick a checkbox in a cell of a table indicated by the input row and column indices .
37,197
protected void process ( HttpServletRequest request , HttpServletResponse response ) throws IOException { boolean doStatusQuery = request . getParameter ( PING_NODES ) != null ; String acceptHeader = request . getHeader ( "Accept" ) ; if ( acceptHeader != null && acceptHeader . equalsIgnoreCase ( "application/json" ) ) { ServletHelper . respondAsJsonWithHttpStatus ( response , getProxyInfo ( doStatusQuery ) , HttpServletResponse . SC_OK ) ; } else { ServletHelper . respondAsHtmlUsingJsonAndTemplateWithHttpStatus ( response , getProxyInfo ( doStatusQuery ) , RESOURCE_PAGE_FILE , HttpServletResponse . SC_OK ) ; } }
This method gets all the nodes which are connected to the grid machine from the Registry and displays them in html page .
37,198
public Object [ ] [ ] getDataByKeys ( String [ ] keys ) { logger . entering ( Arrays . toString ( keys ) ) ; Object [ ] [ ] obj = new Object [ keys . length ] [ 1 ] ; for ( int i = 0 ; i < keys . length ; i ++ ) { obj [ i ] [ 0 ] = getSingleExcelRow ( getObject ( ) , keys [ i ] , true ) ; } logger . exiting ( ( Object [ ] ) obj ) ; return obj ; }
This function will use the input string representing the keys to collect and return the correct excel sheet data rows as two dimensional object to be used as TestNG DataProvider .
37,199
public Iterator < Object [ ] > getDataByFilter ( DataProviderFilter dataFilter ) { logger . entering ( dataFilter ) ; List < Object [ ] > objs = new ArrayList < > ( ) ; Field [ ] fields = resource . getCls ( ) . getDeclaredFields ( ) ; List < Row > rowToBeRead = excelReader . getAllExcelRows ( resource . getCls ( ) . getSimpleName ( ) , false ) ; List < String > excelHeaderRow = getHeaderRowContents ( resource . getCls ( ) . getSimpleName ( ) , fields . length ) ; for ( Row row : rowToBeRead ) { List < String > excelRowData = excelReader . getRowContents ( row , fields . length ) ; Map < String , String > headerRowDataMap = prepareHeaderRowDataMap ( excelHeaderRow , excelRowData ) ; if ( excelRowData . size ( ) != 0 ) { try { Object temp = prepareObject ( getObject ( ) , fields , excelRowData , headerRowDataMap ) ; if ( dataFilter . filter ( temp ) ) { objs . add ( new Object [ ] { temp } ) ; } } catch ( IllegalAccessException e ) { throw new DataProviderException ( "Unable to create instance of type '" + resource . getCls ( ) . getName ( ) + "'" , e ) ; } } } logger . exiting ( objs . iterator ( ) ) ; return objs . iterator ( ) ; }
Gets data from Excel sheet by applying the given filter .