idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
40,000
public Direction direction ( ) { if ( ! Op . isFinite ( slope ) || Op . isEq ( slope , 0.0 ) ) { return Direction . Zero ; } if ( Op . isGt ( slope , 0.0 ) ) { return Direction . Positive ; } return Direction . Negative ; }
Returns the direction of the sigmoid
40,001
public static Engine mamdani ( ) { Engine engine = new Engine ( ) ; engine . setName ( "simple-dimmer" ) ; engine . setDescription ( "" ) ; InputVariable ambient = new InputVariable ( ) ; ambient . setName ( "ambient" ) ; ambient . setDescription ( "" ) ; ambient . setEnabled ( true ) ; ambient . setRange ( 0.000 , 1.000 ) ; ambient . setLockValueInRange ( false ) ; ambient . addTerm ( new Triangle ( "DARK" , 0.000 , 0.250 , 0.500 ) ) ; ambient . addTerm ( new Triangle ( "MEDIUM" , 0.250 , 0.500 , 0.750 ) ) ; ambient . addTerm ( new Triangle ( "BRIGHT" , 0.500 , 0.750 , 1.000 ) ) ; engine . addInputVariable ( ambient ) ; OutputVariable power = new OutputVariable ( ) ; power . setName ( "power" ) ; power . setDescription ( "" ) ; power . setEnabled ( true ) ; power . setRange ( 0.000 , 2.000 ) ; power . setLockValueInRange ( false ) ; power . setAggregation ( new Maximum ( ) ) ; power . setDefuzzifier ( new Centroid ( 200 ) ) ; power . setDefaultValue ( Double . NaN ) ; power . setLockPreviousValue ( false ) ; power . addTerm ( new Triangle ( "LOW" , 0.000 , 0.500 , 1.000 ) ) ; power . addTerm ( new Triangle ( "MEDIUM" , 0.500 , 1.000 , 1.500 ) ) ; power . addTerm ( new Triangle ( "HIGH" , 1.000 , 1.500 , 2.000 ) ) ; engine . addOutputVariable ( power ) ; RuleBlock ruleBlock = new RuleBlock ( ) ; ruleBlock . setName ( "" ) ; ruleBlock . setDescription ( "" ) ; ruleBlock . setEnabled ( true ) ; ruleBlock . setConjunction ( null ) ; ruleBlock . setDisjunction ( null ) ; ruleBlock . setImplication ( new Minimum ( ) ) ; ruleBlock . setActivation ( new General ( ) ) ; ruleBlock . addRule ( Rule . parse ( "if ambient is DARK then power is HIGH" , engine ) ) ; ruleBlock . addRule ( Rule . parse ( "if ambient is MEDIUM then power is MEDIUM" , engine ) ) ; ruleBlock . addRule ( Rule . parse ( "if ambient is BRIGHT then power is LOW" , engine ) ) ; engine . addRuleBlock ( ruleBlock ) ; return engine ; }
Creates a new Mamdani Engine based on the SimpleDimmer example
40,002
public void benchmark ( File fllFile , File fldFile , int runs , Writer writer ) throws Exception { Engine engine = new FllImporter ( ) . fromFile ( fllFile ) ; Reader reader = new InputStreamReader ( new FileInputStream ( fldFile ) , FuzzyLite . UTF_8 ) ; try { Benchmark benchmark = new Benchmark ( engine . getName ( ) , engine ) ; benchmark . prepare ( reader ) ; if ( writer != null ) { FuzzyLite . logger ( ) . log ( Level . INFO , "\tEvaluating on {0} values read from {1}" , new Object [ ] { benchmark . getExpected ( ) . size ( ) , fldFile . getAbsolutePath ( ) } ) ; } for ( int i = 0 ; i < runs ; ++ i ) { benchmark . runOnce ( ) ; } String results = benchmark . format ( benchmark . results ( ) , Benchmark . TableShape . Horizontal , Benchmark . TableContents . Body ) + "\n" ; if ( writer != null ) { double [ ] times = new double [ benchmark . getTimes ( ) . size ( ) ] ; for ( int i = 0 ; i < benchmark . getTimes ( ) . size ( ) ; ++ i ) { times [ i ] = benchmark . getTimes ( ) . get ( i ) ; } FuzzyLite . logger ( ) . log ( Level . INFO , "\tMean(t)={0}" , Op . str ( Op . mean ( times ) ) ) ; writer . write ( results ) ; writer . flush ( ) ; } else { System . out . println ( results ) ; } } catch ( Exception ex ) { throw ex ; } finally { reader . close ( ) ; } }
Benchmarks the engine described in the FLL file against the dataset contained in the FLD file .
40,003
public void benchmarks ( File fllFileList , File fldFileList , int runs , Writer writer ) throws Exception { List < String > fllFiles = new ArrayList < String > ( ) ; List < String > fldFiles = new ArrayList < String > ( ) ; { BufferedReader fllReader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( fllFileList ) , FuzzyLite . UTF_8 ) ) ; BufferedReader fldReader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( fldFileList ) , FuzzyLite . UTF_8 ) ) ; try { String fllLine , fldLine ; while ( ( fllLine = fllReader . readLine ( ) ) != null && ( fldLine = fldReader . readLine ( ) ) != null ) { fllLine = fllLine . trim ( ) ; fldLine = fldLine . trim ( ) ; if ( fllLine . isEmpty ( ) || fllLine . charAt ( 0 ) == '#' ) { continue ; } fllFiles . add ( fllLine ) ; fldFiles . add ( fldLine ) ; } } catch ( Exception ex ) { throw ex ; } finally { fllReader . close ( ) ; fldReader . close ( ) ; } } if ( writer != null ) { writer . write ( Op . join ( new Benchmark ( ) . header ( runs , true ) , "\t" ) + "\n" ) ; writer . flush ( ) ; } else { System . out . println ( Op . join ( new Benchmark ( ) . header ( runs , true ) , "\t" ) ) ; } for ( int i = 0 ; i < fllFiles . size ( ) ; ++ i ) { if ( writer != null ) { FuzzyLite . logger ( ) . log ( Level . INFO , "Benchmark {0}/{1}: {2}" , new Object [ ] { i + 1 , fllFiles . size ( ) , fllFiles . get ( i ) } ) ; } benchmark ( new File ( fllFiles . get ( i ) ) , new File ( fldFiles . get ( i ) ) , runs , writer ) ; } }
Benchmarks the list of engines against the list of datasets both described as absolute or relative paths
40,004
public void setValue ( double value ) { this . value = lockValueInRange ? Op . bound ( value , minimum , maximum ) : value ; }
Sets the value of the variable
40,005
public String fuzzify ( double x ) { StringBuilder sb = new StringBuilder ( ) ; for ( Term term : getTerms ( ) ) { double fx = term . membership ( x ) ; if ( sb . length ( ) == 0 ) { sb . append ( Op . str ( fx ) ) ; } else if ( Double . isNaN ( fx ) || Op . isGE ( fx , 0.0 ) ) { sb . append ( " + " ) . append ( Op . str ( fx ) ) ; } else { sb . append ( " - " ) . append ( Op . str ( fx ) ) ; } sb . append ( "/" ) . append ( term . getName ( ) ) ; } return sb . toString ( ) ; }
Evaluates the membership function of value x for each term i resulting in a fuzzy value in the form
40,006
public Op . Pair < Double , Term > highestMembership ( double x ) { Op . Pair < Double , Term > result = new Op . Pair < Double , Term > ( 0.0 , null ) ; for ( Term term : terms ) { double y = term . membership ( x ) ; if ( Op . isGt ( y , result . getFirst ( ) ) ) { result . setFirst ( y ) ; result . setSecond ( term ) ; } } return result ; }
Gets the term which has the highest membership function value for
40,007
public void sort ( ) { PriorityQueue < Op . Pair < Term , Double > > termCentroids = new PriorityQueue < Op . Pair < Term , Double > > ( terms . size ( ) , new Ascending ( ) ) ; Defuzzifier defuzzifier = new Centroid ( ) ; for ( Term term : terms ) { double centroid ; try { if ( term instanceof Constant || term instanceof Linear ) { centroid = term . membership ( 0 ) ; } else { centroid = defuzzifier . defuzzify ( term , getMinimum ( ) , getMaximum ( ) ) ; } } catch ( Exception ex ) { centroid = Double . POSITIVE_INFINITY ; } termCentroids . offer ( new Op . Pair < Term , Double > ( term , centroid ) ) ; } List < Term > sortedTerms = new ArrayList < Term > ( terms . size ( ) ) ; while ( ! termCentroids . isEmpty ( ) ) { sortedTerms . add ( termCentroids . poll ( ) . getFirst ( ) ) ; } setTerms ( sortedTerms ) ; }
Sorts the terms in ascending order according to their centroids
40,008
public Term getTerm ( String name ) { for ( Term term : this . terms ) { if ( name . equals ( term . getName ( ) ) ) { return term ; } } return null ; }
Gets the term of the given name .
40,009
public Term removeTerm ( String name ) { Iterator < Term > it = this . terms . iterator ( ) ; while ( it . hasNext ( ) ) { Term term = it . next ( ) ; if ( term . getName ( ) . equals ( name ) ) { it . remove ( ) ; return term ; } } return null ; }
Removes the term
40,010
public static void setDecimals ( int decimals ) { FuzzyLite . decimals = decimals ; DecimalFormat decimalFormat = FORMATTER . get ( ) ; decimalFormat . setMinimumFractionDigits ( decimals ) ; decimalFormat . setMaximumFractionDigits ( decimals ) ; }
Sets the number of decimals utilized when formatting scalar values
40,011
public static void setLogging ( boolean logging ) { if ( logging ) { logger . setLevel ( debugging ? Level . FINE : Level . INFO ) ; } else { logger . setLevel ( Level . OFF ) ; } }
Sets whether the library is set to log information
40,012
public static void setDebugging ( boolean debugging ) { FuzzyLite . debugging = debugging ; if ( isLogging ( ) ) { logger . setLevel ( debugging ? Level . FINE : Level . INFO ) ; } }
Sets whether the library is set to run in debug mode
40,013
public Engine fromFile ( File file ) throws IOException { BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) , FuzzyLite . UTF_8 ) ) ; String line ; StringBuilder textEngine = new StringBuilder ( ) ; try { while ( ( line = reader . readLine ( ) ) != null ) { textEngine . append ( line ) . append ( "\n" ) ; } } catch ( IOException ex ) { throw ex ; } finally { reader . close ( ) ; } return fromString ( textEngine . toString ( ) ) ; }
Imports the engine from the given file
40,014
public double compute ( double a , double b ) { if ( Op . isEq ( a + b , 0.0 ) ) return 0.0 ; return ( a * b ) / ( a + b - a * b ) ; }
Computes the Hamacher product of two membership function values
40,015
public ExtWebDriver getCurrentSession ( boolean createIfNotFound ) { for ( int i = 0 ; i < MAX_RETRIES ; i ++ ) { ExtWebDriver sel = sessions . get ( currentSessionId ) ; try { if ( ( sel == null ) && ( createIfNotFound ) ) { sel = getNewSession ( ) ; } return sel ; } catch ( Exception e ) { if ( ! ( e instanceof UnreachableBrowserException ) ) { e . printStackTrace ( ) ; } } } return null ; }
Get the current session associated with this thread . Because a SessionManager instance is thread - local the notion of current is also specific to a thread .
40,016
public ExtWebDriver getNewSession ( boolean setAsCurrent ) throws Exception { Map < String , String > options = sessionFactory . get ( ) . createDefaultOptions ( ) ; return getNewSessionDo ( options , setAsCurrent ) ; }
Create and return new ExtWebDriver instance with default options . If setAsCurrent is true set the new session as the current session for this SessionManager .
40,017
private static double similarity ( BufferedImage var , BufferedImage cont ) { double [ ] varArr = new double [ var . getWidth ( ) * var . getHeight ( ) * 3 ] ; double [ ] contArr = new double [ cont . getWidth ( ) * cont . getHeight ( ) * 3 ] ; if ( varArr . length != contArr . length ) throw new IllegalStateException ( "The pictures are different sizes!" ) ; for ( int i = 0 ; i < var . getHeight ( ) ; i ++ ) { for ( int j = 0 ; j < var . getWidth ( ) ; j ++ ) { varArr [ i * var . getWidth ( ) + j + 0 ] = new Color ( var . getRGB ( j , i ) ) . getRed ( ) ; contArr [ i * cont . getWidth ( ) + j + 0 ] = new Color ( cont . getRGB ( j , i ) ) . getRed ( ) ; varArr [ i * var . getWidth ( ) + j + 1 ] = new Color ( var . getRGB ( j , i ) ) . getGreen ( ) ; contArr [ i * cont . getWidth ( ) + j + 1 ] = new Color ( cont . getRGB ( j , i ) ) . getGreen ( ) ; varArr [ i * var . getWidth ( ) + j + 2 ] = new Color ( var . getRGB ( j , i ) ) . getBlue ( ) ; contArr [ i * cont . getWidth ( ) + j + 2 ] = new Color ( cont . getRGB ( j , i ) ) . getBlue ( ) ; } } double mins = 0 ; double maxs = 0 ; for ( int i = 0 ; i != varArr . length ; i ++ ) { if ( varArr [ i ] > contArr [ i ] ) { mins += contArr [ i ] ; maxs += varArr [ i ] ; } else { mins += varArr [ i ] ; maxs += contArr [ i ] ; } } return mins / maxs ; }
Returns a double between 0 and 1 . 0
40,018
private String generateXPathLocator ( ) throws WidgetException { if ( xPathLocator == null ) { IElement elem = new Element ( getByLocator ( ) ) ; String key = "tablewidgetattribute" ; long value = System . currentTimeMillis ( ) ; elem . eval ( "arguments[0].setAttribute('" + key + "', '" + value + "')" ) ; xPathLocator = "//*[@" + key + "='" + value + "']" ; } return xPathLocator ; }
unique attribute value
40,019
private boolean isElementPresent_internal ( ) throws WidgetException { try { try { final boolean isPotentiallyXpathWithLocator = ( locator instanceof EByFirstMatching ) || ( locator instanceof EByXpath ) ; if ( isPotentiallyXpathWithLocator && isElementPresentJavaXPath ( ) ) return true ; } catch ( Exception e ) { } findElement ( ) ; return true ; } catch ( NoSuchElementException e ) { return false ; } }
Use the JavaXPath to determine if element is present . If not then try finding element . Return false if the element does not exist
40,020
public void waitForNotVisible ( final long time ) throws WidgetException { try { waitForCommand ( new ITimerCallback ( ) { public boolean execute ( ) throws WidgetException { return ! isVisible ( ) ; } public String toString ( ) { return "Waiting for element with locator: " + locator + " to not be visible" ; } } , time ) ; } catch ( Exception e ) { throw new WidgetException ( "Error while waiting for element to be not visible" , locator , e ) ; } }
Waits for specific element at locator to be not visible within period of specified time
40,021
public void eval ( String javascript ) throws WidgetException { WebElement element = findElement ( false ) ; WebDriver wd = getGUIDriver ( ) . getWrappedDriver ( ) ; try { ( ( JavascriptExecutor ) wd ) . executeScript ( javascript , element ) ; } catch ( Exception e ) { long time = System . currentTimeMillis ( ) + 2000 ; boolean success = false ; while ( ! success && System . currentTimeMillis ( ) < time ) { try { ( ( JavascriptExecutor ) wd ) . executeScript ( javascript , element ) ; success = true ; } catch ( Exception e2 ) { try { Thread . sleep ( 500 ) ; } catch ( InterruptedException e1 ) { } e = e2 ; } } if ( ! success ) { throw new RuntimeException ( e ) ; } } }
Executes JavaScript code on the current element in the current frame or window .
40,022
protected void waitForCommand ( ITimerCallback callback , long timeout ) throws WidgetTimeoutException { WaitForConditionTimer t = new WaitForConditionTimer ( getByLocator ( ) , callback ) ; t . waitUntil ( timeout ) ; }
wait for timeout amount of time
40,023
private boolean isElementPresentJavaXPath ( ) throws Exception { String xpath = ( ( StringLocatorAwareBy ) getByLocator ( ) ) . getLocator ( ) ; try { xpath = formatXPathForJavaXPath ( xpath ) ; NodeList nodes = getNodeListUsingJavaXPath ( xpath ) ; if ( nodes . getLength ( ) > 0 ) { return true ; } else { return false ; } } catch ( Exception e ) { throw new Exception ( "Error performing isElement present using Java XPath: " + xpath , e ) ; } }
Use the Java Xpath API to determine if the element is present or not
40,024
private static String formatXPathForJavaXPath ( String xpath ) throws Exception { String newXPath = "" ; if ( xpath . startsWith ( "xpath=" ) ) { xpath = xpath . replace ( "xpath=" , "" ) ; } boolean convertIndicator = true ; boolean onSlash = false ; boolean onSingleQuote = false ; boolean onDoubleQuote = false ; for ( int i = 0 ; i < xpath . length ( ) ; i ++ ) { char c = xpath . charAt ( i ) ; if ( c == '/' ) { if ( ! onSingleQuote && ! onDoubleQuote ) { if ( convertIndicator ) { if ( ! onSlash ) { onSlash = true ; } else { onSlash = false ; } } else { convertIndicator = true ; onSlash = true ; } } } else if ( c == '[' ) { if ( ! onSingleQuote && ! onDoubleQuote ) convertIndicator = false ; } else if ( c == ']' ) { if ( ! onSingleQuote && ! onDoubleQuote ) convertIndicator = true ; } else if ( c == '\'' ) { if ( ! onSingleQuote ) onSingleQuote = true ; else onSingleQuote = false ; } else if ( c == '\"' ) { if ( ! onDoubleQuote ) onDoubleQuote = true ; else onDoubleQuote = false ; } if ( convertIndicator ) newXPath = newXPath + String . valueOf ( c ) . toLowerCase ( ) ; else newXPath = newXPath + String . valueOf ( c ) ; } return newXPath ; }
Format the xpath to work with Java XPath API
40,025
private NodeList getNodeListUsingJavaXPath ( String xpath ) throws Exception { XPathFactory xpathFac = XPathFactory . newInstance ( ) ; XPath theXpath = xpathFac . newXPath ( ) ; String html = getGUIDriver ( ) . getHtmlSource ( ) ; html = html . replaceAll ( ">\\s+<" , "><" ) ; InputStream input = new ByteArrayInputStream ( html . getBytes ( Charset . forName ( "UTF-8" ) ) ) ; XMLReader reader = new Parser ( ) ; reader . setFeature ( Parser . namespacesFeature , false ) ; Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; DOMResult result = new DOMResult ( ) ; transformer . transform ( new SAXSource ( reader , new InputSource ( input ) ) , result ) ; Node htmlNode = result . getNode ( ) ; NodeList nodes = ( NodeList ) theXpath . evaluate ( xpath , htmlNode , XPathConstants . NODESET ) ; return nodes ; }
Get the list of nodes which satisfy the xpath expression passed in
40,026
private void waitForAttributePatternMatcher ( String attributeName , String pattern , long timeout , boolean waitCondition ) throws WidgetException { long start = System . currentTimeMillis ( ) ; long end = start + timeout ; while ( System . currentTimeMillis ( ) < end ) { String attribute = getAttribute ( attributeName ) ; if ( attribute != null && attribute . matches ( pattern ) == waitCondition ) return ; try { Thread . sleep ( DEFAULT_INTERVAL ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } throw new TimeOutException ( "waitForAttribute " + " : timeout : Locator : " + locator + " Attribute : " + attributeName ) ; }
Matches an attribute value to a pattern that is passed .
40,027
public void fireEvent ( String event ) throws WidgetException { try { String javaScript = null ; if ( event . startsWith ( "mouse" ) ) { javaScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('" + event + "', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('on" + event + "');}" ; } else { javaScript = "if(document.createEvent){var evObj = document.createEvent('HTMLEvents');evObj.initEvent('" + event + "', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('on" + event + "');}" ; } eval ( javaScript ) ; } catch ( Exception e ) { throw new WidgetException ( "Error while trying to fire event" , getByLocator ( ) , e ) ; } }
Fires a javascript event on a web element
40,028
public String [ ] getChildNodesValuesText ( ) throws WidgetException { WebElement we = new Element ( getByLocator ( ) ) . getWebElement ( ) ; List < WebElement > childNodes = we . findElements ( By . xpath ( "./*" ) ) ; String [ ] childText = new String [ childNodes . size ( ) ] ; int i = 0 ; for ( WebElement element : childNodes ) { childText [ i ] = element . getText ( ) ; i ++ ; } return childText ; }
Returns the text contained in the child nodes of the current element
40,029
public void highlight ( HIGHLIGHT_MODES mode ) throws WidgetException { if ( mode . equals ( HIGHLIGHT_MODES . NONE ) ) return ; else highlight ( mode . toString ( ) ) ; }
Find the current element and highlight it according to the mode If mode is NONE do nothing
40,030
private void doHighlight ( String colorMode ) throws WidgetException { if ( ! ( getGUIDriver ( ) instanceof HighlightProvider ) ) { return ; } HighlightProvider highDriver = ( HighlightProvider ) getGUIDriver ( ) ; if ( highDriver . isHighlight ( ) ) { setBackgroundColor ( highDriver . getHighlightColor ( colorMode ) ) ; } }
Highlight a web element by getting its color from the map loaded from client properties file
40,031
public void setValue ( Object value ) throws WidgetException { boolean set = false ; try { if ( value instanceof String ) { if ( ( ( String ) value ) . equalsIgnoreCase ( UNCHECK ) ) { doAction ( true ) ; } else if ( ( ( String ) value ) . equalsIgnoreCase ( CHECK ) ) { doAction ( false ) ; } set = true ; } else { throw new WidgetRuntimeException ( "value must be a String of either 'check' or 'uncheck'" , getByLocator ( ) ) ; } } catch ( Exception e ) { throw new WidgetException ( "Error while checking/unchecking" , getByLocator ( ) , e ) ; } if ( ! set ) throw new WidgetException ( "Invalid set value for checkbox. It must be either 'check' or 'uncheck'" , getByLocator ( ) ) ; }
Sets the value of the CheckBox
40,032
public void waitForChecked ( final long time ) throws WidgetException { super . waitForCommand ( new ITimerCallback ( ) { public boolean execute ( ) { WebElement elem = null ; try { elem = getWebElement ( ) ; } catch ( WidgetException e ) { } boolean isSelected = false ; try { isSelected = isSelected ( elem ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } return ( elem != null && isSelected ) ; } public String toString ( ) { return "Waiting for element with the locator: " + getByLocator ( ) + "to be checked" ; } } , time ) ; }
Waits for element at locator to be checked within period of specified time
40,033
private Map < String , String > getGeneratedHtmlSourceRecursive ( FrameNode currentFrame , String currFrameId ) throws Exception { Map < String , String > frames = new HashMap < String , String > ( ) ; if ( ! currentFrame . isRoot ( ) ) { wd . switchTo ( ) . defaultContent ( ) ; Stack < FrameNode > framesToSelect = new Stack < FrameNode > ( ) ; FrameNode currFrame = currentFrame ; while ( currFrame . getParent ( ) != null ) { framesToSelect . push ( currFrame ) ; currFrame = currFrame . getParent ( ) ; } while ( ! framesToSelect . isEmpty ( ) ) { FrameNode fn = framesToSelect . pop ( ) ; wd . switchTo ( ) . frame ( fn . getFrame ( ) ) ; } } else { wd . switchTo ( ) . defaultContent ( ) ; } frames . put ( currFrameId , wd . getPageSource ( ) ) ; int iframeCount = wd . findElements ( By . xpath ( "//iframe" ) ) . size ( ) ; if ( iframeCount == 0 ) { return frames ; } for ( int i = 1 ; i <= iframeCount ; i ++ ) { if ( ! currentFrame . isRoot ( ) ) { wd . switchTo ( ) . defaultContent ( ) ; Stack < FrameNode > framesToSelect = new Stack < FrameNode > ( ) ; FrameNode currFrame = currentFrame ; while ( currFrame . getParent ( ) != null ) { framesToSelect . push ( currFrame ) ; currFrame = currFrame . getParent ( ) ; } while ( ! framesToSelect . isEmpty ( ) ) { FrameNode fn = framesToSelect . pop ( ) ; wd . switchTo ( ) . frame ( fn . getFrame ( ) ) ; } } else { wd . switchTo ( ) . defaultContent ( ) ; } FrameNode nextFrame = new FrameNode ( currentFrame , By . xpath ( "(//iframe)[" + i + "]" ) , this . getWrappedDriver ( ) . findElement ( By . xpath ( "(//iframe)[" + i + "]" ) ) ) ; String nextFrameId = currFrameId . substring ( 0 , currFrameId . length ( ) - 1 ) + "-" + i + "]" ; frames . putAll ( getGeneratedHtmlSourceRecursive ( nextFrame , nextFrameId ) ) ; } return frames ; }
Gets the current html source from the dom for the every frame in the current window recursively
40,034
private static void removeWebDriverTempOldFolders ( ClientProperties properties ) { String tempFolder = System . getProperty ( "java.io.tmpdir" ) ; int numberOfDaysToKeepTempFolders = properties . getNumberOfDaysToKeepTempFolders ( ) ; if ( numberOfDaysToKeepTempFolders < 0 ) { numberOfDaysToKeepTempFolders = 7 ; } List < String > tempFolderNameContainsList = new ArrayList < String > ( ) ; tempFolderNameContainsList . add ( "anonymous" ) ; tempFolderNameContainsList . add ( "scoped_dir" ) ; tempFolderNameContainsList . add ( "webdriver-ie" ) ; String tempFolderNameContainsListFromProp = properties . getTempFolderNameContainsList ( ) ; if ( tempFolderNameContainsListFromProp != null ) { String [ ] tempFolderNameContainsListFromPropSpit = tempFolderNameContainsListFromProp . split ( "," ) ; for ( String name : tempFolderNameContainsListFromPropSpit ) { tempFolderNameContainsList . add ( name ) ; } } removeFolders ( tempFolder , tempFolderNameContainsList , numberOfDaysToKeepTempFolders ) ; }
This method cleans out folders where the WebDriver temp information is stored .
40,035
private final static void removeFolders ( String folder , List < String > folderTemplates , int numberOfDaysToKeepTempFolders ) { long dateToRemoveFiledAfter = ( new Date ( ) ) . getTime ( ) - ( numberOfDaysToKeepTempFolders * MILLISECONDS_IN_DAY ) ; File tempFolder = new File ( folder ) ; File [ ] folderChildren = tempFolder . listFiles ( ) ; if ( null == folderChildren ) { log . debug ( "Folder '" + tempFolder . getName ( ) + "' was empty. Nothing to delete" ) ; return ; } for ( File currentFile : folderChildren ) { if ( currentFile . isDirectory ( ) ) { for ( String folderTemplate : folderTemplates ) { if ( currentFile . getName ( ) . contains ( folderTemplate ) && ( currentFile . lastModified ( ) < dateToRemoveFiledAfter ) ) { try { currentFile . delete ( ) ; FileUtils . deleteDirectory ( currentFile ) ; log . debug ( "Folder '" + currentFile . getName ( ) + "' deleted..." ) ; } catch ( Exception e ) { log . fatal ( "Error deleting folder '" + currentFile . getName ( ) + "'" ) ; } } } } } }
This method can be called to remove specific folders or set how long you want to keep the temp information .
40,036
static void runChildWithRetry ( Object runner , final FrameworkMethod method , RunNotifier notifier , int maxRetry ) { boolean doRetry = false ; Statement statement = invoke ( runner , "methodBlock" , method ) ; Description description = invoke ( runner , "describeChild" , method ) ; AtomicInteger count = new AtomicInteger ( maxRetry ) ; do { EachTestNotifier eachNotifier = new EachTestNotifier ( notifier , description ) ; eachNotifier . fireTestStarted ( ) ; try { statement . evaluate ( ) ; doRetry = false ; } catch ( AssumptionViolatedException thrown ) { doRetry = doRetry ( method , thrown , count ) ; if ( doRetry ) { description = RetriedTest . proxyFor ( description , thrown ) ; eachNotifier . fireTestIgnored ( ) ; } else { eachNotifier . addFailedAssumption ( thrown ) ; } } catch ( Throwable thrown ) { doRetry = doRetry ( method , thrown , count ) ; if ( doRetry ) { description = RetriedTest . proxyFor ( description , thrown ) ; eachNotifier . fireTestIgnored ( ) ; } else { eachNotifier . addFailure ( thrown ) ; } } finally { eachNotifier . fireTestFinished ( ) ; } } while ( doRetry ) ; }
Run the specified method retrying on failure .
40,037
static boolean doRetry ( FrameworkMethod method , Throwable thrown , AtomicInteger retryCounter ) { boolean doRetry = false ; if ( ( retryCounter . decrementAndGet ( ) > - 1 ) && isRetriable ( method , thrown ) ) { LOGGER . warn ( "### RETRY ### {}" , method ) ; doRetry = true ; } return doRetry ; }
Determine if the indicated failure should be retried .
40,038
static boolean isRetriable ( final FrameworkMethod method , final Throwable thrown ) { synchronized ( retryAnalyzerLoader ) { for ( JUnitRetryAnalyzer analyzer : retryAnalyzerLoader ) { if ( analyzer . retry ( method , thrown ) ) { return true ; } } } return false ; }
Determine if the specified failed test should be retried .
40,039
public static Description describeChild ( Object target , Object child ) { Object runner = getRunnerForTarget ( target ) ; return invoke ( runner , "describeChild" , child ) ; }
Get the description of the indicated child object from the runner for the specified test class instance .
40,040
public static Class < ? > getInstanceClass ( Object instance ) { Class < ? > clazz = instance . getClass ( ) ; return ( instance instanceof Hooked ) ? clazz . getSuperclass ( ) : clazz ; }
Get class of specified test class instance .
40,041
static String getSubclassName ( Object testObj ) { Class < ? > testClass = testObj . getClass ( ) ; String testClassName = testClass . getSimpleName ( ) ; String testPackageName = testClass . getPackage ( ) . getName ( ) ; ReportsDirectory constant = ReportsDirectory . fromObject ( testObj ) ; switch ( constant ) { case FAILSAFE_2 : case FAILSAFE_3 : case SUREFIRE_2 : case SUREFIRE_3 : case SUREFIRE_4 : return testPackageName + ".Hooked" + testClassName ; default : return testClass . getCanonicalName ( ) + "Hooked" ; } }
Get fully - qualified name to use for hooked test class .
40,042
@ SuppressWarnings ( "unchecked" ) static < T > T invoke ( Object target , String methodName , Object ... parameters ) { Class < ? > [ ] parameterTypes = new Class < ? > [ parameters . length ] ; for ( int i = 0 ; i < parameters . length ; i ++ ) { parameterTypes [ i ] = parameters [ i ] . getClass ( ) ; } Throwable thrown = null ; for ( Class < ? > current = target . getClass ( ) ; current != null ; current = current . getSuperclass ( ) ) { try { Method method = current . getDeclaredMethod ( methodName , parameterTypes ) ; method . setAccessible ( true ) ; return ( T ) method . invoke ( target , parameters ) ; } catch ( NoSuchMethodException e ) { thrown = e ; } catch ( SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { thrown = e ; break ; } } throw UncheckedThrow . throwUnchecked ( thrown ) ; }
Invoke the named method with the specified parameters on the specified target object .
40,043
static Field getDeclaredField ( Object target , String name ) throws NoSuchFieldException { Throwable thrown = null ; for ( Class < ? > current = target . getClass ( ) ; current != null ; current = current . getSuperclass ( ) ) { try { return current . getDeclaredField ( name ) ; } catch ( NoSuchFieldException e ) { thrown = e ; } catch ( SecurityException e ) { thrown = e ; break ; } } throw UncheckedThrow . throwUnchecked ( thrown ) ; }
Get the specified field of the supplied object .
40,044
@ SuppressWarnings ( "unchecked" ) static < T > T getFieldValue ( Object target , String name ) throws IllegalAccessException , NoSuchFieldException , SecurityException { Field field = getDeclaredField ( target , name ) ; field . setAccessible ( true ) ; return ( T ) field . get ( target ) ; }
Get the value of the specified field from the supplied object .
40,045
static void setFieldValue ( Object target , String name , Object value ) throws IllegalAccessException , NoSuchFieldException , SecurityException { Field field = getDeclaredField ( target , name ) ; field . setAccessible ( true ) ; field . set ( target , value ) ; }
Set the value of the specified field of the supplied object .
40,046
@ SuppressWarnings ( "unchecked" ) public static < T extends TestRule > Optional < T > getAttachedRule ( RuleChain ruleChain , Class < T > ruleType ) { for ( TestRule rule : getRuleList ( ruleChain ) ) { if ( rule . getClass ( ) == ruleType ) { return Optional . of ( ( T ) rule ) ; } } return Optional . absent ( ) ; }
Get reference to an instance of the specified test rule type on the supplied rule chain .
40,047
@ SuppressWarnings ( "unchecked" ) private static List < TestRule > getRuleList ( RuleChain ruleChain ) { Field ruleChainList ; try { String fieldName = JUnitConfig . getConfig ( ) . getString ( JUnitSettings . RULE_CHAIN_LIST . key ( ) ) ; ruleChainList = RuleChain . class . getDeclaredField ( fieldName ) ; ruleChainList . setAccessible ( true ) ; return ( List < TestRule > ) ruleChainList . get ( ruleChain ) ; } catch ( NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e ) { throw UncheckedThrow . throwUnchecked ( e ) ; } }
Get the list of test rules from the specified rule chain .
40,048
private static void applyTimeout ( FrameworkMethod method ) { if ( LifecycleHooks . getConfig ( ) . containsKey ( JUnitSettings . TEST_TIMEOUT . key ( ) ) ) { long defaultTimeout = LifecycleHooks . getConfig ( ) . getLong ( JUnitSettings . TEST_TIMEOUT . key ( ) ) ; Test annotation = method . getAnnotation ( Test . class ) ; if ( ( annotation != null ) && ( annotation . timeout ( ) < defaultTimeout ) ) { MutableTest . proxyFor ( method . getMethod ( ) ) . setTimeout ( defaultTimeout ) ; } } }
If configured for default test timeout apply the timeout value to the specified framework method if it doesn t already specify a longer timeout interval .
40,049
public Optional < Path > captureArtifact ( Throwable reason ) { if ( ! provider . canGetArtifact ( getInstance ( ) ) ) { return Optional . absent ( ) ; } byte [ ] artifact = provider . getArtifact ( getInstance ( ) , reason ) ; if ( ( artifact == null ) || ( artifact . length == 0 ) ) { return Optional . absent ( ) ; } Path collectionPath = getCollectionPath ( ) ; if ( ! collectionPath . toFile ( ) . exists ( ) ) { try { Files . createDirectories ( collectionPath ) ; } catch ( IOException e ) { if ( provider . getLogger ( ) != null ) { String messageTemplate = "Unable to create collection directory ({}); no artifact was captured" ; provider . getLogger ( ) . warn ( messageTemplate , collectionPath , e ) ; } return Optional . absent ( ) ; } } Path artifactPath ; try { artifactPath = PathUtils . getNextPath ( collectionPath , getArtifactBaseName ( ) , provider . getArtifactExtension ( ) ) ; } catch ( IOException e ) { if ( provider . getLogger ( ) != null ) { provider . getLogger ( ) . warn ( "Unable to get output path; no artifact was captured" , e ) ; } return Optional . absent ( ) ; } try { if ( provider . getLogger ( ) != null ) { provider . getLogger ( ) . info ( "Saving captured artifact to ({})." , artifactPath ) ; } Files . write ( artifactPath , artifact ) ; } catch ( IOException e ) { if ( provider . getLogger ( ) != null ) { provider . getLogger ( ) . warn ( "I/O error saving to ({}); no artifact was captured" , artifactPath , e ) ; } return Optional . absent ( ) ; } recordArtifactPath ( artifactPath ) ; return Optional . of ( artifactPath ) ; }
Capture artifact from the current test result context .
40,050
private Path getCollectionPath ( ) { Path collectionPath = PathUtils . ReportsDirectory . getPathForObject ( getInstance ( ) ) ; return collectionPath . resolve ( provider . getArtifactPath ( getInstance ( ) ) ) ; }
Get path of directory at which to store artifacts .
40,051
public Optional < List < Path > > retrieveArtifactPaths ( ) { if ( artifactPaths . isEmpty ( ) ) { return Optional . absent ( ) ; } else { return Optional . of ( artifactPaths ) ; } }
Retrieve the paths of artifacts that were stored in the indicated test result .
40,052
@ SuppressWarnings ( "unchecked" ) public static < S extends ArtifactCollector < ? extends ArtifactType > > Optional < S > getWatcher ( Description description , Class < S > watcherType ) { List < ArtifactCollector < ? extends ArtifactType > > watcherList = watcherMap . get ( description ) ; if ( watcherList != null ) { for ( ArtifactCollector < ? extends ArtifactType > watcher : watcherList ) { if ( watcher . getClass ( ) == watcherType ) { return Optional . of ( ( S ) watcher ) ; } } } return Optional . absent ( ) ; }
Get reference to an instance of the specified watcher type associated with the described method .
40,053
public static boolean isParticleMethod ( FrameworkMethod method ) { return ( ( null != method . getAnnotation ( Test . class ) ) || ( null != method . getAnnotation ( Before . class ) ) || ( null != method . getAnnotation ( After . class ) ) || ( null != method . getAnnotation ( BeforeClass . class ) ) || ( null != method . getAnnotation ( AfterClass . class ) ) ) ; }
Determine if the specified method is a test or configuration method .
40,054
public static Packet build ( IoBuffer buffer ) { if ( buffer . hasArray ( ) ) { return new Packet ( buffer . array ( ) ) ; } byte [ ] buf = new byte [ buffer . remaining ( ) ] ; buffer . get ( buf ) ; return new Packet ( buf ) ; }
Builds the packet which just wraps the IoBuffer .
40,055
public void addPayload ( IoBuffer additionalPayload ) { if ( payload == null ) { payload = IoBuffer . allocate ( additionalPayload . remaining ( ) ) ; payload . setAutoExpand ( true ) ; } this . payload . put ( additionalPayload ) ; }
Adds additional payload data .
40,056
private HandshakeResponse buildHandshakeResponse ( WebSocketConnection conn , String clientKey ) throws WebSocketException { if ( log . isDebugEnabled ( ) ) { log . debug ( "buildHandshakeResponse: {} client key: {}" , conn , clientKey ) ; } byte [ ] accept ; try { MessageDigest md = MessageDigest . getInstance ( "SHA1" ) ; accept = Base64 . encode ( md . digest ( ( clientKey + Constants . WEBSOCKET_MAGIC_STRING ) . getBytes ( ) ) ) ; } catch ( NoSuchAlgorithmException e ) { throw new WebSocketException ( "Algorithm is missing" ) ; } IoBuffer buf = IoBuffer . allocate ( 308 ) ; buf . setAutoExpand ( true ) ; buf . put ( "HTTP/1.1 101 Switching Protocols" . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; buf . put ( "Upgrade: websocket" . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; buf . put ( "Connection: Upgrade" . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; buf . put ( "Server: Red5" . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; buf . put ( "Sec-WebSocket-Version-Server: 13" . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; buf . put ( String . format ( "Sec-WebSocket-Origin: %s" , conn . getOrigin ( ) ) . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; buf . put ( String . format ( "Sec-WebSocket-Location: %s" , conn . getHost ( ) ) . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; if ( conn . hasExtensions ( ) ) { buf . put ( String . format ( "Sec-WebSocket-Extensions: %s" , conn . getExtensionsAsString ( ) ) . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; } if ( conn . hasProtocol ( ) ) { buf . put ( String . format ( "Sec-WebSocket-Protocol: %s" , conn . getProtocol ( ) ) . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; } buf . put ( String . format ( "Sec-WebSocket-Accept: %s" , new String ( accept ) ) . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; buf . put ( Constants . CRLF ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Handshake response size: {}" , buf . limit ( ) ) ; } return new HandshakeResponse ( buf ) ; }
Build a handshake response based on the given client key .
40,057
private HandshakeResponse build400Response ( WebSocketConnection conn ) throws WebSocketException { if ( log . isDebugEnabled ( ) ) { log . debug ( "build400Response: {}" , conn ) ; } IoBuffer buf = IoBuffer . allocate ( 32 ) ; buf . setAutoExpand ( true ) ; buf . put ( "HTTP/1.1 400 Bad Request" . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; buf . put ( "Sec-WebSocket-Version-Server: 13" . getBytes ( ) ) ; buf . put ( Constants . CRLF ) ; buf . put ( Constants . CRLF ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Handshake error response size: {}" , buf . limit ( ) ) ; } return new HandshakeResponse ( buf ) ; }
Build an HTTP 400 Bad Request response .
40,058
public void receive ( WSMessage message ) { log . trace ( "receive message" ) ; if ( isConnected ( ) ) { WebSocketPlugin plugin = ( WebSocketPlugin ) PluginRegistry . getPlugin ( "WebSocketPlugin" ) ; Optional < WebSocketScopeManager > optional = Optional . ofNullable ( ( WebSocketScopeManager ) session . getAttribute ( Constants . MANAGER ) ) ; WebSocketScopeManager manager = optional . isPresent ( ) ? optional . get ( ) : plugin . getManager ( path ) ; WebSocketScope scope = manager . getScope ( path ) ; scope . onMessage ( message ) ; } else { log . warn ( "Not connected" ) ; } }
Receive data from a client .
40,059
public void sendHandshakeResponse ( HandshakeResponse wsResponse ) { log . debug ( "Writing handshake on session: {}" , session . getId ( ) ) ; handshakeWriteFuture = session . write ( wsResponse ) ; handshakeWriteFuture . addListener ( new IoFutureListener < WriteFuture > ( ) { public void operationComplete ( WriteFuture future ) { IoSession sess = future . getSession ( ) ; if ( future . isWritten ( ) ) { log . debug ( "Handshake write success! {}" , sess . getId ( ) ) ; sess . setAttribute ( Constants . HANDSHAKE_COMPLETE ) ; if ( connected . compareAndSet ( false , true ) ) { try { queue . forEach ( entry -> { sess . write ( entry ) ; queue . remove ( entry ) ; } ) ; } catch ( Exception e ) { log . warn ( "Exception draining queued packets on session: {}" , sess . getId ( ) , e ) ; } } } else { log . warn ( "Handshake write failed from: {} to: {}" , sess . getLocalAddress ( ) , sess . getRemoteAddress ( ) ) ; } } } ) ; }
Sends the handshake response .
40,060
public void send ( Packet packet ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "send packet: {}" , packet ) ; } if ( session . containsAttribute ( Constants . HANDSHAKE_COMPLETE ) ) { try { queue . forEach ( entry -> { session . write ( entry ) ; queue . remove ( entry ) ; } ) ; } catch ( Exception e ) { log . warn ( "Exception draining queued packets on session: {}" , session . getId ( ) , e ) ; } session . write ( packet ) ; } else { if ( handshakeWriteFuture != null ) { log . warn ( "Handshake is not complete yet on session: {} written? {}" , session . getId ( ) , handshakeWriteFuture . isWritten ( ) , handshakeWriteFuture . getException ( ) ) ; } else { log . warn ( "Handshake is not complete yet on session: {}" , session . getId ( ) ) ; } MessageType type = packet . getType ( ) ; if ( type != MessageType . PING && type != MessageType . PONG ) { log . info ( "Placing {} message in session: {} queue" , type , session . getId ( ) ) ; queue . offer ( packet ) ; } } }
Sends WebSocket packet to the client .
40,061
public void send ( String data ) throws UnsupportedEncodingException { log . trace ( "send message: {}" , data ) ; if ( StringUtils . isNotBlank ( data ) ) { send ( Packet . build ( data . getBytes ( "UTF8" ) , MessageType . TEXT ) ) ; } else { throw new UnsupportedEncodingException ( "Cannot send a null string" ) ; } }
Sends text to the client .
40,062
public void send ( byte [ ] buf ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "send binary: {}" , Arrays . toString ( buf ) ) ; } send ( Packet . build ( buf ) ) ; }
Sends binary data to the client .
40,063
public void sendPing ( byte [ ] buf ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "send ping: {}" , buf ) ; } send ( Packet . build ( buf , MessageType . PING ) ) ; }
Sends a ping to the client .
40,064
public void sendPong ( byte [ ] buf ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "send pong: {}" , buf ) ; } send ( Packet . build ( buf , MessageType . PONG ) ) ; }
Sends a pong back to the client ; normally in response to a ping .
40,065
public void close ( int statusCode , HandshakeResponse errResponse ) { log . warn ( "Closing connection with status: {}" , statusCode ) ; session . removeAttribute ( Constants . HANDSHAKE_COMPLETE ) ; queue . clear ( ) ; session . write ( errResponse ) ; if ( WebSocketTransport . isNiceClose ( ) ) { IoBuffer buf = IoBuffer . allocate ( 16 ) ; buf . setAutoExpand ( true ) ; buf . putUnsigned ( ( short ) statusCode ) ; try { if ( statusCode == 1008 ) { buf . put ( "Policy Violation" . getBytes ( "UTF8" ) ) ; } else { buf . put ( "Protocol error" . getBytes ( "UTF8" ) ) ; } } catch ( Exception e ) { } buf . flip ( ) ; byte [ ] errBytes = new byte [ buf . remaining ( ) ] ; buf . get ( errBytes ) ; Packet packet = Packet . build ( errBytes , MessageType . CLOSE ) ; WriteFuture writeFuture = session . write ( packet ) ; writeFuture . addListener ( new IoFutureListener < WriteFuture > ( ) { public void operationComplete ( WriteFuture future ) { if ( future . isWritten ( ) ) { log . debug ( "Close message written" ) ; session . setAttribute ( Constants . STATUS_CLOSE_WRITTEN , Boolean . TRUE ) ; } future . removeListener ( this ) ; } } ) ; CloseFuture closeFuture = session . closeOnFlush ( ) ; closeFuture . addListener ( new IoFutureListener < CloseFuture > ( ) { public void operationComplete ( CloseFuture future ) { if ( future . isClosed ( ) ) { log . debug ( "Connection is closed" ) ; } else { log . debug ( "Connection is not yet closed" ) ; } future . removeListener ( this ) ; } } ) ; } else { CloseFuture closeFuture = session . closeNow ( ) ; closeFuture . addListener ( new IoFutureListener < CloseFuture > ( ) { public void operationComplete ( CloseFuture future ) { if ( future . isClosed ( ) ) { log . debug ( "Connection is closed" ) ; } else { log . debug ( "Connection is not yet closed" ) ; } future . removeListener ( this ) ; } } ) ; } log . debug ( "Close complete" ) ; }
Close with an associated error status .
40,066
public String getExtensionsAsString ( ) { String extensionsList = null ; if ( extensions != null ) { StringBuilder sb = new StringBuilder ( ) ; for ( String key : extensions . keySet ( ) ) { sb . append ( key ) ; sb . append ( "; " ) ; } extensionsList = sb . toString ( ) . trim ( ) ; } return extensionsList ; }
Returns the extensions list as a comma separated string as specified by the rfc .
40,067
public boolean isEnabled ( String path ) { if ( path . startsWith ( "/" ) ) { int roomSlashPos = path . indexOf ( '/' , 1 ) ; if ( roomSlashPos == - 1 ) { path = path . substring ( 1 ) ; } else { path = path . substring ( 1 , roomSlashPos ) ; } } boolean enabled = activeRooms . contains ( path ) ; log . debug ( "Enabled check on path: {} enabled: {}" , path , enabled ) ; return enabled ; }
Returns the enable state of a given path .
40,068
public void addScope ( IScope scope ) { String app = scope . getName ( ) ; activeRooms . add ( app ) ; IContext ctx = scope . getContext ( ) ; if ( ctx != null && ctx . hasBean ( "webSocketScopeDefault" ) ) { log . debug ( "WebSocket scope found in context" ) ; WebSocketScope wsScope = ( WebSocketScope ) scope . getContext ( ) . getBean ( "webSocketScopeDefault" ) ; if ( wsScope != null ) { log . trace ( "Default WebSocketScope has {} listeners" , wsScope . getListeners ( ) . size ( ) ) ; } scopes . put ( String . format ( "/%s" , app ) , wsScope ) ; } else { log . debug ( "Creating a new scope" ) ; WebSocketScope wsScope = new WebSocketScope ( ) ; wsScope . setScope ( scope ) ; wsScope . setPath ( String . format ( "/%s" , app ) ) ; if ( wsScope . getListeners ( ) . isEmpty ( ) ) { log . debug ( "adding default listener" ) ; wsScope . addListener ( new DefaultWebSocketDataListener ( ) ) ; } notifyListeners ( WebSocketEvent . SCOPE_CREATED , wsScope ) ; addWebSocketScope ( wsScope ) ; } }
Adds a scope to the enabled applications .
40,069
public void addWebSocketScope ( WebSocketScope webSocketScope ) { String path = webSocketScope . getPath ( ) ; if ( scopes . putIfAbsent ( path , webSocketScope ) == null ) { log . info ( "addWebSocketScope: {}" , webSocketScope ) ; notifyListeners ( WebSocketEvent . SCOPE_ADDED , webSocketScope ) ; } }
Adds a websocket scope .
40,070
public void removeWebSocketScope ( WebSocketScope webSocketScope ) { log . info ( "removeWebSocketScope: {}" , webSocketScope ) ; WebSocketScope wsScope = scopes . remove ( webSocketScope . getPath ( ) ) ; if ( wsScope != null ) { notifyListeners ( WebSocketEvent . SCOPE_REMOVED , wsScope ) ; } }
Removes a websocket scope .
40,071
public void addConnection ( WebSocketConnection conn ) { WebSocketScope scope = getScope ( conn ) ; scope . addConnection ( conn ) ; }
Add the connection on scope .
40,072
public void addListener ( IWebSocketDataListener listener , String path ) { log . trace ( "addListener: {}" , listener ) ; WebSocketScope scope = getScope ( path ) ; if ( scope != null ) { scope . addListener ( listener ) ; } else { log . info ( "Scope not found for path: {}" , path ) ; } }
Add the listener on scope via its path .
40,073
public void removeListener ( IWebSocketDataListener listener , String path ) { log . trace ( "removeListener: {}" , listener ) ; WebSocketScope scope = getScope ( path ) ; if ( scope != null ) { scope . removeListener ( listener ) ; if ( ! scope . isValid ( ) ) { removeWebSocketScope ( scope ) ; } } else { log . info ( "Scope not found for path: {}" , path ) ; } }
Remove listener from scope via its path .
40,074
public void makeScope ( String path ) { log . debug ( "makeScope: {}" , path ) ; WebSocketScope wsScope = null ; if ( ! scopes . containsKey ( path ) ) { wsScope = new WebSocketScope ( ) ; wsScope . setPath ( path ) ; notifyListeners ( WebSocketEvent . SCOPE_CREATED , wsScope ) ; addWebSocketScope ( wsScope ) ; log . debug ( "Use the IWebSocketScopeListener interface to be notified of new scopes" ) ; } else { log . debug ( "Scope already exists: {}" , path ) ; } }
Create a web socket scope . Use the IWebSocketScopeListener interface to configure the created scope .
40,075
public void makeScope ( IScope scope ) { log . debug ( "makeScope: {}" , scope ) ; String path = scope . getContextPath ( ) ; WebSocketScope wsScope = null ; if ( ! scopes . containsKey ( path ) ) { activeRooms . add ( scope . getName ( ) ) ; wsScope = new WebSocketScope ( ) ; wsScope . setPath ( path ) ; wsScope . setScope ( scope ) ; notifyListeners ( WebSocketEvent . SCOPE_CREATED , wsScope ) ; addWebSocketScope ( wsScope ) ; log . debug ( "Use the IWebSocketScopeListener interface to be notified of new scopes" ) ; } else { log . debug ( "Scope already exists: {}" , path ) ; } }
Create a web socket scope from a server IScope . Use the IWebSocketScopeListener interface to configure the created scope .
40,076
public WebSocketScope getScope ( String path ) { log . debug ( "getScope: {}" , path ) ; WebSocketScope scope = scopes . get ( path ) ; if ( scope == null ) { scope = scopes . get ( "default" ) ; } log . debug ( "Returning: {}" , scope ) ; return scope ; }
Get the corresponding scope .
40,077
private WebSocketScope getScope ( WebSocketConnection conn ) { if ( log . isTraceEnabled ( ) ) { log . trace ( "Scopes: {}" , scopes ) ; } log . debug ( "getScope: {}" , conn ) ; WebSocketScope wsScope ; String path = conn . getPath ( ) ; if ( ! scopes . containsKey ( path ) ) { if ( ! scopes . containsKey ( "default" ) ) { wsScope = new WebSocketScope ( ) ; wsScope . setPath ( path ) ; notifyListeners ( WebSocketEvent . SCOPE_CREATED , wsScope ) ; addWebSocketScope ( wsScope ) ; } else { path = "default" ; } } wsScope = scopes . get ( path ) ; log . debug ( "Returning: {}" , wsScope ) ; return wsScope ; }
Get the corresponding scope if none exists make new one .
40,078
public void setApplication ( IScope appScope ) { log . debug ( "Application scope: {}" , appScope ) ; this . appScope = appScope ; activeRooms . add ( appScope . getName ( ) ) ; }
Set the application scope for this manager .
40,079
public static IoBuffer encodeOutgoingData ( Packet packet ) { log . debug ( "encode outgoing: {}" , packet ) ; IoBuffer data = packet . getData ( ) ; int frameLen = data . limit ( ) ; IoBuffer buffer = IoBuffer . allocate ( frameLen + 2 , false ) ; buffer . setAutoExpand ( true ) ; byte frameInfo = ( byte ) ( 1 << 7 ) ; switch ( packet . getType ( ) ) { case TEXT : if ( log . isTraceEnabled ( ) ) { log . trace ( "Encoding text frame \r\n{}" , new String ( packet . getData ( ) . array ( ) ) ) ; } frameInfo = ( byte ) ( frameInfo | 1 ) ; break ; case BINARY : log . trace ( "Encoding binary frame" ) ; frameInfo = ( byte ) ( frameInfo | 2 ) ; break ; case CLOSE : frameInfo = ( byte ) ( frameInfo | 8 ) ; break ; case CONTINUATION : frameInfo = ( byte ) ( frameInfo | 0 ) ; break ; case PING : log . trace ( "ping out" ) ; frameInfo = ( byte ) ( frameInfo | 9 ) ; break ; case PONG : log . trace ( "pong out" ) ; frameInfo = ( byte ) ( frameInfo | 0xa ) ; break ; default : break ; } buffer . put ( frameInfo ) ; log . trace ( "Frame length {} " , frameLen ) ; if ( frameLen <= 125 ) { buffer . put ( ( byte ) ( ( byte ) frameLen & ( byte ) 0x7F ) ) ; } else if ( frameLen > 125 && frameLen <= 65535 ) { buffer . put ( ( byte ) ( ( byte ) 126 & ( byte ) 0x7F ) ) ; buffer . putShort ( ( short ) frameLen ) ; } else { buffer . put ( ( byte ) ( ( byte ) 127 & ( byte ) 0x7F ) ) ; buffer . putLong ( ( int ) frameLen ) ; } buffer . put ( data ) ; buffer . flip ( ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Encoded: {}" , buffer ) ; } return buffer ; }
Encode the in buffer according to the Section 5 . 2 . RFC 6455
40,080
public WebSocketScopeManager getManager ( String path ) { log . debug ( "getManager: {}" , path ) ; String [ ] parts = path . split ( "\\/" ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Path parts: {}" , Arrays . toString ( parts ) ) ; } if ( parts . length > 1 ) { String name = ! "default" . equals ( parts [ 1 ] ) ? parts [ 1 ] : ( ( parts . length >= 3 ) ? parts [ 2 ] : parts [ 1 ] ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Managers: {}" , managerMap . entrySet ( ) ) ; } for ( Entry < IScope , WebSocketScopeManager > entry : managerMap . entrySet ( ) ) { IScope appScope = entry . getKey ( ) ; if ( appScope . getName ( ) . equals ( name ) ) { log . debug ( "Application scope name matches path: {}" , name ) ; return entry . getValue ( ) ; } else if ( log . isTraceEnabled ( ) ) { log . trace ( "Application scope name: {} didnt match path: {}" , appScope . getName ( ) , name ) ; } } } return null ; }
Returns a WebSocketScopeManager for a given path .
40,081
public void register ( ) { log . info ( "Application scope: {}" , scope ) ; WebSocketScopeManager manager = ( ( WebSocketPlugin ) PluginRegistry . getPlugin ( "WebSocketPlugin" ) ) . getManager ( scope ) ; manager . setApplication ( scope ) ; log . info ( "WebSocket app added: {}" , scope . getName ( ) ) ; manager . addWebSocketScope ( this ) ; log . info ( "WebSocket scope added" ) ; }
Registers with the WebSocketScopeManager .
40,082
public void unregister ( ) { for ( WebSocketConnection conn : conns ) { conn . close ( ) ; } conns . clear ( ) ; for ( IWebSocketDataListener listener : listeners ) { listener . stop ( ) ; } listeners . clear ( ) ; }
Un - registers from the WebSocketScopeManager .
40,083
public void addConnection ( WebSocketConnection conn ) { conns . add ( conn ) ; for ( IWebSocketDataListener listener : listeners ) { listener . onWSConnect ( conn ) ; } }
Add new connection on scope .
40,084
public void setListeners ( Collection < IWebSocketDataListener > listeners ) { log . trace ( "setListeners: {}" , listeners ) ; this . listeners . addAll ( listeners ) ; }
Add new listeners on scope .
40,085
public void onMessage ( WSMessage message ) { log . trace ( "Listeners: {}" , listeners . size ( ) ) ; for ( IWebSocketDataListener listener : listeners ) { try { listener . onWSMessage ( message ) ; } catch ( Exception e ) { log . warn ( "onMessage exception" , e ) ; } } }
Message received from client and passed on to the listeners .
40,086
public static final long generateId ( ) { long id = 0 ; random . addSeedMaterial ( ThreadLocalRandom . current ( ) . nextLong ( ) ) ; byte [ ] bytes = new byte [ 16 ] ; random . nextBytes ( bytes ) ; for ( int i = 0 ; i < bytes . length ; i ++ ) { id += ( ( long ) bytes [ i ] & 0xffL ) << ( 8 * i ) ; } return id ; }
Returns a cryptographically generated id .
40,087
static public String capitalize ( String string0 ) { if ( string0 == null ) { return null ; } int length = string0 . length ( ) ; if ( length == 0 ) { return string0 ; } else if ( length == 1 ) { return string0 . toUpperCase ( ) ; } else { StringBuilder buf = new StringBuilder ( length ) ; buf . append ( string0 . substring ( 0 , 1 ) . toUpperCase ( ) ) ; buf . append ( string0 . substring ( 1 ) ) ; return buf . toString ( ) ; } }
Safely capitalizes a string by converting the first character to upper case . Handles null empty and strings of length of 1 or greater . For example this will convert joe to Joe . If the string is null this will return null . If the string is empty such as then it ll just return an empty string such as .
40,088
static public String uncapitalize ( String string0 ) { if ( string0 == null ) { return null ; } int length = string0 . length ( ) ; if ( length == 0 ) { return string0 ; } else if ( length == 1 ) { return string0 . toLowerCase ( ) ; } else { StringBuilder buf = new StringBuilder ( length ) ; buf . append ( string0 . substring ( 0 , 1 ) . toLowerCase ( ) ) ; buf . append ( string0 . substring ( 1 ) ) ; return buf . toString ( ) ; } }
Safely uncapitalizes a string by converting the first character to lower case . Handles null empty and strings of length of 1 or greater . For example this will convert Joe to joe . If the string is null this will return null . If the string is empty such as then it ll just return an empty string such as .
40,089
static public int indexOf ( String [ ] strings , String targetString ) { if ( strings == null ) return - 1 ; for ( int i = 0 ; i < strings . length ; i ++ ) { if ( strings [ i ] == null ) { if ( targetString == null ) { return i ; } } else { if ( targetString != null ) { if ( strings [ i ] . equals ( targetString ) ) { return i ; } } } } return - 1 ; }
Finds the first occurrence of the targetString in the array of strings . Returns - 1 if an occurrence wasn t found . This method will return true if a null is contained in the array and the targetString is also null .
40,090
static public String stripQuotes ( String string0 ) { if ( string0 . length ( ) == 0 ) { return string0 ; } if ( string0 . length ( ) > 1 && string0 . charAt ( 0 ) == '"' && string0 . charAt ( string0 . length ( ) - 1 ) == '"' ) { return string0 . substring ( 1 , string0 . length ( ) - 1 ) ; } else if ( string0 . charAt ( 0 ) == '"' ) { string0 = string0 . substring ( 1 ) ; } else if ( string0 . charAt ( string0 . length ( ) - 1 ) == '"' ) { string0 = string0 . substring ( 0 , string0 . length ( ) - 1 ) ; } return string0 ; }
If present this method will strip off the leading and trailing character in the string parameter . For example 10958 will becomes just 10958 .
40,091
static public boolean containsOnlyDigits ( String string0 ) { for ( int i = 0 ; i < string0 . length ( ) ; i ++ ) { if ( ! Character . isDigit ( string0 . charAt ( i ) ) ) { return false ; } } return true ; }
Checks if a string contains only digits .
40,092
static public String [ ] split ( String str , char delim ) { if ( str == null ) { throw new NullPointerException ( "str can't be null" ) ; } StringTokenizer st = new StringTokenizer ( str , String . valueOf ( delim ) ) ; int n = st . countTokens ( ) ; String [ ] s = new String [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { s [ i ] = st . nextToken ( ) ; } return s ; }
Splits a string around matches of the given delimiter character .
40,093
public final static String formatForPrint ( String input ) { if ( input . length ( ) > 60 ) { StringBuffer tmp = new StringBuffer ( input . substring ( 0 , 60 ) ) ; tmp . append ( "&" ) ; input = tmp . toString ( ) ; } return input ; }
Used to print out a string for error messages chops is off at 60 chars for historical reasons .
40,094
public static String [ ] toStringArray ( Object [ ] objArray ) { int idx ; int len = objArray . length ; String [ ] strArray = new String [ len ] ; for ( idx = 0 ; idx < len ; idx ++ ) { strArray [ idx ] = objArray [ idx ] . toString ( ) ; } return strArray ; }
A method that receive an array of Objects and return a String array representation of that array .
40,095
public static byte [ ] getAsciiBytes ( String input ) { char [ ] c = input . toCharArray ( ) ; byte [ ] b = new byte [ c . length ] ; for ( int i = 0 ; i < c . length ; i ++ ) { b [ i ] = ( byte ) ( c [ i ] & 0x007F ) ; } return b ; }
Get 7 - bit ASCII character array from input String . The lower 7 bits of each character in the input string is assumed to be the ASCII character value .
40,096
public static String trimTrailing ( String str ) { if ( str == null ) { return null ; } int len = str . length ( ) ; for ( ; len > 0 ; len -- ) { if ( ! Character . isWhitespace ( str . charAt ( len - 1 ) ) ) { break ; } } return str . substring ( 0 , len ) ; }
Trim off trailing blanks but not leading blanks
40,097
public static String truncate ( String value , int length ) { if ( value != null && value . length ( ) > length ) { value = value . substring ( 0 , length ) ; } return value ; }
Truncate a String to the given length with no warnings or error raised if it is bigger .
40,098
public static String hexDump ( String prefix , byte [ ] data ) { byte byte_value ; StringBuffer str = new StringBuffer ( data . length * 3 ) ; str . append ( prefix ) ; for ( int i = 0 ; i < data . length ; i += 16 ) { String offset = Integer . toHexString ( i ) ; str . append ( " " ) ; for ( int offlen = offset . length ( ) ; offlen < 8 ; offlen ++ ) { str . append ( "0" ) ; } str . append ( offset ) ; str . append ( ":" ) ; for ( int j = 0 ; ( j < 16 ) && ( ( i + j ) < data . length ) ; j ++ ) { byte_value = data [ i + j ] ; if ( ( j % 2 ) == 0 ) { str . append ( " " ) ; } byte high_nibble = ( byte ) ( ( byte_value & 0xf0 ) >>> 4 ) ; byte low_nibble = ( byte ) ( byte_value & 0x0f ) ; str . append ( HEX_TABLE [ high_nibble ] ) ; str . append ( HEX_TABLE [ low_nibble ] ) ; } if ( i + 16 > data . length ) { int last_row_byte_count = data . length % 16 ; int num_bytes_short = 16 - last_row_byte_count ; int num_spaces = ( num_bytes_short * 2 ) + ( 7 - ( last_row_byte_count / 2 ) ) ; for ( int v = 0 ; v < num_spaces ; v ++ ) { str . append ( " " ) ; } } str . append ( " " ) ; for ( int j = 0 ; ( j < 16 ) && ( ( i + j ) < data . length ) ; j ++ ) { char char_value = ( char ) data [ i + j ] ; if ( isPrintableChar ( char_value ) ) { str . append ( String . valueOf ( char_value ) ) ; } else { str . append ( "." ) ; } } str . append ( "\n" ) ; } str . deleteCharAt ( str . length ( ) - 1 ) ; return ( str . toString ( ) ) ; }
Convert a byte array to a human - readable String for debugging purposes .
40,099
static String quoteString ( String source , char quote ) { StringBuffer quoted = new StringBuffer ( source . length ( ) + 2 ) ; quoted . append ( quote ) ; for ( int i = 0 ; i < source . length ( ) ; i ++ ) { char c = source . charAt ( i ) ; if ( c == quote ) quoted . append ( quote ) ; quoted . append ( c ) ; } quoted . append ( quote ) ; return quoted . toString ( ) ; }
Quote a string so that it can be used as an identifier or a string literal in SQL statements . Identifiers are surrounded by double quotes and string literals are surrounded by single quotes . If the string contains quote characters they are escaped .