idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
37,200
protected Object getSingleExcelRow ( Object userObj , String key , boolean isExternalCall ) { logger . entering ( new Object [ ] { userObj , key , isExternalCall } ) ; Class < ? > cls ; try { cls = Class . forName ( userObj . getClass ( ) . getName ( ) ) ; } catch ( ClassNotFoundException e ) { throw new DataProviderException ( "Unable to find class of type + '" + userObj . getClass ( ) . getName ( ) + "'" , e ) ; } int rowIndex = excelReader . getRowIndex ( cls . getSimpleName ( ) , key ) ; if ( rowIndex == - 1 ) { throw new DataProviderException ( "Row with key '" + key + "' is not found" ) ; } Object object = getSingleExcelRow ( userObj , rowIndex , isExternalCall ) ; logger . exiting ( object ) ; return object ; }
This method fetches a specific row from an excel sheet which can be identified using a key and returns the data as an Object which can be cast back into the user s actual data type .
37,201
private void setValueForArrayType ( DataMemberInformation memberInfo ) throws IllegalAccessException , ArrayIndexOutOfBoundsException , IllegalArgumentException , InstantiationException { logger . entering ( memberInfo ) ; Field eachField = memberInfo . getField ( ) ; Object objectToSetDataInto = memberInfo . getObjectToSetDataInto ( ) ; String data = memberInfo . getDataToUse ( ) ; Class < ? > eachFieldType = eachField . getType ( ) ; String [ ] arrayData = data . split ( "," ) ; Object arrayObject ; if ( ReflectionUtils . isPrimitiveArray ( eachFieldType ) ) { arrayObject = ReflectionUtils . instantiatePrimitiveArray ( eachFieldType , arrayData ) ; eachField . set ( objectToSetDataInto , arrayObject ) ; logger . exiting ( ) ; return ; } if ( ReflectionUtils . isWrapperArray ( eachFieldType ) || ReflectionUtils . hasOneArgStringConstructor ( eachFieldType . getComponentType ( ) ) ) { arrayObject = ReflectionUtils . instantiateWrapperArray ( eachFieldType , arrayData ) ; eachField . set ( objectToSetDataInto , arrayObject ) ; logger . exiting ( ) ; return ; } DefaultCustomType customType = fetchMatchingCustomType ( eachFieldType ) ; if ( customType != null ) { arrayObject = ReflectionUtils . instantiateDefaultCustomTypeArray ( customType , arrayData ) ; eachField . set ( objectToSetDataInto , arrayObject ) ; logger . exiting ( ) ; return ; } arrayObject = Array . newInstance ( eachFieldType . getComponentType ( ) , arrayData . length ) ; for ( int counter = 0 ; counter < arrayData . length ; counter ++ ) { Array . set ( arrayObject , counter , getSingleExcelRow ( eachFieldType . getComponentType ( ) . newInstance ( ) , arrayData [ counter ] . trim ( ) , true ) ) ; } eachField . set ( objectToSetDataInto , arrayObject ) ; logger . exiting ( ) ; }
A utility method that setups up data members which are arrays .
37,202
private void setValueForNonArrayType ( DataMemberInformation memberInfo ) throws IllegalAccessException , InstantiationException , IllegalArgumentException , InvocationTargetException , NoSuchMethodException , SecurityException { logger . entering ( memberInfo ) ; Field eachField = memberInfo . getField ( ) ; Class < ? > eachFieldType = eachField . getType ( ) ; Object objectToSetDataInto = memberInfo . getObjectToSetDataInto ( ) ; Object userProvidedObject = memberInfo . getUserProvidedObject ( ) ; String data = memberInfo . getDataToUse ( ) ; boolean isPrimitive = eachFieldType . isPrimitive ( ) ; if ( isPrimitive ) { eachField . set ( objectToSetDataInto , ReflectionUtils . instantiatePrimitiveObject ( eachFieldType , userProvidedObject , data ) ) ; logger . exiting ( ) ; return ; } if ( ClassUtils . isPrimitiveWrapper ( eachFieldType ) ) { eachField . set ( objectToSetDataInto , ReflectionUtils . instantiateWrapperObject ( eachFieldType , userProvidedObject , data ) ) ; logger . exiting ( ) ; return ; } if ( ReflectionUtils . hasOneArgStringConstructor ( eachFieldType ) ) { Object objToSet = eachFieldType . getConstructor ( new Class < ? > [ ] { String . class } ) . newInstance ( data ) ; eachField . set ( objectToSetDataInto , objToSet ) ; logger . exiting ( ) ; return ; } DefaultCustomType customType = fetchMatchingCustomType ( eachFieldType ) ; if ( customType != null ) { eachField . set ( objectToSetDataInto , customType . instantiateObject ( data ) ) ; logger . exiting ( ) ; return ; } eachField . set ( objectToSetDataInto , getSingleExcelRow ( eachFieldType . newInstance ( ) , data , true ) ) ; logger . exiting ( ) ; }
A utility method that setups up data members which are NOT arrays .
37,203
public List < String > getHeaderRowContents ( String sheetName , int size ) { return excelReader . getHeaderRowContents ( sheetName , size ) ; }
Utility to get the header row contents of the excel sheet
37,204
public int getWidth ( ) { try { return ( ( RemoteWebElement ) getElement ( ) ) . getSize ( ) . width ; } catch ( NumberFormatException e ) { throw new WebElementException ( "Attribute " + WIDTH + " not found for Image " + getLocator ( ) , e ) ; } }
This function is to get image s width .
37,205
public int getHeight ( ) { try { return ( ( RemoteWebElement ) getElement ( ) ) . getSize ( ) . height ; } catch ( NumberFormatException e ) { throw new WebElementException ( "Attribute " + HEIGHT + " not found for Image " + getLocator ( ) , e ) ; } }
This function is to get image s height .
37,206
void checkPort ( int port , String msg ) { StringBuilder message = new StringBuilder ( ) . append ( " " ) . append ( msg ) ; String portInUseError = String . format ( "Port %d is already in use. Please shutdown the service " + "listening on this port or configure a different port%s." , port , message ) ; boolean free = false ; try { free = PortProber . pollPort ( port ) ; } catch ( RuntimeException e ) { throw new IllegalArgumentException ( portInUseError , e ) ; } finally { if ( ! free ) { throw new IllegalArgumentException ( portInUseError ) ; } } }
Check the port availability
37,207
public Object [ ] [ ] getDataByIndex ( String indexes ) throws IOException , DataProviderException { logger . entering ( indexes ) ; int [ ] arrayIndex = DataProviderHelper . parseIndexString ( indexes ) ; Object [ ] [ ] yamlObjRequested = getDataByIndex ( arrayIndex ) ; logger . exiting ( ( Object [ ] ) yamlObjRequested ) ; return yamlObjRequested ; }
Gets yaml data for requested indexes .
37,208
public void selectByValue ( String value ) { getDispatcher ( ) . beforeSelect ( this , value ) ; new Select ( getElement ( ) ) . selectByValue ( value ) ; if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIActions ( UIActions . SELECTED , value ) ; } getDispatcher ( ) . afterSelect ( this , value ) ; }
Select all options that have a value matching the argument .
37,209
public void selectByLabel ( String label ) { getDispatcher ( ) . beforeSelect ( this , label ) ; new Select ( getElement ( ) ) . selectByVisibleText ( label ) ; if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIActions ( UIActions . SELECTED , label ) ; } getDispatcher ( ) . afterSelect ( this , label ) ; }
Select all options that display text matching the argument .
37,210
public void selectByValue ( String [ ] values ) { for ( int i = 0 ; i < values . length ; i ++ ) { selectByValue ( values [ i ] ) ; } }
Select all options that have a value matching any arguments .
37,211
public void selectByLabel ( String [ ] labels ) { for ( int i = 0 ; i < labels . length ; i ++ ) { selectByLabel ( labels [ i ] ) ; } }
Select all options that display text matching any arguments .
37,212
public void selectByIndex ( String [ ] indexes ) { for ( int i = 0 ; i < indexes . length ; i ++ ) { selectByIndex ( Integer . parseInt ( indexes [ i ] ) ) ; } }
Select the option at the given indexes . This is done by examing the index attribute of an element and not merely by counting .
37,213
public String [ ] getSelectOptions ( ) { List < WebElement > optionList = getElement ( ) . findElements ( By . tagName ( "option" ) ) ; String [ ] optionArray = new String [ optionList . size ( ) ] ; for ( int i = 0 ; i < optionList . size ( ) ; i ++ ) { optionArray [ i ] = optionList . get ( i ) . getText ( ) ; } return optionArray ; }
Returns all options currently selected .
37,214
public String getSelectedLabel ( ) { List < WebElement > options = getElement ( ) . findElements ( By . tagName ( "option" ) ) ; for ( WebElement option : options ) { if ( option . isSelected ( ) ) { return option . getText ( ) ; } } return null ; }
Get a single selected label . If multiple options are selected then the first one is returned .
37,215
public String getSelectedValue ( ) { List < WebElement > options = getElement ( ) . findElements ( By . tagName ( "option" ) ) ; for ( WebElement option : options ) { if ( option . isSelected ( ) ) { return option . getAttribute ( "value" ) ; } } return null ; }
Get a single selected value . If multiple options are selected then the first one is returned .
37,216
public String [ ] getSelectedLabels ( ) { List < WebElement > options = getElement ( ) . findElements ( By . tagName ( "option" ) ) ; List < String > selected = new ArrayList < String > ( ) ; for ( WebElement option : options ) { if ( option . isSelected ( ) ) { selected . add ( option . getText ( ) ) ; } } return ( String [ ] ) selected . toArray ( new String [ selected . size ( ) ] ) ; }
Gets multiple selected labels .
37,217
public String [ ] getSelectedValues ( ) { List < WebElement > options = getElement ( ) . findElements ( By . tagName ( "option" ) ) ; List < String > selected = new ArrayList < String > ( ) ; for ( WebElement option : options ) { if ( option . isSelected ( ) ) { selected . add ( option . getAttribute ( "value" ) ) ; } } return ( String [ ] ) selected . toArray ( new String [ selected . size ( ) ] ) ; }
Gets multiple selected values .
37,218
public String [ ] getContentLabel ( ) { List < WebElement > options = getElement ( ) . findElements ( By . tagName ( "option" ) ) ; List < String > contents = new ArrayList < String > ( ) ; for ( WebElement option : options ) { contents . add ( option . getText ( ) ) ; } return ( String [ ] ) contents . toArray ( new String [ contents . size ( ) ] ) ; }
Get all labels whether they are selected or not .
37,219
public String [ ] getContentValue ( ) { List < WebElement > options = getElement ( ) . findElements ( By . tagName ( "option" ) ) ; List < String > contents = new ArrayList < String > ( ) ; for ( WebElement option : options ) { contents . add ( option . getAttribute ( "value" ) ) ; } return ( String [ ] ) contents . toArray ( new String [ contents . size ( ) ] ) ; }
Get all values whether they are selected or not .
37,220
public void deselectByValue ( String value ) { getDispatcher ( ) . beforeDeselect ( this , value ) ; new Select ( getElement ( ) ) . deselectByValue ( value ) ; if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIActions ( UIActions . CLEARED , value ) ; } getDispatcher ( ) . afterDeselect ( this , value ) ; }
Deselect all options that have a value matching the argument .
37,221
public void deselectByIndex ( int index ) { getDispatcher ( ) . beforeDeselect ( this , index ) ; new Select ( getElement ( ) ) . deselectByIndex ( index ) ; if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIActions ( UIActions . CLEARED , Integer . toString ( index ) ) ; } getDispatcher ( ) . afterDeselect ( this , index ) ; }
Deselect the option at the given index . This is done by examing the index attribute of an element and not merely by counting .
37,222
public void deselectByLabel ( String label ) { getDispatcher ( ) . beforeDeselect ( this , label ) ; new Select ( getElement ( ) ) . deselectByVisibleText ( label ) ; if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIActions ( UIActions . CLEARED , label ) ; } getDispatcher ( ) . afterDeselect ( this , label ) ; }
Deselect all options that display text matching the argument .
37,223
public void click ( String locator ) { getDispatcher ( ) . beforeClick ( this , locator ) ; getElement ( ) . click ( ) ; validatePresenceOfAlert ( ) ; if ( Config . getBoolConfigProperty ( ConfigProperty . ENABLE_GUI_LOGGING ) ) { logUIAction ( UIActions . CLICKED ) ; } WebDriverWaitUtils . waitUntilElementIsPresent ( locator ) ; getDispatcher ( ) . afterClick ( this , locator ) ; }
The RadioButton click function and wait for object to load
37,224
private void parseResults ( ) { logger . entering ( ) ; if ( result . getStatus ( ) == ITestResult . SUCCESS ) { this . status = "Passed" ; } else if ( result . getStatus ( ) == ITestResult . FAILURE ) { this . status = "Failed" ; } else if ( result . getStatus ( ) == ITestResult . SKIP ) { this . status = "Skipped" ; } else if ( result . getStatus ( ) == ITestResult . STARTED ) { this . status = "Running" ; } Calendar c = Calendar . getInstance ( ) ; c . setTimeInMillis ( result . getStartMillis ( ) ) ; this . startTime = ReporterDateFormatter . getISO8601String ( c . getTime ( ) ) ; c . setTimeInMillis ( result . getEndMillis ( ) ) ; this . endTime = ReporterDateFormatter . getISO8601String ( c . getTime ( ) ) ; if ( result . getMethod ( ) . getDescription ( ) != null ) { this . description = result . getMethod ( ) . getDescription ( ) ; } if ( result . getThrowable ( ) != null ) { this . exception = result . getThrowable ( ) . getClass ( ) . toString ( ) + ":" + result . getThrowable ( ) . getLocalizedMessage ( ) ; this . stacktrace = getStackTraceInfo ( result . getThrowable ( ) ) ; } loadMethodInfo ( result ) ; logger . exiting ( ) ; }
Parse the test results and convert to the MethodInfo fields
37,225
public String getStackTraceInfo ( Throwable aThrowable ) { final Writer localWriter = new StringWriter ( ) ; final PrintWriter printWriter = new PrintWriter ( localWriter ) ; aThrowable . printStackTrace ( printWriter ) ; return localWriter . toString ( ) ; }
Used to return StackTrace of an Exception as String .
37,226
public String toJson ( ) { logger . entering ( ) ; parseResults ( ) ; Gson gson = new GsonBuilder ( ) . setPrettyPrinting ( ) . create ( ) ; String json = gson . toJson ( this ) ; logger . exiting ( json ) ; return json ; }
This method generate the JSON string for the instance . GSON builder helps to build JSON string and it will exclude the static and transient variable during generation .
37,227
public static synchronized ConfigParser setConfigFile ( String file ) { LOGGER . entering ( file ) ; if ( configuration == null ) { configFile = file ; } LOGGER . exiting ( parser . toString ( ) ) ; return parser ; }
Set the config file
37,228
public List < String > getRowContents ( Row row , int size ) { logger . entering ( new Object [ ] { row , size } ) ; List < String > rowData = new ArrayList < String > ( ) ; if ( row != null ) { for ( int i = 1 ; i <= size ; i ++ ) { String data = null ; if ( row . getCell ( i ) != null ) { data = row . getCell ( i ) . toString ( ) ; } rowData . add ( data ) ; } } logger . exiting ( rowData ) ; return rowData ; }
Return the row contents of the specified row in a list of string format .
37,229
public int getRowIndex ( String sheetName , String key ) { logger . entering ( new Object [ ] { sheetName , key } ) ; int index = - 1 ; Sheet sheet = fetchSheet ( sheetName ) ; int rowCount = sheet . getPhysicalNumberOfRows ( ) ; for ( int i = 0 ; i < rowCount ; i ++ ) { Row row = sheet . getRow ( i ) ; if ( row == null ) { continue ; } String cellValue = row . getCell ( 0 ) . toString ( ) ; if ( ( key . compareTo ( cellValue ) == 0 ) && ( ! cellValue . contains ( "#" ) ) ) { index = i ; break ; } } logger . exiting ( index ) ; return index ; }
Search for the input key from the specified sheet name and return the index position of the row that contained the key
37,230
static List < String > getExecutableNames ( ) { List < String > executableNames = new ArrayList < > ( ) ; if ( Platform . getCurrent ( ) . is ( Platform . WINDOWS ) ) { Collections . addAll ( executableNames , ProcessNames . PHANTOMJS . getWindowsImageName ( ) , ProcessNames . CHROMEDRIVER . getWindowsImageName ( ) , ProcessNames . IEDRIVER . getWindowsImageName ( ) , ProcessNames . EDGEDRIVER . getWindowsImageName ( ) , ProcessNames . GECKODRIVER . getWindowsImageName ( ) ) ; } else { Collections . addAll ( executableNames , ProcessNames . PHANTOMJS . getUnixImageName ( ) , ProcessNames . CHROMEDRIVER . getUnixImageName ( ) , ProcessNames . GECKODRIVER . getUnixImageName ( ) ) ; } return executableNames ; }
Utility method to return the executable names for the specified platform .
37,231
static String extractMsi ( String msiFile ) { LOGGER . entering ( msiFile ) ; Process process = null ; String exeFilePath = null ; boolean isMsiExtracted = true ; try { process = Runtime . getRuntime ( ) . exec ( new String [ ] { "msiexec" , "/a" , msiFile , "/qn" , "TARGETDIR=" + SeLionConstants . SELION_HOME_DIR } ) ; process . waitFor ( ) ; } catch ( IOException e ) { LOGGER . log ( Level . SEVERE , "Could not find file " + msiFile , e ) ; isMsiExtracted = false ; } catch ( InterruptedException e ) { LOGGER . log ( Level . SEVERE , "Exception waiting for msiexec to be finished" , e ) ; isMsiExtracted = false ; } finally { process . destroy ( ) ; } if ( isMsiExtracted ) { moveExeFileToSeLionHomeAndDeleteExtras ( ) ; exeFilePath = FileUtils . getFile ( SeLionConstants . SELION_HOME_DIR + SeLionConstants . EDGE_DRIVER ) . getAbsolutePath ( ) ; } LOGGER . exiting ( exeFilePath ) ; return exeFilePath ; }
Installs MicrosoftWebDriver . msi file as administrator in SELION_HOME_DIR and also deletes unwanted file and directory created by Msiexec .
37,232
public RemoteWebDriver createDriver ( MobileNodeType nodeType , WebDriverPlatform platform , CommandExecutor command , URL url , Capabilities caps ) { if ( mobileProviders . containsKey ( nodeType ) ) { logger . log ( Level . FINE , "Found mobile driver provider that supports " + nodeType ) ; return mobileProviders . get ( nodeType ) . createDriver ( platform , command , url , caps ) ; } logger . severe ( "Did not found a mobile driver provider that supports " + nodeType ) ; return null ; }
Creates a new RemoteWebDriver instance from the first MobileProvider that supports the specified nodeType .
37,233
public static void waitUntilElementIsClickable ( final String elementLocator ) { logger . entering ( elementLocator ) ; By by = HtmlElementUtils . resolveByType ( elementLocator ) ; ExpectedCondition < WebElement > condition = ExpectedConditions . elementToBeClickable ( by ) ; waitForCondition ( condition ) ; logger . exiting ( ) ; }
Waits until element is cickable .
37,234
public static void waitUntilElementIsInvisible ( final String elementLocator ) { logger . entering ( elementLocator ) ; By by = HtmlElementUtils . resolveByType ( elementLocator ) ; ExpectedCondition < Boolean > condition = ExpectedConditions . invisibilityOfElementLocated ( by ) ; waitForCondition ( condition ) ; logger . exiting ( ) ; }
Waits until element is either invisible or not present on the DOM .
37,235
public static void waitUntilElementIsPresent ( final String elementLocator ) { logger . entering ( elementLocator ) ; By by = HtmlElementUtils . resolveByType ( elementLocator ) ; ExpectedCondition < WebElement > condition = ExpectedConditions . presenceOfElementLocated ( by ) ; waitForCondition ( condition ) ; logger . exiting ( ) ; }
Waits until element is present on the DOM of a page . This does not necessarily mean that the element is visible .
37,236
public static void waitUntilElementIsVisible ( final String elementLocator ) { logger . entering ( elementLocator ) ; By by = HtmlElementUtils . resolveByType ( elementLocator ) ; ExpectedCondition < WebElement > condition = ExpectedConditions . visibilityOfElementLocated ( by ) ; waitForCondition ( condition ) ; logger . exiting ( ) ; }
Waits until element is present on the DOM of a page and visible . Visibility means that the element is not only displayed but also has a height and width that is greater than 0 .
37,237
public static void waitUntilPageTitleContains ( final String pageTitle ) { logger . entering ( pageTitle ) ; Preconditions . checkArgument ( StringUtils . isNotEmpty ( pageTitle ) , "Expected Page title cannot be null (or) empty." ) ; ExpectedCondition < Boolean > condition = ExpectedConditions . titleContains ( pageTitle ) ; waitForCondition ( condition ) ; logger . exiting ( ) ; }
Waits until the current page s title contains a case - sensitive substring of the given title .
37,238
public static void waitUntilTextPresent ( final String searchString ) { logger . entering ( searchString ) ; Preconditions . checkArgument ( StringUtils . isNotEmpty ( searchString ) , "Search string cannot be null (or) empty." ) ; ExpectedCondition < Boolean > conditionToCheck = new ExpectedCondition < Boolean > ( ) { public Boolean apply ( WebDriver input ) { return getTextFromBody ( ) . contains ( searchString ) ; } } ; waitForCondition ( conditionToCheck ) ; logger . exiting ( ) ; }
Waits until text appears anywhere within the current page s &lt ; body&gt ; tag .
37,239
public static void waitUntilAllElementsArePresent ( final String ... locators ) { logger . entering ( new Object [ ] { Arrays . toString ( locators ) } ) ; Preconditions . checkArgument ( locators != null , "Please provide a valid set of locators." ) ; for ( String eachLocator : locators ) { waitUntilElementIsPresent ( eachLocator ) ; } logger . exiting ( ) ; }
Waits until both two elements appear at the page Waits until all the elements are present on the DOM of a page . This does not necessarily mean that the element is visible .
37,240
public static boolean changePassword ( String userName , String newPassword ) { LOGGER . entering ( userName , newPassword . replaceAll ( "." , "*" ) ) ; boolean changeSucceeded = false ; File authFile = new File ( AUTH_FILE_LOCATION ) ; try { authFile . delete ( ) ; authFile . createNewFile ( ) ; createAuthFile ( authFile , userName , newPassword ) ; changeSucceeded = true ; } catch ( Exception e ) { changeSucceeded = false ; } LOGGER . exiting ( changeSucceeded ) ; return changeSucceeded ; }
Changes the password for the given user to the new password
37,241
protected void parse ( String json ) { logger . entering ( json ) ; try { Gson gson = new Gson ( ) ; BaseLog baseLog = gson . fromJson ( json , this . getClass ( ) ) ; this . msg = baseLog . msg ; this . screen = baseLog . screen ; this . location = baseLog . location ; this . href = baseLog . href ; } catch ( JsonSyntaxException e ) { this . msg = json ; } logger . exiting ( ) ; }
Parsing the JSON string using Gson library .
37,242
public void shutdown ( ) throws Exception { if ( type == null ) { return ; } if ( type instanceof Hub ) { ( ( Hub ) type ) . stop ( ) ; } if ( type instanceof SelfRegisteringRemote ) { ( ( SelfRegisteringRemote ) type ) . stopRemoteServer ( ) ; } if ( type instanceof SeleniumServer ) { ( ( SeleniumServer ) type ) . stop ( ) ; } LOGGER . info ( "Selenium is shut down" ) ; }
Shutdown the instance
37,243
public void boot ( String [ ] args ) throws Exception { SeLionStandaloneConfiguration configuration = new SeLionStandaloneConfiguration ( ) ; JCommander commander = new JCommander ( ) ; commander . setAcceptUnknownOptions ( true ) ; commander . addObject ( configuration ) ; commander . parse ( args ) ; LauncherConfiguration lc = configuration . processLauncherConfiguration ; ConfigParser . setConfigFile ( lc . getSeLionConfig ( ) ) ; StandaloneConfiguration sc = configuration . standaloneConfiguration ; String role = sc . role . toLowerCase ( ) ; GridRole gridRole = GridRole . get ( role ) ; if ( launchers . containsKey ( gridRole ) ) { SeLionGridItemLauncher launcher = launchers . get ( gridRole ) ; launcher . setConfiguration ( args ) ; if ( launcher . versionRequested ) { System . out . println ( ident ( ) ) ; return ; } if ( launcher . helpRequested ) { launcher . printUsage ( ) ; return ; } configureLogging ( sc ) ; logEnvironment ( ) ; LOGGER . info ( ident ( ) ) ; launcher . launch ( ) ; type = launcher . type ; } else { printInfoAboutRoles ( role ) ; return ; } }
Boot the instance base on the arguments supplied
37,244
public void dragToValue ( double value ) { logger . entering ( value ) ; WebElement webElement = findElement ( locator ) ; Point currentLocation = webElement . getLocation ( ) ; Dimension elementSize = webElement . getSize ( ) ; int x = currentLocation . getX ( ) ; int y = currentLocation . getY ( ) + ( elementSize . getHeight ( ) / 2 ) ; int pos = Double . valueOf ( value * ( elementSize . getWidth ( ) ) ) . intValue ( ) ; int endX = x + pos ; if ( value >= VALUE_UPPER_LIMIT ) { endX -- ; } if ( endX < MIN_END_X ) { endX = MIN_END_X ; } initBridgeDriver ( ) ; MobileNodeType mobileType = Grid . getMobileTestSession ( ) . getMobileNodeType ( ) ; if ( mobileType . equals ( MobileNodeType . APPIUM ) ) { driver . swipe ( 1 , endX , y , 100 ) ; } else { driver . swipe ( x , y , endX , y ) ; } logger . exiting ( ) ; }
it is not accurate and is best to used only for setting value to 0 or 1 otherwise the result is close to parameter
37,245
public void exiting ( Object object ) { if ( ! getLogger ( ) . isLoggable ( Level . FINER ) ) { return ; } FrameInfo fi = getLoggingFrame ( ) ; getLogger ( ) . exiting ( fi . className , fi . methodName , object ) ; }
Function exit log convenience method .
37,246
private static FrameInfo getLoggingFrame ( ) { StackTraceElement [ ] stackTrace = Thread . currentThread ( ) . getStackTrace ( ) ; StackTraceElement loggingFrame = null ; for ( int ix = 1 ; ix < stackTrace . length ; ix ++ ) { loggingFrame = stackTrace [ ix ] ; if ( loggingFrame . getClassName ( ) . contains ( CLASS_NAME ) ) { for ( int iy = ix ; iy < stackTrace . length ; iy ++ ) { loggingFrame = stackTrace [ iy ] ; if ( ! loggingFrame . getClassName ( ) . contains ( CLASS_NAME ) ) { break ; } } break ; } } return new FrameInfo ( loggingFrame . getClassName ( ) , loggingFrame . getMethodName ( ) ) ; }
Calculate the logging frame s class name and method name .
37,247
public void onStart ( ISuite suite ) { logger . entering ( suite ) ; if ( ListenerManager . isCurrentMethodSkipped ( this ) ) { logger . exiting ( ListenerManager . THREAD_EXCLUSION_MSG ) ; return ; } Config . initConfig ( suite ) ; ConfigSummaryData . initConfigSummary ( ) ; ReporterConfigMetadata . initReporterMetadata ( ) ; RuntimeMXBean runtime = ManagementFactory . getRuntimeMXBean ( ) ; String jdkInfo = runtime . getVmName ( ) + " from " + runtime . getSpecVendor ( ) + " ver. " + System . getProperty ( "java.version" ) ; logger . info ( "JDK Information: " + jdkInfo ) ; logger . exiting ( ) ; }
Initiate config on suite start
37,248
public static String filterOutputDirectory ( String base , String suiteName ) { logger . entering ( new Object [ ] { base , suiteName } ) ; int index = base . lastIndexOf ( suiteName ) ; String outputFolderWithoutName = base . substring ( 0 , index ) ; logger . exiting ( outputFolderWithoutName + File . separator ) ; return outputFolderWithoutName + File . separator ; }
Generates and returns output directory string path
37,249
public void onFinish ( ISuite suite ) { logger . entering ( suite ) ; if ( ListenerManager . isCurrentMethodSkipped ( this ) ) { logger . exiting ( ListenerManager . THREAD_EXCLUSION_MSG ) ; return ; } LocalGridManager . shutDownHub ( ) ; logger . exiting ( ) ; }
Closes selenium session when suite finished to run
37,250
public void onStart ( ITestContext context ) { logger . entering ( context ) ; if ( ListenerManager . isCurrentMethodSkipped ( this ) ) { logger . exiting ( ListenerManager . THREAD_EXCLUSION_MSG ) ; return ; } String testName = context . getCurrentXmlTest ( ) . getName ( ) ; ConfigSummaryData . initLocalConfigSummary ( testName ) ; invokeInitializersBasedOnPriority ( context ) ; ConfigManager . printConfiguration ( testName ) ; ISuite suite = context . getSuite ( ) ; if ( ! suite . getParallel ( ) . equals ( "false" ) && logger . isLoggable ( Level . FINE ) ) { logger . log ( Level . FINE , "Parallel suite execution. Updating SeLion local config for Test, " + context . getCurrentXmlTest ( ) . getName ( ) ) ; } String base = suite . getOutputDirectory ( ) ; String suiteName = suite . getName ( ) ; String rootFolder = filterOutputDirectory ( base , suiteName ) ; SeLionReporter . setTestNGOutputFolder ( rootFolder ) ; SeLionReporter . init ( ) ; logger . exiting ( ) ; }
On start each suite initialize config object and report object
37,251
private void invokeInitializersBasedOnPriority ( ITestContext context ) { ServiceLoader < Initializer > serviceLoader = ServiceLoader . load ( Initializer . class ) ; List < AbstractConfigInitializer > loader = new ArrayList < AbstractConfigInitializer > ( ) ; for ( Initializer l : serviceLoader ) { loader . add ( ( AbstractConfigInitializer ) l ) ; } Collections . sort ( loader ) ; for ( AbstractConfigInitializer temp : loader ) { temp . initialize ( context ) ; } }
This method facilitates initialization of all configurations from the current project as well as downstream consumers .
37,252
public boolean filter ( Object data ) { logger . entering ( data ) ; String [ ] keyValues = filterKeyValues . split ( "," ) ; String tempKey = null ; Field field ; try { field = data . getClass ( ) . getDeclaredField ( filterKeyName ) ; field . setAccessible ( true ) ; for ( String keyValue : keyValues ) { tempKey = keyValue ; if ( field . get ( data ) != null && field . get ( data ) . toString ( ) . trim ( ) . equals ( keyValue ) ) { logger . exiting ( true ) ; return true ; } } } catch ( NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e ) { throw new DataProviderException ( "Row with key '" + tempKey + "' is not found for given filter key '" + filterKeyName + "'" , e ) ; } logger . exiting ( false ) ; return false ; }
This function identifies whether the object falls in the filtering criteria or not based on the filterKeyName and its corresponding filterKeyValues .
37,253
public static void isValidXpath ( String locator ) { logger . entering ( locator ) ; Preconditions . checkArgument ( StringUtils . isNotBlank ( locator ) , INVALID_LOCATOR_ERR_MSG ) ; if ( locator . startsWith ( "xpath=/" ) || locator . startsWith ( "/" ) ) { throw new UnsupportedOperationException ( "Use xpath dot notation to search for Container descendant elements. Example: \".//myLocator\". " ) ; } logger . exiting ( ) ; }
Validates a child locator to have the xpath dot notation .
37,254
public static boolean isElementPresent ( String locator ) { logger . entering ( locator ) ; boolean flag = false ; try { flag = HtmlElementUtils . locateElement ( locator ) != null ; } catch ( NoSuchElementException e ) { } logger . exiting ( flag ) ; return flag ; }
Checks if the provided element is present on the page based on the locator provided
37,255
String getSubFolderName ( ) { if ( subFolderName == null ) { String relPath = getAbsolutePath ( ) . replace ( REPO_ABSOLUTE_PATH , "" ) ; relPath = relPath . substring ( relPath . indexOf ( SystemUtils . FILE_SEPARATOR ) + 1 ) ; String [ ] parts = relPath . split ( "[\\\\/]" ) ; subFolderName = ( ( parts . length < 3 ) || ( StringUtils . isBlank ( parts [ 1 ] ) ) ) ? "" : parts [ 1 ] ; } return subFolderName ; }
Returns the optional sub folder for the artifact
37,256
private CommandLine createCommandForChildProcess ( ) throws IOException { LOGGER . entering ( ) ; CommandLine cmdLine = CommandLine . parse ( "appium" ) ; cmdLine . addArguments ( getProgramArguments ( ) ) ; LOGGER . exiting ( cmdLine . toString ( ) ) ; return cmdLine ; }
This method loads the default arguments required to spawn appium
37,257
public MgcpSignal provide ( String pkg , String signal , int requestId , NotifiedEntity notifiedEntity , Map < String , String > parameters , MgcpEndpoint endpoint ) throws UnrecognizedMgcpPackageException , UnsupportedMgcpSignalException { switch ( pkg ) { case AudioPackage . PACKAGE_NAME : return provideAudioSignal ( signal , requestId , notifiedEntity , parameters , endpoint , this . executor ) ; default : throw new UnrecognizedMgcpPackageException ( "Unrecognized package " + pkg ) ; } }
Provides an MGCP Signal to be executed .
37,258
public boolean contains ( Format format ) { for ( Format f : list ) { if ( f . matches ( format ) ) return true ; } return false ; }
Checks that collection has specified format .
37,259
public void intersection ( Formats other , Formats intersection ) { intersection . list . clear ( ) ; for ( Format f1 : list ) { for ( Format f2 : other . list ) { if ( f1 . matches ( f2 ) ) intersection . list . add ( f2 ) ; } } }
Find the intersection between this collection and other
37,260
public void add ( Task task ) { synchronized ( LOCK ) { task . setListener ( this ) ; this . task [ wi ] = task ; wi ++ ; } }
Adds task to the chain .
37,261
private void continueExecution ( ) { i ++ ; if ( i < task . length && task [ i ] != null ) { scheduler . submit ( task [ i ] ) ; } else if ( listener != null ) { listener . onTermination ( ) ; } }
Submits next task for the execution
37,262
public char getDataLength ( ) { char length = 0 ; List < StunAttribute > attrs = getAttributes ( ) ; for ( StunAttribute att : attrs ) { int attLen = att . getDataLength ( ) + StunAttribute . HEADER_LENGTH ; attLen += ( 4 - ( attLen % 4 ) ) % 4 ; length += attLen ; } return length ; }
Returns the length of this message s body .
37,263
public void addAttribute ( StunAttribute attribute ) throws IllegalArgumentException { if ( getAttributePresentity ( attribute . getAttributeType ( ) ) == N_A ) { throw new IllegalArgumentException ( "The attribute " + attribute . getName ( ) + " is not allowed in a " + getName ( ) ) ; } synchronized ( attributes ) { attributes . put ( attribute . getAttributeType ( ) , attribute ) ; } }
Adds the specified attribute to this message . If an attribute with that name was already added it would be replaced .
37,264
public void setTransactionID ( byte [ ] tranID ) throws StunException { if ( tranID == null || ( tranID . length != TRANSACTION_ID_LENGTH && tranID . length != RFC3489_TRANSACTION_ID_LENGTH ) ) throw new StunException ( StunException . ILLEGAL_ARGUMENT , "Invalid transaction id length" ) ; int tranIDLength = tranID . length ; this . transactionID = new byte [ tranIDLength ] ; System . arraycopy ( tranID , 0 , this . transactionID , 0 , tranIDLength ) ; }
Copies the specified tranID and sets it as this message s transactionID .
37,265
protected byte getAttributePresentity ( char attributeType ) { if ( ! rfc3489CompatibilityMode ) { return O ; } byte msgIndex = - 1 ; byte attributeIndex = - 1 ; switch ( messageType ) { case BINDING_REQUEST : msgIndex = BINDING_REQUEST_PRESENTITY_INDEX ; break ; case BINDING_SUCCESS_RESPONSE : msgIndex = BINDING_RESPONSE_PRESENTITY_INDEX ; break ; case BINDING_ERROR_RESPONSE : msgIndex = BINDING_ERROR_RESPONSE_PRESENTITY_INDEX ; break ; case SHARED_SECRET_REQUEST : msgIndex = SHARED_SECRET_REQUEST_PRESENTITY_INDEX ; break ; case SHARED_SECRET_RESPONSE : msgIndex = SHARED_SECRET_RESPONSE_PRESENTITY_INDEX ; break ; case SHARED_SECRET_ERROR_RESPONSE : msgIndex = SHARED_SECRET_ERROR_RESPONSE_PRESENTITY_INDEX ; break ; case ALLOCATE_REQUEST : msgIndex = ALLOCATE_REQUEST_PRESENTITY_INDEX ; break ; case REFRESH_REQUEST : msgIndex = REFRESH_REQUEST_PRESENTITY_INDEX ; break ; case CHANNELBIND_REQUEST : msgIndex = CHANNELBIND_REQUEST_PRESENTITY_INDEX ; break ; case SEND_INDICATION : msgIndex = SEND_INDICATION_PRESENTITY_INDEX ; break ; case DATA_INDICATION : msgIndex = DATA_INDICATION_PRESENTITY_INDEX ; break ; default : if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Attribute presentity not defined for STUN " + "message type: " + ( ( int ) messageType ) + ". Will assume optional." ) ; } return O ; } switch ( attributeType ) { case StunAttribute . MAPPED_ADDRESS : attributeIndex = MAPPED_ADDRESS_PRESENTITY_INDEX ; break ; case StunAttribute . RESPONSE_ADDRESS : attributeIndex = RESPONSE_ADDRESS_PRESENTITY_INDEX ; break ; case StunAttribute . CHANGE_REQUEST : attributeIndex = CHANGE_REQUEST_PRESENTITY_INDEX ; break ; case StunAttribute . SOURCE_ADDRESS : attributeIndex = SOURCE_ADDRESS_PRESENTITY_INDEX ; break ; case StunAttribute . CHANGED_ADDRESS : attributeIndex = CHANGED_ADDRESS_PRESENTITY_INDEX ; break ; case StunAttribute . USERNAME : attributeIndex = USERNAME_PRESENTITY_INDEX ; break ; case StunAttribute . PASSWORD : attributeIndex = PASSWORD_PRESENTITY_INDEX ; break ; case StunAttribute . MESSAGE_INTEGRITY : attributeIndex = MESSAGE_INTEGRITY_PRESENTITY_INDEX ; break ; case StunAttribute . ERROR_CODE : attributeIndex = ERROR_CODE_PRESENTITY_INDEX ; break ; case StunAttribute . UNKNOWN_ATTRIBUTES : attributeIndex = UNKNOWN_ATTRIBUTES_PRESENTITY_INDEX ; break ; case StunAttribute . REFLECTED_FROM : attributeIndex = REFLECTED_FROM_PRESENTITY_INDEX ; break ; case StunAttribute . XOR_MAPPED_ADDRESS : attributeIndex = XOR_MAPPED_ADDRESS_PRESENTITY_INDEX ; break ; case StunAttribute . XOR_ONLY : attributeIndex = XOR_ONLY_PRESENTITY_INDEX ; break ; case StunAttribute . SOFTWARE : attributeIndex = SOFTWARE_PRESENTITY_INDEX ; break ; case StunAttribute . ALTERNATE_SERVER : attributeIndex = ALTERNATE_SERVER_PRESENTITY_INDEX ; break ; case StunAttribute . REALM : attributeIndex = REALM_PRESENTITY_INDEX ; break ; case StunAttribute . NONCE : attributeIndex = NONCE_PRESENTITY_INDEX ; break ; case StunAttribute . FINGERPRINT : attributeIndex = FINGERPRINT_PRESENTITY_INDEX ; break ; case StunAttribute . CHANNEL_NUMBER : attributeIndex = CHANNEL_NUMBER_PRESENTITY_INDEX ; break ; case StunAttribute . LIFETIME : attributeIndex = LIFETIME_PRESENTITY_INDEX ; break ; case StunAttribute . XOR_PEER_ADDRESS : attributeIndex = XOR_PEER_ADDRESS_PRESENTITY_INDEX ; break ; case StunAttribute . DATA : attributeIndex = DATA_PRESENTITY_INDEX ; break ; case StunAttribute . XOR_RELAYED_ADDRESS : attributeIndex = XOR_RELAYED_ADDRESS_PRESENTITY_INDEX ; break ; case StunAttribute . EVEN_PORT : attributeIndex = EVEN_PORT_PRESENTITY_INDEX ; break ; case StunAttribute . REQUESTED_TRANSPORT : attributeIndex = REQUESTED_TRANSPORT_PRESENTITY_INDEX ; break ; case StunAttribute . DONT_FRAGMENT : attributeIndex = DONT_FRAGMENT_PRESENTITY_INDEX ; break ; case StunAttribute . RESERVATION_TOKEN : attributeIndex = RESERVATION_TOKEN_PRESENTITY_INDEX ; break ; default : attributeIndex = UNKNOWN_OPTIONAL_ATTRIBUTES_PRESENTITY_INDEX ; break ; } return attributePresentities [ attributeIndex ] [ msgIndex ] ; }
Returns whether an attribute could be present in this message .
37,266
public String getName ( ) { switch ( messageType ) { case ALLOCATE_REQUEST : return "ALLOCATE-REQUEST" ; case ALLOCATE_RESPONSE : return "ALLOCATE-RESPONSE" ; case ALLOCATE_ERROR_RESPONSE : return "ALLOCATE-ERROR-RESPONSE" ; case BINDING_REQUEST : return "BINDING-REQUEST" ; case BINDING_SUCCESS_RESPONSE : return "BINDING-RESPONSE" ; case BINDING_ERROR_RESPONSE : return "BINDING-ERROR-RESPONSE" ; case CREATEPERMISSION_REQUEST : return "CREATE-PERMISSION-REQUEST" ; case CREATEPERMISSION_RESPONSE : return "CREATE-PERMISSION-RESPONSE" ; case CREATEPERMISSION_ERROR_RESPONSE : return "CREATE-PERMISSION-ERROR-RESPONSE" ; case DATA_INDICATION : return "DATA-INDICATION" ; case REFRESH_REQUEST : return "REFRESH-REQUEST" ; case REFRESH_RESPONSE : return "REFRESH-RESPONSE" ; case REFRESH_ERROR_RESPONSE : return "REFRESH-ERROR-RESPONSE" ; case SEND_INDICATION : return "SEND-INDICATION" ; case SHARED_SECRET_REQUEST : return "SHARED-SECRET-REQUEST" ; case SHARED_SECRET_RESPONSE : return "SHARED-SECRET-RESPONSE" ; case SHARED_SECRET_ERROR_RESPONSE : return "SHARED-SECRET-ERROR-RESPONSE" ; default : return "UNKNOWN-MESSAGE" ; } }
Returns the human readable name of this message . Message names do not really matter from the protocol point of view . They are only used for debugging and readability .
37,267
public byte [ ] encode ( ) throws IllegalStateException { prepareForEncoding ( ) ; validateAttributePresentity ( ) ; final char dataLength = getDataLength ( ) ; byte binMsg [ ] = new byte [ HEADER_LENGTH + dataLength ] ; int offset = 0 ; binMsg [ offset ++ ] = ( byte ) ( getMessageType ( ) >> 8 ) ; binMsg [ offset ++ ] = ( byte ) ( getMessageType ( ) & 0xFF ) ; final int messageLengthOffset = offset ; offset += 2 ; byte tranID [ ] = getTransactionId ( ) ; if ( tranID . length == 12 ) { System . arraycopy ( MAGIC_COOKIE , 0 , binMsg , offset , 4 ) ; offset += 4 ; System . arraycopy ( tranID , 0 , binMsg , offset , TRANSACTION_ID_LENGTH ) ; offset += TRANSACTION_ID_LENGTH ; } else { System . arraycopy ( tranID , 0 , binMsg , offset , RFC3489_TRANSACTION_ID_LENGTH ) ; offset += RFC3489_TRANSACTION_ID_LENGTH ; } Vector < Map . Entry < Character , StunAttribute > > v = new Vector < Map . Entry < Character , StunAttribute > > ( ) ; Iterator < Map . Entry < Character , StunAttribute > > iter = null ; char dataLengthForContentDependentAttribute = 0 ; synchronized ( attributes ) { v . addAll ( attributes . entrySet ( ) ) ; } iter = v . iterator ( ) ; while ( iter . hasNext ( ) ) { StunAttribute attribute = iter . next ( ) . getValue ( ) ; int attributeLength = attribute . getDataLength ( ) + StunAttribute . HEADER_LENGTH ; attributeLength += ( 4 - attributeLength % 4 ) % 4 ; dataLengthForContentDependentAttribute += attributeLength ; byte [ ] binAtt ; if ( attribute instanceof ContextDependentAttribute ) { binMsg [ messageLengthOffset ] = ( byte ) ( dataLengthForContentDependentAttribute >> 8 ) ; binMsg [ messageLengthOffset + 1 ] = ( byte ) ( dataLengthForContentDependentAttribute & 0xFF ) ; binAtt = ( ( ContextDependentAttribute ) attribute ) . encode ( binMsg , 0 , offset ) ; } else { binAtt = attribute . encode ( ) ; } System . arraycopy ( binAtt , 0 , binMsg , offset , binAtt . length ) ; offset += attributeLength ; } binMsg [ messageLengthOffset ] = ( byte ) ( dataLength >> 8 ) ; binMsg [ messageLengthOffset + 1 ] = ( byte ) ( dataLength & 0xFF ) ; return binMsg ; }
Returns a binary representation of this message .
37,268
private void prepareForEncoding ( ) { StunAttribute msgIntAttr = removeAttribute ( StunAttribute . MESSAGE_INTEGRITY ) ; StunAttribute fingerprint = removeAttribute ( StunAttribute . FINGERPRINT ) ; String software = System . getProperty ( "TelScale Media Server" ) ; if ( getAttribute ( StunAttribute . SOFTWARE ) == null && software != null && software . length ( ) > 0 ) { addAttribute ( StunAttributeFactory . createSoftwareAttribute ( software . getBytes ( ) ) ) ; } if ( msgIntAttr != null ) { addAttribute ( msgIntAttr ) ; } if ( fingerprint == null ) { fingerprint = StunAttributeFactory . createFingerprintAttribute ( ) ; } if ( fingerprint != null ) { addAttribute ( fingerprint ) ; } }
Adds attributes that have been requested vis configuration properties . Asserts attribute order where necessary .
37,269
private static void performAttributeSpecificActions ( StunAttribute attribute , byte [ ] binMessage , int offset , int msgLen ) throws StunException { if ( attribute instanceof FingerprintAttribute ) { if ( ! validateFingerprint ( ( FingerprintAttribute ) attribute , binMessage , offset , msgLen ) ) { throw new StunException ( "Wrong value in FINGERPRINT" ) ; } } }
Executes actions related specific attributes like asserting proper fingerprint checksum .
37,270
protected void validateAttributePresentity ( ) throws IllegalStateException { if ( ! rfc3489CompatibilityMode ) { return ; } for ( char i = StunAttribute . MAPPED_ADDRESS ; i < StunAttribute . REFLECTED_FROM ; i ++ ) { if ( getAttributePresentity ( i ) == M && getAttribute ( i ) == null ) { throw new IllegalStateException ( "A mandatory attribute (type=" + ( int ) i + ") is missing!" ) ; } } }
Verify that the message has all obligatory attributes and throw an exception if this is not the case .
37,271
public static SessionDescription buildSdp ( boolean offer , String localAddress , String externalAddress , MediaChannel ... channels ) { SessionDescription sd = new SessionDescription ( ) ; sd . setVersion ( new VersionField ( ( short ) 0 ) ) ; String originAddress = ( externalAddress == null || externalAddress . isEmpty ( ) ) ? localAddress : externalAddress ; sd . setOrigin ( new OriginField ( "-" , String . valueOf ( System . currentTimeMillis ( ) ) , "1" , "IN" , "IP4" , originAddress ) ) ; sd . setSessionName ( new SessionNameField ( "Mobicents Media Server" ) ) ; sd . setConnection ( new ConnectionField ( "IN" , "IP4" , originAddress ) ) ; sd . setTiming ( new TimingField ( 0 , 0 ) ) ; boolean ice = false ; for ( MediaChannel channel : channels ) { MediaDescriptionField md = buildMediaDescription ( channel , offer ) ; md . setSession ( sd ) ; sd . addMediaDescription ( md ) ; if ( md . containsIce ( ) ) { sd . getConnection ( ) . setAddress ( md . getConnection ( ) . getAddress ( ) ) ; ice = true ; } } if ( ice ) { sd . setIceLite ( new IceLiteAttribute ( ) ) ; } return sd ; }
Builds a Session Description object to be sent to a remote peer .
37,272
public static void rejectMediaField ( SessionDescription answer , MediaDescriptionField media ) { MediaDescriptionField rejected = new MediaDescriptionField ( ) ; rejected . setMedia ( media . getMedia ( ) ) ; rejected . setPort ( 0 ) ; rejected . setProtocol ( media . getProtocol ( ) ) ; rejected . setPayloadTypes ( media . getPayloadTypes ( ) ) ; rejected . setSession ( answer ) ; answer . addMediaDescription ( rejected ) ; }
Rejects a media description from an SDP offer .
37,273
protected void setDescriptor ( Text line ) throws ParseException { line . trim ( ) ; try { Iterator < Text > it = line . split ( '=' ) . iterator ( ) ; Text t = it . next ( ) ; t = it . next ( ) ; it = t . split ( ' ' ) . iterator ( ) ; mediaType = it . next ( ) ; mediaType . trim ( ) ; t = it . next ( ) ; t . trim ( ) ; port = t . toInteger ( ) ; profile = it . next ( ) ; profile . trim ( ) ; while ( it . hasNext ( ) ) { t = it . next ( ) ; t . trim ( ) ; RTPFormat fmt = AVProfile . getFormat ( t . toInteger ( ) , mediaType ) ; if ( fmt != null && ! formats . contains ( fmt . getFormat ( ) ) ) { formats . add ( fmt . clone ( ) ) ; } } } catch ( Exception e ) { throw new ParseException ( "Could not parse media descriptor" , 0 ) ; } }
Reads values from specified text line
37,274
protected void addAttribute ( Text attribute ) { if ( attribute . startsWith ( SessionDescription . RTPMAP ) ) { addRtpMapAttribute ( attribute ) ; return ; } if ( attribute . startsWith ( SessionDescription . FMTP ) ) { addFmtAttribute ( attribute ) ; return ; } if ( attribute . startsWith ( SessionDescription . WEBRTC_FINGERPRINT ) ) { addFingerprintAttribute ( attribute ) ; return ; } if ( attribute . startsWith ( SessionDescription . ICE_UFRAG ) ) { this . ice = true ; addIceUfragAttribute ( attribute ) ; return ; } if ( attribute . startsWith ( SessionDescription . ICE_PWD ) ) { this . ice = true ; addIcePwdAttribute ( attribute ) ; return ; } if ( attribute . startsWith ( CandidateField . CANDIDATE_FIELD ) ) { this . ice = true ; addCandidate ( attribute ) ; return ; } if ( attribute . startsWith ( RtcpMuxField . RTCP_MUX_FIELD ) ) { this . rtcpMux = true ; return ; } }
Parses attribute .
37,275
private void addCandidate ( Text attribute ) { Text attr = new Text ( ) ; attribute . copy ( attr ) ; attr . trim ( ) ; CandidateField candidateField = new CandidateField ( attr ) ; this . candidates . add ( candidateField ) ; Collections . sort ( this . candidates , Collections . reverseOrder ( ) ) ; }
Parses a candidate field for ICE and register it on internal list .
37,276
protected void setConnection ( Text line ) throws ParseException { connection = new ConnectionField ( ) ; connection . strain ( line ) ; Collections . sort ( this . candidates ) ; }
Modify connection attribute .
37,277
private RTPFormat createFormat ( int payload , Text description ) { MediaType mtype = MediaType . fromDescription ( mediaType ) ; switch ( mtype ) { case AUDIO : return createAudioFormat ( payload , description ) ; case VIDEO : return createVideoFormat ( payload , description ) ; case APPLICATION : return createApplicationFormat ( payload , description ) ; default : return null ; } }
Creates or updates format using payload number and text format description .
37,278
private RTPFormat createAudioFormat ( int payload , Text description ) { Iterator < Text > it = description . split ( '/' ) . iterator ( ) ; Text token = it . next ( ) ; token . trim ( ) ; EncodingName name = new EncodingName ( token ) ; token = it . next ( ) ; token . trim ( ) ; int clockRate = token . toInteger ( ) ; int channels = 1 ; if ( it . hasNext ( ) ) { token = it . next ( ) ; token . trim ( ) ; channels = token . toInteger ( ) ; } RTPFormat rtpFormat = getFormat ( payload ) ; if ( rtpFormat == null ) { formats . add ( new RTPFormat ( payload , FormatFactory . createAudioFormat ( name , clockRate , - 1 , channels ) ) ) ; } else { ( ( AudioFormat ) rtpFormat . getFormat ( ) ) . setName ( name ) ; ( ( AudioFormat ) rtpFormat . getFormat ( ) ) . setSampleRate ( clockRate ) ; ( ( AudioFormat ) rtpFormat . getFormat ( ) ) . setChannels ( channels ) ; } return rtpFormat ; }
Creates or updates audio format using payload number and text format description .
37,279
private RTPFormat createVideoFormat ( int payload , Text description ) { Iterator < Text > it = description . split ( '/' ) . iterator ( ) ; Text token = it . next ( ) ; token . trim ( ) ; EncodingName name = new EncodingName ( token ) ; token = it . next ( ) ; token . trim ( ) ; int clockRate = token . toInteger ( ) ; RTPFormat rtpFormat = getFormat ( payload ) ; if ( rtpFormat == null ) { formats . add ( new RTPFormat ( payload , FormatFactory . createVideoFormat ( name , clockRate ) ) ) ; } else { ( ( VideoFormat ) rtpFormat . getFormat ( ) ) . setName ( name ) ; ( ( VideoFormat ) rtpFormat . getFormat ( ) ) . setFrameRate ( clockRate ) ; } return rtpFormat ; }
Creates or updates video format using payload number and text format description .
37,280
private RTPFormat createApplicationFormat ( int payload , Text description ) { Iterator < Text > it = description . split ( '/' ) . iterator ( ) ; Text token = it . next ( ) ; token . trim ( ) ; EncodingName name = new EncodingName ( token ) ; token = it . next ( ) ; token . trim ( ) ; RTPFormat rtpFormat = getFormat ( payload ) ; if ( rtpFormat == null ) { formats . add ( new RTPFormat ( payload , FormatFactory . createApplicationFormat ( name ) ) ) ; } else { ( ( ApplicationFormat ) rtpFormat . getFormat ( ) ) . setName ( name ) ; } return rtpFormat ; }
Creates or updates application format using payload number and text format description .
37,281
private boolean isTypeValid ( char type ) { return ( type == MAPPED_ADDRESS || type == RESPONSE_ADDRESS || type == SOURCE_ADDRESS || type == CHANGED_ADDRESS || type == REFLECTED_FROM || type == XOR_MAPPED_ADDRESS || type == ALTERNATE_SERVER || type == XOR_PEER_ADDRESS || type == XOR_RELAYED_ADDRESS || type == DESTINATION_ADDRESS ) ; }
Verifies that type is a valid address attribute type .
37,282
public static boolean isSubclass ( Class a , Class b ) { if ( a == b ) return false ; if ( ! ( b . isAssignableFrom ( a ) ) ) return false ; return true ; }
Is a a subclass of b? Strict .
37,283
public void append ( byte [ ] data , int len ) { if ( data == null || len <= 0 || len > data . length ) { throw new IllegalArgumentException ( "Invalid combination of parameters data and length to append()" ) ; } int oldLimit = buffer . limit ( ) ; grow ( len ) ; buffer . position ( oldLimit ) ; buffer . limit ( oldLimit + len ) ; buffer . put ( data , 0 , len ) ; }
Append a byte array to the end of the packet . This may change the data buffer of this packet .
37,284
public int readInt ( int off ) { this . buffer . rewind ( ) ; return ( ( buffer . get ( off ++ ) & 0xFF ) << 24 ) | ( ( buffer . get ( off ++ ) & 0xFF ) << 16 ) | ( ( buffer . get ( off ++ ) & 0xFF ) << 8 ) | ( buffer . get ( off ++ ) & 0xFF ) ; }
Read a integer from this packet at specified offset
37,285
public byte [ ] readRegion ( int off , int len ) { this . buffer . rewind ( ) ; if ( off < 0 || len <= 0 || off + len > this . buffer . limit ( ) ) { return null ; } byte [ ] region = new byte [ len ] ; this . buffer . get ( region , off , len ) ; return region ; }
Read a byte region from specified offset with specified length
37,286
public void readRegionToBuff ( int off , int len , byte [ ] outBuff ) { assert off >= 0 ; assert len > 0 ; assert outBuff != null ; assert outBuff . length >= len ; assert buffer . limit ( ) >= off + len ; buffer . position ( off ) ; buffer . get ( outBuff , 0 , len ) ; }
Read a byte region from specified offset in the RTP packet and with specified length into a given buffer
37,287
public int readUnsignedShortAsInt ( int off ) { this . buffer . position ( off ) ; int b1 = ( 0x000000FF & ( this . buffer . get ( ) ) ) ; int b2 = ( 0x000000FF & ( this . buffer . get ( ) ) ) ; int val = b1 << 8 | b2 ; return val ; }
Read an unsigned short at specified offset as a int
37,288
public long readUnsignedIntAsLong ( int off ) { buffer . position ( off ) ; return ( ( ( long ) ( buffer . get ( ) & 0xff ) << 24 ) | ( ( long ) ( buffer . get ( ) & 0xff ) << 16 ) | ( ( long ) ( buffer . get ( ) & 0xff ) << 8 ) | ( ( long ) ( buffer . get ( ) & 0xff ) ) ) & 0xFFFFFFFFL ; }
Read an unsigned integer as long at specified offset
37,289
public void shrink ( int delta ) { if ( delta <= 0 ) { return ; } int newLimit = buffer . limit ( ) - delta ; if ( newLimit <= 0 ) { newLimit = 0 ; } this . buffer . limit ( newLimit ) ; }
Shrink the buffer of this packet by specified length
37,290
public void recycle ( ) { while ( buffer . size ( ) > 0 ) buffer . poll ( ) . recycle ( ) ; if ( activeFrame != null ) activeFrame . recycle ( ) ; activeFrame = null ; activeData = null ; byteIndex = 0 ; }
Recycles input stream
37,291
public void bind ( boolean isLocal ) throws IOException , SocketException { try { rtpChannel = udpManager . open ( rtpHandler ) ; if ( channelsManager . getIsControlEnabled ( ) ) { rtcpChannel = udpManager . open ( new RTCPHandler ( ) ) ; } } catch ( IOException e ) { throw new SocketException ( e . getMessage ( ) ) ; } if ( ! isLocal ) { this . rxBuffer . setInUse ( true ) ; udpManager . bind ( rtpChannel , PORT_ANY ) ; } else { this . rxBuffer . setInUse ( false ) ; udpManager . bindLocal ( rtpChannel , PORT_ANY ) ; } this . rtpChannelBound = true ; if ( channelsManager . getIsControlEnabled ( ) ) { if ( ! isLocal ) udpManager . bind ( rtcpChannel , rtpChannel . socket ( ) . getLocalPort ( ) + 1 ) ; else udpManager . bindLocal ( rtcpChannel , rtpChannel . socket ( ) . getLocalPort ( ) + 1 ) ; } }
Binds channel to the first available port .
37,292
public void setPeer ( SocketAddress address ) { this . remotePeer = address ; boolean connectImmediately = false ; if ( rtpChannel != null ) { if ( rtpChannel . isConnected ( ) ) try { rtpChannel . disconnect ( ) ; } catch ( IOException e ) { logger . error ( e ) ; } connectImmediately = udpManager . connectImmediately ( ( InetSocketAddress ) address ) ; if ( connectImmediately ) try { rtpChannel . connect ( address ) ; } catch ( IOException e ) { logger . info ( "Can not connect to remote address , please check that you are not using local address - 127.0.0.X to connect to remote" ) ; logger . error ( e ) ; } } if ( udpManager . getRtpTimeout ( ) > 0 && ! connectImmediately ) { if ( shouldReceive ) { lastPacketReceived = scheduler . getClock ( ) . getTime ( ) ; scheduler . submitHeatbeat ( heartBeat ) ; } else { heartBeat . cancel ( ) ; } } }
Sets the address of remote peer .
37,293
public void close ( ) { if ( rtpChannel != null ) { if ( rtpChannel . isConnected ( ) ) { try { rtpChannel . disconnect ( ) ; } catch ( IOException e ) { logger . error ( e ) ; } try { rtpChannel . socket ( ) . close ( ) ; rtpChannel . close ( ) ; } catch ( IOException e ) { logger . error ( e ) ; } } } if ( rtcpChannel != null ) { rtcpChannel . socket ( ) . close ( ) ; } rxCount = 0 ; txCount = 0 ; input . deactivate ( ) ; dtmfInput . deactivate ( ) ; dtmfInput . reset ( ) ; output . deactivate ( ) ; dtmfOutput . deactivate ( ) ; this . tx . clear ( ) ; heartBeat . cancel ( ) ; sendDtmf = false ; }
Closes this socket .
37,294
public boolean isAvailable ( ) { boolean available = this . rtpChannel != null && this . rtpChannel . isConnected ( ) ; if ( this . isWebRtc ) { available = available && this . webRtcHandler . isHandshakeComplete ( ) ; } return available ; }
Checks whether the data channel is available for media exchange .
37,295
public void enableWebRTC ( Text remotePeerFingerprint ) { this . isWebRtc = true ; if ( this . webRtcHandler == null ) { this . webRtcHandler = new DtlsHandler ( this . dtlsServerProvider ) ; } this . webRtcHandler . setRemoteFingerprint ( "sha-256" , remotePeerFingerprint . toString ( ) ) ; }
Enables WebRTC encryption for the RTP channel .
37,296
public void open ( ) { this . ssrc = SsrcGenerator . generateSsrc ( ) ; this . statistics . setSsrc ( this . ssrc ) ; this . open = true ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( this . mediaType + " channel " + this . ssrc + " is open" ) ; } }
Enables the channel and activates it s resources .
37,297
public void close ( ) throws IllegalStateException { if ( this . open ) { this . rtpChannel . close ( ) ; if ( ! this . rtcpMux ) { this . rtcpChannel . close ( ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( this . mediaType + " channel " + this . ssrc + " is closed" ) ; } reset ( ) ; this . open = false ; } else { throw new IllegalStateException ( "Channel is already inactive" ) ; } }
Disables the channel and deactivates it s resources .
37,298
private void reset ( ) { resetFormats ( ) ; if ( this . rtcpMux ) { this . rtcpMux = false ; } if ( this . ice ) { disableICE ( ) ; } if ( this . dtls ) { disableDTLS ( ) ; } this . statistics . reset ( ) ; this . cname = "" ; this . ssrc = 0L ; }
Resets the state of the channel .
37,299
protected void setFormats ( RTPFormats formats ) { try { this . rtpChannel . setFormatMap ( formats ) ; this . rtpChannel . setOutputFormats ( formats . getFormats ( ) ) ; } catch ( FormatNotSupportedException e ) { logger . warn ( "Could not set output formats" , e ) ; } }
Sets the supported codecs of the RTP components .