idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
16,000
public void deleteTemporaryFiles ( ) { if ( ! shouldReap ( ) ) { return ; } for ( File file : temporaryFiles ) { try { FileHandler . delete ( file ) ; } catch ( WebDriverException e ) { } } }
Perform the operation that a shutdown hook would have .
16,001
public Proxy setAutodetect ( boolean autodetect ) { if ( this . autodetect == autodetect ) { return this ; } if ( autodetect ) { verifyProxyTypeCompatibility ( ProxyType . AUTODETECT ) ; this . proxyType = ProxyType . AUTODETECT ; } else { this . proxyType = ProxyType . UNSPECIFIED ; } this . autodetect = autodetect ; return this ; }
Specifies whether to autodetect proxy settings .
16,002
public Proxy setSslProxy ( String sslProxy ) { verifyProxyTypeCompatibility ( ProxyType . MANUAL ) ; this . proxyType = ProxyType . MANUAL ; this . sslProxy = sslProxy ; return this ; }
Specify which proxy to use for SSL connections .
16,003
public Proxy setSocksProxy ( String socksProxy ) { verifyProxyTypeCompatibility ( ProxyType . MANUAL ) ; this . proxyType = ProxyType . MANUAL ; this . socksProxy = socksProxy ; return this ; }
Specifies which proxy to use for SOCKS .
16,004
public Proxy setSocksUsername ( String username ) { verifyProxyTypeCompatibility ( ProxyType . MANUAL ) ; this . proxyType = ProxyType . MANUAL ; this . socksUsername = username ; return this ; }
Specifies a username for the SOCKS proxy . Supported by SOCKS v5 and above .
16,005
public Proxy setSocksPassword ( String password ) { verifyProxyTypeCompatibility ( ProxyType . MANUAL ) ; this . proxyType = ProxyType . MANUAL ; this . socksPassword = password ; return this ; }
Specifies a password for the SOCKS proxy . Supported by SOCKS v5 and above .
16,006
public static Level normalize ( Level level ) { if ( levelMap . containsKey ( level . intValue ( ) ) ) { return levelMap . get ( level . intValue ( ) ) ; } else if ( level . intValue ( ) >= Level . SEVERE . intValue ( ) ) { return Level . SEVERE ; } else if ( level . intValue ( ) >= Level . WARNING . intValue ( ) ) { return Level . WARNING ; } else if ( level . intValue ( ) >= Level . INFO . intValue ( ) ) { return Level . INFO ; } else { return Level . FINE ; } }
Normalizes the given level to one of those supported by Selenium .
16,007
public static String getName ( Level level ) { Level normalized = normalize ( level ) ; return normalized == Level . FINE ? DEBUG : normalized . getName ( ) ; }
Converts the JDK level to a name supported by Selenium .
16,008
public void defineCommand ( String name , HttpMethod method , String pathPattern ) { defineCommand ( name , new CommandSpec ( method , pathPattern ) ) ; }
Defines a new command mapping .
16,009
public WebElement findElement ( SearchContext context ) { List < WebElement > allElements = findElements ( context ) ; if ( allElements == null || allElements . isEmpty ( ) ) { throw new NoSuchElementException ( "Cannot locate an element using " + toString ( ) ) ; } return allElements . get ( 0 ) ; }
Find a single element . Override this method if necessary .
16,010
public static Map < String , SessionLogs > getSessionLogs ( Map < String , Object > rawSessionMap ) { Map < String , SessionLogs > sessionLogsMap = new HashMap < > ( ) ; for ( Map . Entry < String , Object > entry : rawSessionMap . entrySet ( ) ) { String sessionId = entry . getKey ( ) ; if ( ! ( entry . getValue ( ) instanceof Map ) ) { throw new InvalidArgumentException ( "Expected value to be an object: " + entry . getValue ( ) ) ; } @ SuppressWarnings ( "unchecked" ) Map < String , Object > value = ( Map < String , Object > ) entry . getValue ( ) ; SessionLogs sessionLogs = SessionLogs . fromJSON ( value ) ; sessionLogsMap . put ( sessionId , sessionLogs ) ; } return sessionLogsMap ; }
Creates a session logs map with session logs mapped to session IDs given a raw session log map as a JSON object .
16,011
public void setEnvironmentVariables ( Map < String , String > environment ) { for ( Map . Entry < String , String > entry : environment . entrySet ( ) ) { setEnvironmentVariable ( entry . getKey ( ) , entry . getValue ( ) ) ; } }
Adds the specified environment variables .
16,012
public MutableCapabilities merge ( Capabilities extraCapabilities ) { if ( extraCapabilities == null ) { return this ; } extraCapabilities . asMap ( ) . forEach ( this :: setCapability ) ; return this ; }
Merge the extra capabilities provided into this DesiredCapabilities instance . If capabilities with the same name exist in this instance they will be overridden by the values from the extraCapabilities object .
16,013
public InetAddress getIp4NonLoopbackAddressOfThisMachine ( ) { for ( NetworkInterface iface : networkInterfaceProvider . getNetworkInterfaces ( ) ) { final InetAddress ip4NonLoopback = iface . getIp4NonLoopBackOnly ( ) ; if ( ip4NonLoopback != null ) { return ip4NonLoopback ; } } throw new WebDriverException ( "Could not find a non-loopback ip4 address for this machine" ) ; }
Returns a non - loopback IP4 hostname of the local host .
16,014
public String obtainLoopbackIp4Address ( ) { final NetworkInterface networkInterface = getLoopBackAndIp4Only ( ) ; if ( networkInterface != null ) { return networkInterface . getIp4LoopbackOnly ( ) . getHostName ( ) ; } final String ipOfIp4LoopBack = getIpOfLoopBackIp4 ( ) ; if ( ipOfIp4LoopBack != null ) { return ipOfIp4LoopBack ; } if ( Platform . getCurrent ( ) . is ( Platform . UNIX ) ) { NetworkInterface linuxLoopback = networkInterfaceProvider . getLoInterface ( ) ; if ( linuxLoopback != null ) { final InetAddress netAddress = linuxLoopback . getIp4LoopbackOnly ( ) ; if ( netAddress != null ) { return netAddress . getHostAddress ( ) ; } } } throw new WebDriverException ( "Unable to resolve local loopback address, please file an issue with the full message of this error:\n" + getNetWorkDiags ( ) + "\n==== End of error message" ) ; }
Returns a single address that is guaranteed to resolve to an ipv4 representation of localhost This may either be a hostname or an ip address depending if we can guarantee what that the hostname will resolve to ip4 .
16,015
public String serialize ( ) { StringBuilder sb = new StringBuilder ( ) ; boolean first = true ; for ( String key : options . keySet ( ) ) { if ( first ) { first = false ; } else { sb . append ( ';' ) ; } sb . append ( key ) . append ( '=' ) . append ( options . get ( key ) ) ; } return sb . toString ( ) ; }
Serializes to the format name = value ; name = value .
16,016
public BrowserConfigurationOptions set ( String key , String value ) { if ( value != null ) { options . put ( key , value ) ; } return this ; }
Sets the given key to the given value unless the value is null . In that case no entry for the key is made .
16,017
public String executeCommandOnServlet ( String command ) { try { return getCommandResponseAsString ( command ) ; } catch ( IOException e ) { if ( e instanceof ConnectException ) { throw new SeleniumException ( e . getMessage ( ) , e ) ; } e . printStackTrace ( ) ; throw new UnsupportedOperationException ( "Catch body broken: IOException from " + command + " -> " + e , e ) ; } }
Sends the specified command string to the bridge servlet
16,018
public static String [ ] parseCSV ( String input ) { List < String > output = new ArrayList < > ( ) ; StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < input . length ( ) ; i ++ ) { char c = input . charAt ( i ) ; switch ( c ) { case ',' : output . add ( sb . toString ( ) ) ; sb = new StringBuffer ( ) ; continue ; case '\\' : i ++ ; c = input . charAt ( i ) ; default : sb . append ( c ) ; } } output . add ( sb . toString ( ) ) ; return output . toArray ( new String [ output . size ( ) ] ) ; }
Convert backslash - escaped comma - delimited string into String array . As described in SRC - CDP spec section 5 . 2 . 1 . 2 these strings are comma - delimited but commas can be escaped with a backslash \ . Backslashes can also be escaped as a double - backslash .
16,019
public void merge ( StandaloneConfiguration other ) { if ( other == null ) { return ; } if ( isMergeAble ( Integer . class , other . browserTimeout , browserTimeout ) ) { browserTimeout = other . browserTimeout ; } if ( isMergeAble ( Integer . class , other . jettyMaxThreads , jettyMaxThreads ) ) { jettyMaxThreads = other . jettyMaxThreads ; } if ( isMergeAble ( Integer . class , other . timeout , timeout ) ) { timeout = other . timeout ; } }
copy another configuration s values into this one if they are set .
16,020
public Map < String , Object > toJson ( ) { Map < String , Object > json = new HashMap < > ( ) ; json . put ( "browserTimeout" , browserTimeout ) ; json . put ( "debug" , debug ) ; json . put ( "jettyMaxThreads" , jettyMaxThreads ) ; json . put ( "log" , log ) ; json . put ( "host" , host ) ; json . put ( "port" , port ) ; json . put ( "role" , role ) ; json . put ( "timeout" , timeout ) ; serializeFields ( json ) ; return json . entrySet ( ) . stream ( ) . filter ( entry -> entry . getValue ( ) != null ) . collect ( toImmutableSortedMap ( natural ( ) , Map . Entry :: getKey , Map . Entry :: getValue ) ) ; }
Return a JsonElement representation of the configuration . Does not serialize nulls .
16,021
public static ExternalSessionKey fromResponseBody ( String responseBody ) throws NewSessionException { if ( responseBody != null && responseBody . startsWith ( "OK," ) ) { return new ExternalSessionKey ( responseBody . replace ( "OK," , "" ) ) ; } throw new NewSessionException ( "The server returned an error : " + responseBody ) ; }
extract the external key from the server response for a selenium1 new session request .
16,022
public < K extends Throwable > FluentWait < T > ignoreAll ( Collection < Class < ? extends K > > types ) { ignoredExceptions . addAll ( types ) ; return this ; }
Configures this instance to ignore specific types of exceptions while waiting for a condition . Any exceptions not whitelisted will be allowed to propagate terminating the wait .
16,023
private String tabConfig ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "<div type='config' class='content_detail'>" ) ; builder . append ( proxy . getConfig ( ) . toString ( "<p>%1$s: %2$s</p>" ) ) ; builder . append ( "</div>" ) ; return builder . toString ( ) ; }
content of the config tab .
16,024
private String tabBrowsers ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "<div type='browsers' class='content_detail'>" ) ; SlotsLines rcLines = new SlotsLines ( ) ; SlotsLines wdLines = new SlotsLines ( ) ; for ( TestSlot slot : proxy . getTestSlots ( ) ) { if ( slot . getProtocol ( ) == SeleniumProtocol . Selenium ) { rcLines . add ( slot ) ; } else { wdLines . add ( slot ) ; } } if ( rcLines . getLinesType ( ) . size ( ) != 0 ) { builder . append ( "<p class='protocol' >Remote Control (legacy)</p>" ) ; builder . append ( getLines ( rcLines ) ) ; } if ( wdLines . getLinesType ( ) . size ( ) != 0 ) { builder . append ( "<p class='protocol' >WebDriver</p>" ) ; builder . append ( getLines ( wdLines ) ) ; } builder . append ( "</div>" ) ; return builder . toString ( ) ; }
content of the browsers tab
16,025
private String getLines ( SlotsLines lines ) { StringBuilder builder = new StringBuilder ( ) ; for ( MiniCapability cap : lines . getLinesType ( ) ) { String icon = cap . getIcon ( ) ; String version = cap . getVersion ( ) ; builder . append ( "<p>" ) ; if ( version != null ) { builder . append ( "v:" ) . append ( version ) ; } for ( TestSlot s : lines . getLine ( cap ) ) { builder . append ( getSingleSlotHtml ( s , icon ) ) ; } builder . append ( "</p>" ) ; } return builder . toString ( ) ; }
the lines of icon representing the possible slots
16,026
private String nodeTabs ( ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "<div class='tabs'>" ) ; builder . append ( "<ul>" ) ; builder . append ( "<li class='tab' type='browsers'><a title='test slots' href='#'>Browsers</a></li>" ) ; builder . append ( "<li class='tab' type='config'><a title='node configuration' href='#'>Configuration</a></li>" ) ; builder . append ( "</ul>" ) ; builder . append ( "</div>" ) ; return builder . toString ( ) ; }
the tabs header .
16,027
public static String getPlatform ( RemoteProxy proxy ) { if ( proxy . getTestSlots ( ) . size ( ) == 0 ) { return "Unknown" ; } Platform res = getPlatform ( proxy . getTestSlots ( ) . get ( 0 ) ) ; for ( TestSlot slot : proxy . getTestSlots ( ) ) { Platform tmp = getPlatform ( slot ) ; if ( tmp != res ) { return "mixed OS" ; } res = tmp ; } if ( res == null ) { return "not specified" ; } return res . toString ( ) ; }
return the platform for the proxy . It should be the same for all slots of the proxy so checking that .
16,028
public void merge ( GridConfiguration other ) { if ( other == null ) { return ; } super . merge ( other ) ; if ( isMergeAble ( Integer . class , other . cleanUpCycle , cleanUpCycle ) ) { cleanUpCycle = other . cleanUpCycle ; } if ( isMergeAble ( Map . class , other . custom , custom ) ) { if ( custom == null ) { custom = new HashMap < > ( ) ; } custom . putAll ( other . custom ) ; } if ( isMergeAble ( Integer . class , other . maxSession , maxSession ) && other . maxSession > 0 ) { maxSession = other . maxSession ; } if ( isMergeAble ( List . class , other . servlets , servlets ) ) { servlets = other . servlets ; } if ( isMergeAble ( List . class , other . withoutServlets , withoutServlets ) ) { withoutServlets = other . withoutServlets ; } }
replaces this instance of configuration value with the other value if it s set .
16,029
public static Class < ? extends Servlet > createServlet ( String className ) { try { return Class . forName ( className ) . asSubclass ( Servlet . class ) ; } catch ( ClassNotFoundException e ) { log . warning ( "The specified class : " + className + " cannot be instantiated " + e . getMessage ( ) ) ; } return null ; }
Reflexion to create the servlet based on the class name . Returns null if the class cannot be instantiated .
16,030
protected void log ( SessionId sessionId , String commandName , Object toLog , When when ) { if ( ! logger . isLoggable ( level ) ) { return ; } String text = String . valueOf ( toLog ) ; if ( commandName . equals ( DriverCommand . EXECUTE_SCRIPT ) || commandName . equals ( DriverCommand . EXECUTE_ASYNC_SCRIPT ) ) { if ( text . length ( ) > 100 && Boolean . getBoolean ( "webdriver.remote.shorten_log_messages" ) ) { text = text . substring ( 0 , 100 ) + "..." ; } } switch ( when ) { case BEFORE : logger . log ( level , "Executing: " + commandName + " " + text ) ; break ; case AFTER : logger . log ( level , "Executed: " + text ) ; break ; case EXCEPTION : logger . log ( level , "Exception: " + text ) ; break ; default : logger . log ( level , text ) ; break ; } }
Override this to be notified at key points in the execution of a command .
16,031
public boolean isRunning ( ) { lock . lock ( ) ; try { return process != null && process . isRunning ( ) ; } catch ( IllegalThreadStateException e ) { return true ; } finally { lock . unlock ( ) ; } }
Checks whether the driver child process is currently running .
16,032
public void start ( ) throws IOException { lock . lock ( ) ; try { if ( process != null ) { return ; } process = new CommandLine ( this . executable , args . toArray ( new String [ ] { } ) ) ; process . setEnvironmentVariables ( environment ) ; process . copyOutputTo ( getOutputStream ( ) ) ; process . executeAsync ( ) ; waitUntilAvailable ( ) ; } finally { lock . unlock ( ) ; } }
Starts this service if it is not already running . This method will block until the server has been fully started and is ready to handle commands .
16,033
public void stop ( ) { lock . lock ( ) ; WebDriverException toThrow = null ; try { if ( process == null ) { return ; } if ( hasShutdownEndpoint ( ) ) { try { URL killUrl = new URL ( url . toString ( ) + "/shutdown" ) ; new UrlChecker ( ) . waitUntilUnavailable ( 3 , SECONDS , killUrl ) ; } catch ( MalformedURLException e ) { toThrow = new WebDriverException ( e ) ; } catch ( UrlChecker . TimeoutException e ) { toThrow = new WebDriverException ( "Timed out waiting for driver server to shutdown." , e ) ; } } process . destroy ( ) ; if ( getOutputStream ( ) instanceof FileOutputStream ) { try { getOutputStream ( ) . close ( ) ; } catch ( IOException e ) { } } } finally { process = null ; lock . unlock ( ) ; } if ( toThrow != null ) { throw toThrow ; } }
Stops this service if it is currently running . This method will attempt to block until the server has been fully shutdown .
16,034
public TouchActions singleTap ( WebElement onElement ) { if ( touchScreen != null ) { action . addAction ( new SingleTapAction ( touchScreen , ( Locatable ) onElement ) ) ; } tick ( touchPointer . createPointerDown ( 0 ) ) ; tick ( touchPointer . createPointerUp ( 0 ) ) ; return this ; }
Allows the execution of single tap on the screen analogous to click using a Mouse .
16,035
public TouchActions down ( int x , int y ) { if ( touchScreen != null ) { action . addAction ( new DownAction ( touchScreen , x , y ) ) ; } return this ; }
Allows the execution of the gesture down on the screen . It is typically the first of a sequence of touch gestures .
16,036
public TouchActions up ( int x , int y ) { if ( touchScreen != null ) { action . addAction ( new UpAction ( touchScreen , x , y ) ) ; } return this ; }
Allows the execution of the gesture up on the screen . It is typically the last of a sequence of touch gestures .
16,037
public TouchActions move ( int x , int y ) { if ( touchScreen != null ) { action . addAction ( new MoveAction ( touchScreen , x , y ) ) ; } return this ; }
Allows the execution of the gesture move on the screen .
16,038
public TouchActions scroll ( WebElement onElement , int xOffset , int yOffset ) { if ( touchScreen != null ) { action . addAction ( new ScrollAction ( touchScreen , ( Locatable ) onElement , xOffset , yOffset ) ) ; } return this ; }
Creates a scroll gesture that starts on a particular screen location .
16,039
public TouchActions doubleTap ( WebElement onElement ) { if ( touchScreen != null ) { action . addAction ( new DoubleTapAction ( touchScreen , ( Locatable ) onElement ) ) ; } return this ; }
Allows the execution of double tap on the screen analogous to double click using a Mouse .
16,040
public TouchActions longPress ( WebElement onElement ) { if ( touchScreen != null ) { action . addAction ( new LongPressAction ( touchScreen , ( Locatable ) onElement ) ) ; } return this ; }
Allows the execution of long press gestures .
16,041
public TouchActions scroll ( int xOffset , int yOffset ) { if ( touchScreen != null ) { action . addAction ( new ScrollAction ( touchScreen , xOffset , yOffset ) ) ; } return this ; }
Allows the view to be scrolled by an x and y offset .
16,042
public TouchActions flick ( int xSpeed , int ySpeed ) { if ( touchScreen != null ) { action . addAction ( new FlickAction ( touchScreen , xSpeed , ySpeed ) ) ; } return this ; }
Sends a flick gesture to the current view .
16,043
public TouchActions flick ( WebElement onElement , int xOffset , int yOffset , int speed ) { if ( touchScreen != null ) { action . addAction ( new FlickAction ( touchScreen , ( Locatable ) onElement , xOffset , yOffset , speed ) ) ; } return this ; }
Allows the execution of flick gestures starting in a location s element .
16,044
public LoggingPreferences addPreferences ( LoggingPreferences prefs ) { if ( prefs == null ) { return this ; } for ( String logType : prefs . getEnabledLogTypes ( ) ) { enable ( logType , prefs . getLevel ( logType ) ) ; } return this ; }
Adds the given logging preferences giving them precedence over existing preferences .
16,045
@ SuppressWarnings ( "unchecked" ) public T get ( ) { try { isLoaded ( ) ; return ( T ) this ; } catch ( Error e ) { load ( ) ; } isLoaded ( ) ; return ( T ) this ; }
Ensure that the component is currently loaded .
16,046
public void add ( RequestHandler request ) { lock . writeLock ( ) . lock ( ) ; try { newSessionRequests . add ( request ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
Adds a request handler to this queue .
16,047
public void processQueue ( Predicate < RequestHandler > handlerConsumer , Prioritizer prioritizer ) { Comparator < RequestHandler > comparator = prioritizer == null ? Ordering . allEqual ( ) :: compare : ( a , b ) -> prioritizer . compareTo ( a . getRequest ( ) . getDesiredCapabilities ( ) , b . getRequest ( ) . getDesiredCapabilities ( ) ) ; lock . writeLock ( ) . lock ( ) ; try { newSessionRequests . stream ( ) . sorted ( comparator ) . filter ( handlerConsumer ) . forEach ( requestHandler -> { if ( ! removeNewSessionRequest ( requestHandler ) ) { log . severe ( "Bug removing request " + requestHandler ) ; } } ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
Processes all the entries in this queue .
16,048
public boolean removeNewSessionRequest ( RequestHandler request ) { lock . writeLock ( ) . lock ( ) ; try { return newSessionRequests . remove ( request ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } }
Remove a specific request
16,049
public Iterable < DesiredCapabilities > getDesiredCapabilities ( ) { lock . readLock ( ) . lock ( ) ; try { return newSessionRequests . stream ( ) . map ( req -> new DesiredCapabilities ( req . getRequest ( ) . getDesiredCapabilities ( ) ) ) . collect ( Collectors . toList ( ) ) ; } finally { lock . readLock ( ) . unlock ( ) ; } }
Provides the desired capabilities of all the items in this queue .
16,050
public static RemoteCommand parse ( String inputLine ) { if ( null == inputLine ) throw new NullPointerException ( "inputLine can't be null" ) ; String [ ] values = inputLine . split ( "\\|" ) ; if ( values . length != NUMARGSINCLUDINGBOUNDARIES ) { throw new IllegalStateException ( "Cannot parse invalid line: " + inputLine + values . length ) ; } return new DefaultRemoteCommand ( values [ FIRSTINDEX ] , new String [ ] { values [ SECONDINDEX ] , values [ THIRDINDEX ] } ) ; }
Factory method to create a RemoteCommand from a wiki - style input string
16,051
public void addBrowser ( DesiredCapabilities cap , int instances ) { String s = cap . getBrowserName ( ) ; if ( s == null || "" . equals ( s ) ) { throw new InvalidParameterException ( cap + " does seems to be a valid browser." ) ; } if ( cap . getPlatform ( ) == null ) { cap . setPlatform ( Platform . getCurrent ( ) ) ; } cap . setCapability ( RegistrationRequest . MAX_INSTANCES , instances ) ; registrationRequest . getConfiguration ( ) . capabilities . add ( cap ) ; registrationRequest . getConfiguration ( ) . fixUpCapabilities ( ) ; }
Adding the browser described by the capability automatically finding out what platform the node is launched from
16,052
private GridHubConfiguration getHubConfiguration ( ) throws Exception { String hubApi = "http://" + registrationRequest . getConfiguration ( ) . getHubHost ( ) + ":" + registrationRequest . getConfiguration ( ) . getHubPort ( ) + "/grid/api/hub" ; URL api = new URL ( hubApi ) ; HttpClient client = httpClientFactory . createClient ( api ) ; String url = api . toExternalForm ( ) ; HttpRequest request = new HttpRequest ( GET , url ) ; HttpResponse response = client . execute ( request ) ; try ( Reader reader = new StringReader ( response . getContentString ( ) ) ; JsonInput jsonInput = new Json ( ) . newInput ( reader ) ) { return GridHubConfiguration . loadFromJSON ( jsonInput ) ; } }
uses the hub API to get some of its configuration .
16,053
public static Response success ( SessionId sessionId , Object value ) { Response response = new Response ( ) ; response . setSessionId ( sessionId != null ? sessionId . toString ( ) : null ) ; response . setValue ( value ) ; response . setStatus ( ErrorCodes . SUCCESS ) ; response . setState ( ErrorCodes . SUCCESS_STRING ) ; return response ; }
Creates a response object for a successful command execution .
16,054
public void createLogFileAndAddToMap ( SessionId sessionId ) throws IOException { File rcLogFile ; rcLogFile = File . createTempFile ( sessionId . toString ( ) , ".rclog" ) ; rcLogFile . deleteOnExit ( ) ; LogFile logFile = new LogFile ( rcLogFile . getAbsolutePath ( ) ) ; sessionToLogFileMap . put ( sessionId , logFile ) ; }
This creates log file object which represents logs in file form . This opens ObjectOutputStream which is used to write logRecords to log file and opens a ObjectInputStream which is used to read logRecords from the file .
16,055
private void assignRequestToProxy ( ) { while ( ! stop ) { try { testSessionAvailable . await ( 5 , TimeUnit . SECONDS ) ; newSessionQueue . processQueue ( this :: takeRequestHandler , getHub ( ) . getConfiguration ( ) . prioritizer ) ; LoggingManager . perSessionLogHandler ( ) . clearThreadTempLogs ( ) ; } catch ( InterruptedException e ) { LOG . info ( "Shutting down registry." ) ; } catch ( Throwable t ) { LOG . log ( Level . SEVERE , "Unhandled exception in Matcher thread." , t ) ; } } }
iterates the list of incoming session request to find a potential match in the list of proxies . If something changes in the registry the matcher iteration is stopped to account for that change .
16,056
private void release ( TestSession session , SessionTerminationReason reason ) { try { lock . lock ( ) ; boolean removed = activeTestSessions . remove ( session , reason ) ; if ( removed ) { fireMatcherStateChanged ( ) ; } } finally { lock . unlock ( ) ; } }
mark the session as finished for the registry . The resources that were associated to it are now free to be reserved by other tests
16,057
private static Executable locateFirefoxBinaryFromSystemProperty ( ) { String binaryName = System . getProperty ( FirefoxDriver . SystemProperty . BROWSER_BINARY ) ; if ( binaryName == null ) return null ; File binary = new File ( binaryName ) ; if ( binary . exists ( ) && ! binary . isDirectory ( ) ) return new Executable ( binary ) ; Platform current = Platform . getCurrent ( ) ; if ( current . is ( WINDOWS ) ) { if ( ! binaryName . endsWith ( ".exe" ) ) { binaryName += ".exe" ; } } else if ( current . is ( MAC ) ) { if ( ! binaryName . endsWith ( ".app" ) ) { binaryName += ".app" ; } binaryName += "/Contents/MacOS/firefox-bin" ; } binary = new File ( binaryName ) ; if ( binary . exists ( ) ) return new Executable ( binary ) ; throw new WebDriverException ( String . format ( "'%s' property set, but unable to locate the requested binary: %s" , FirefoxDriver . SystemProperty . BROWSER_BINARY , binaryName ) ) ; }
Locates the firefox binary from a system property . Will throw an exception if the binary cannot be found .
16,058
private static Stream < Executable > locateFirefoxBinariesFromPlatform ( ) { ImmutableList . Builder < Executable > executables = new ImmutableList . Builder < > ( ) ; Platform current = Platform . getCurrent ( ) ; if ( current . is ( WINDOWS ) ) { executables . addAll ( Stream . of ( "Mozilla Firefox\\firefox.exe" , "Firefox Developer Edition\\firefox.exe" , "Nightly\\firefox.exe" ) . map ( FirefoxBinary :: getPathsInProgramFiles ) . flatMap ( List :: stream ) . map ( File :: new ) . filter ( File :: exists ) . map ( Executable :: new ) . collect ( toList ( ) ) ) ; } else if ( current . is ( MAC ) ) { File binary = new File ( "/Applications/Firefox.app/Contents/MacOS/firefox-bin" ) ; if ( binary . exists ( ) ) { executables . add ( new Executable ( binary ) ) ; } binary = new File ( System . getProperty ( "user.home" ) + binary . getAbsolutePath ( ) ) ; if ( binary . exists ( ) ) { executables . add ( new Executable ( binary ) ) ; } } else if ( current . is ( UNIX ) ) { String systemFirefoxBin = new ExecutableFinder ( ) . find ( "firefox-bin" ) ; if ( systemFirefoxBin != null ) { executables . add ( new Executable ( new File ( systemFirefoxBin ) ) ) ; } } String systemFirefox = new ExecutableFinder ( ) . find ( "firefox" ) ; if ( systemFirefox != null ) { Path firefoxPath = new File ( systemFirefox ) . toPath ( ) ; if ( Files . isSymbolicLink ( firefoxPath ) ) { try { Path realPath = firefoxPath . toRealPath ( ) ; File attempt1 = realPath . getParent ( ) . resolve ( "firefox" ) . toFile ( ) ; if ( attempt1 . exists ( ) ) { executables . add ( new Executable ( attempt1 ) ) ; } else { File attempt2 = realPath . getParent ( ) . resolve ( "firefox-bin" ) . toFile ( ) ; if ( attempt2 . exists ( ) ) { executables . add ( new Executable ( attempt2 ) ) ; } } } catch ( IOException e ) { } } else { executables . add ( new Executable ( new File ( systemFirefox ) ) ) ; } } return executables . build ( ) . stream ( ) ; }
Locates the firefox binary by platform .
16,059
public synchronized void removeSessionLogs ( SessionId sessionId ) { if ( storeLogsOnSessionQuit ) { return ; } ThreadKey threadId = sessionToThreadMap . get ( sessionId ) ; SessionId sessionIdForThread = threadToSessionMap . get ( threadId ) ; if ( threadId != null && sessionIdForThread != null && sessionIdForThread . equals ( sessionId ) ) { threadToSessionMap . remove ( threadId ) ; sessionToThreadMap . remove ( sessionId ) ; } perSessionRecords . remove ( sessionId ) ; logFileRepository . removeLogFile ( sessionId ) ; }
Removes session logs for the given session id .
16,060
public synchronized String getLog ( SessionId sessionId ) throws IOException { String logs = formattedRecords ( sessionId ) ; logs = "\n<RC_Logs RC_Session_ID=" + sessionId + ">\n" + logs + "\n</RC_Logs>\n" ; return logs ; }
This returns Selenium Remote Control logs associated with the sessionId .
16,061
public synchronized List < SessionId > getLoggedSessions ( ) { ImmutableList . Builder < SessionId > builder = new ImmutableList . Builder < > ( ) ; builder . addAll ( perSessionDriverEntries . keySet ( ) ) ; return builder . build ( ) ; }
Returns a list of session IDs for which there are logs .
16,062
public synchronized SessionLogs getAllLogsForSession ( SessionId sessionId ) { SessionLogs sessionLogs = new SessionLogs ( ) ; if ( perSessionDriverEntries . containsKey ( sessionId ) ) { Map < String , LogEntries > typeToEntriesMap = perSessionDriverEntries . get ( sessionId ) ; for ( String logType : typeToEntriesMap . keySet ( ) ) { sessionLogs . addLog ( logType , typeToEntriesMap . get ( logType ) ) ; } perSessionDriverEntries . remove ( sessionId ) ; } return sessionLogs ; }
Gets all logs for a session .
16,063
public synchronized LogEntries getSessionLog ( SessionId sessionId ) throws IOException { List < LogEntry > entries = new ArrayList < > ( ) ; for ( LogRecord record : records ( sessionId ) ) { if ( record . getLevel ( ) . intValue ( ) >= serverLogLevel . intValue ( ) ) entries . add ( new LogEntry ( record . getLevel ( ) , record . getMillis ( ) , record . getMessage ( ) ) ) ; } return new LogEntries ( entries ) ; }
Returns the server log for the given session id .
16,064
public synchronized void fetchAndStoreLogsFromDriver ( SessionId sessionId , WebDriver driver ) throws IOException { if ( ! perSessionDriverEntries . containsKey ( sessionId ) ) { perSessionDriverEntries . put ( sessionId , new HashMap < > ( ) ) ; } Map < String , LogEntries > typeToEntriesMap = perSessionDriverEntries . get ( sessionId ) ; if ( storeLogsOnSessionQuit ) { typeToEntriesMap . put ( LogType . SERVER , getSessionLog ( sessionId ) ) ; Set < String > logTypeSet = driver . manage ( ) . logs ( ) . getAvailableLogTypes ( ) ; for ( String logType : logTypeSet ) { typeToEntriesMap . put ( logType , driver . manage ( ) . logs ( ) . get ( logType ) ) ; } } }
Fetches and stores available logs from the given session and driver .
16,065
public void update ( long a0 , long a1 , long a2 , long a3 ) { if ( done ) { throw new IllegalStateException ( "Can compute a hash only once per instance" ) ; } v1 [ 0 ] += mul0 [ 0 ] + a0 ; v1 [ 1 ] += mul0 [ 1 ] + a1 ; v1 [ 2 ] += mul0 [ 2 ] + a2 ; v1 [ 3 ] += mul0 [ 3 ] + a3 ; for ( int i = 0 ; i < 4 ; ++ i ) { mul0 [ i ] ^= ( v1 [ i ] & 0xffffffffL ) * ( v0 [ i ] >>> 32 ) ; v0 [ i ] += mul1 [ i ] ; mul1 [ i ] ^= ( v0 [ i ] & 0xffffffffL ) * ( v1 [ i ] >>> 32 ) ; } v0 [ 0 ] += zipperMerge0 ( v1 [ 1 ] , v1 [ 0 ] ) ; v0 [ 1 ] += zipperMerge1 ( v1 [ 1 ] , v1 [ 0 ] ) ; v0 [ 2 ] += zipperMerge0 ( v1 [ 3 ] , v1 [ 2 ] ) ; v0 [ 3 ] += zipperMerge1 ( v1 [ 3 ] , v1 [ 2 ] ) ; v1 [ 0 ] += zipperMerge0 ( v0 [ 1 ] , v0 [ 0 ] ) ; v1 [ 1 ] += zipperMerge1 ( v0 [ 1 ] , v0 [ 0 ] ) ; v1 [ 2 ] += zipperMerge0 ( v0 [ 3 ] , v0 [ 2 ] ) ; v1 [ 3 ] += zipperMerge1 ( v0 [ 3 ] , v0 [ 2 ] ) ; }
Updates the hash with 32 bytes of data given as 4 longs . This function is more efficient than updatePacket when you can use it .
16,066
public void updateRemainder ( byte [ ] bytes , int pos , int size_mod32 ) { if ( pos < 0 ) { throw new IllegalArgumentException ( String . format ( "Pos (%s) must be positive" , pos ) ) ; } if ( size_mod32 < 0 || size_mod32 >= 32 ) { throw new IllegalArgumentException ( String . format ( "size_mod32 (%s) must be between 0 and 31" , size_mod32 ) ) ; } if ( pos + size_mod32 > bytes . length ) { throw new IllegalArgumentException ( "bytes must have at least size_mod32 bytes after pos" ) ; } int size_mod4 = size_mod32 & 3 ; int remainder = size_mod32 & ~ 3 ; byte [ ] packet = new byte [ 32 ] ; for ( int i = 0 ; i < 4 ; ++ i ) { v0 [ i ] += ( ( long ) size_mod32 << 32 ) + size_mod32 ; } rotate32By ( size_mod32 , v1 ) ; for ( int i = 0 ; i < remainder ; i ++ ) { packet [ i ] = bytes [ pos + i ] ; } if ( ( size_mod32 & 16 ) != 0 ) { for ( int i = 0 ; i < 4 ; i ++ ) { packet [ 28 + i ] = bytes [ pos + remainder + i + size_mod4 - 4 ] ; } } else { if ( size_mod4 != 0 ) { packet [ 16 + 0 ] = bytes [ pos + remainder + 0 ] ; packet [ 16 + 1 ] = bytes [ pos + remainder + ( size_mod4 >>> 1 ) ] ; packet [ 16 + 2 ] = bytes [ pos + remainder + ( size_mod4 - 1 ) ] ; } } updatePacket ( packet , 0 ) ; }
Updates the hash with the last 1 to 31 bytes of the data . You must use updatePacket first per 32 bytes of the data if and only if 1 to 31 bytes of the data are not processed after that updateRemainder must be used for those final bytes .
16,067
protected void decrementLock ( SessionImplementor session , Object key , Lock lock ) { lock . unlock ( region . nextTimestamp ( ) ) ; region . put ( session , key , lock ) ; }
Unlock and re - put the given key lock combination .
16,068
public void setConfig ( Map < String , ? extends CacheConfig > config ) { this . configMap = ( Map < String , CacheConfig > ) config ; }
Set cache config mapped by cache name
16,069
public static RedissonCache monitor ( MeterRegistry registry , RedissonCache cache , Iterable < Tag > tags ) { new RedissonCacheMetrics ( cache , tags ) . bindTo ( registry ) ; return cache ; }
Record metrics on a Redisson cache .
16,070
private RemoteExecutorServiceAsync asyncScheduledServiceAtFixed ( String executorId , String requestId ) { ScheduledTasksService scheduledRemoteService = new ScheduledTasksService ( codec , name , commandExecutor , executorId , responses ) ; scheduledRemoteService . setTerminationTopicName ( terminationTopicName ) ; scheduledRemoteService . setTasksCounterName ( tasksCounterName ) ; scheduledRemoteService . setStatusName ( statusName ) ; scheduledRemoteService . setSchedulerQueueName ( schedulerQueueName ) ; scheduledRemoteService . setSchedulerChannelName ( schedulerChannelName ) ; scheduledRemoteService . setTasksName ( tasksName ) ; scheduledRemoteService . setRequestId ( new RequestId ( requestId ) ) ; scheduledRemoteService . setTasksRetryIntervalName ( tasksRetryIntervalName ) ; RemoteExecutorServiceAsync asyncScheduledServiceAtFixed = scheduledRemoteService . get ( RemoteExecutorServiceAsync . class , RemoteInvocationOptions . defaults ( ) . noAck ( ) . noResult ( ) ) ; return asyncScheduledServiceAtFixed ; }
Creates RemoteExecutorServiceAsync with special executor which overrides requestId generation and uses current requestId . Because recurring tasks should use the same requestId .
16,071
public static String toJSON ( Map < String , ? extends CacheConfig > config ) throws IOException { return new CacheConfigSupport ( ) . toJSON ( config ) ; }
Convert current configuration to JSON format
16,072
public static String toYAML ( Map < String , ? extends CacheConfig > config ) throws IOException { return new CacheConfigSupport ( ) . toYAML ( config ) ; }
Convert current configuration to YAML format
16,073
public static CronSchedule dailyAtHourAndMinute ( int hour , int minute ) { String expression = String . format ( "0 %d %d ? * *" , minute , hour ) ; return of ( expression ) ; }
Creates cron expression which schedule task execution every day at the given time
16,074
public static CronSchedule weeklyOnDayAndHourAndMinute ( int hour , int minute , Integer ... daysOfWeek ) { if ( daysOfWeek == null || daysOfWeek . length == 0 ) { throw new IllegalArgumentException ( "You must specify at least one day of week." ) ; } String expression = String . format ( "0 %d %d ? * %d" , minute , hour , daysOfWeek [ 0 ] ) ; for ( int i = 1 ; i < daysOfWeek . length ; i ++ ) { expression = expression + "," + daysOfWeek [ i ] ; } return of ( expression ) ; }
Creates cron expression which schedule task execution every given days of the week at the given time . Use Calendar object constants to define day .
16,075
public static CronSchedule monthlyOnDayAndHourAndMinute ( int dayOfMonth , int hour , int minute ) { String expression = String . format ( "0 %d %d %d * ?" , minute , hour , dayOfMonth ) ; return of ( expression ) ; }
Creates cron expression which schedule task execution every given day of the month at the given time
16,076
public LocalCachedMapOptions < K , V > evictionPolicy ( EvictionPolicy evictionPolicy ) { if ( evictionPolicy == null ) { throw new NullPointerException ( "evictionPolicy can't be null" ) ; } this . evictionPolicy = evictionPolicy ; return this ; }
Sets eviction policy .
16,077
public final boolean awaitUninterruptibly ( ) { try { return await ( 15 , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; return false ; } }
waiting for an open state
16,078
protected void handleLockExpiry ( SharedSessionContractImplementor session , Object key , Lockable lock ) { long ts = region . nextTimestamp ( ) + region . getTimeout ( ) ; Lock newLock = new Lock ( ts , uuid , nextLockId . getAndIncrement ( ) , null ) ; newLock . unlock ( ts ) ; region . put ( session , key , newLock ) ; }
Handle the timeout of a previous lock mapped to this key
16,079
public void start ( ) { if ( hasRedissonInstance ) { redisson = Redisson . create ( config ) ; } retrieveAddresses ( ) ; if ( config . getRedissonNodeInitializer ( ) != null ) { config . getRedissonNodeInitializer ( ) . onStartup ( this ) ; } int mapReduceWorkers = config . getMapReduceWorkers ( ) ; if ( mapReduceWorkers != - 1 ) { if ( mapReduceWorkers == 0 ) { mapReduceWorkers = Runtime . getRuntime ( ) . availableProcessors ( ) ; } redisson . getExecutorService ( RExecutorService . MAPREDUCE_NAME ) . registerWorkers ( mapReduceWorkers ) ; log . info ( "{} map reduce worker(s) registered" , mapReduceWorkers ) ; } for ( Entry < String , Integer > entry : config . getExecutorServiceWorkers ( ) . entrySet ( ) ) { String name = entry . getKey ( ) ; int workers = entry . getValue ( ) ; redisson . getExecutorService ( name ) . registerWorkers ( workers ) ; log . info ( "{} worker(s) for '{}' ExecutorService registered" , workers , name ) ; } log . info ( "Redisson node started!" ) ; }
Start Redisson node instance
16,080
public static Object convertValue ( final Object value , final Class < ? > convertType ) { if ( null == value ) { return convertNullValue ( convertType ) ; } if ( value . getClass ( ) == convertType ) { return value ; } if ( value instanceof Number ) { return convertNumberValue ( value , convertType ) ; } if ( value instanceof Date ) { return convertDateValue ( value , convertType ) ; } if ( String . class . equals ( convertType ) ) { return value . toString ( ) ; } else { return value ; } }
Convert value via expected class type .
16,081
public synchronized void remove ( final int statementId ) { MySQLBinaryStatement binaryStatement = getBinaryStatement ( statementId ) ; if ( null != binaryStatement ) { statementIdAssigner . remove ( binaryStatement . getSql ( ) ) ; binaryStatements . remove ( statementId ) ; } }
Remove expired cache statement .
16,082
public RegistryCenter load ( final RegistryCenterConfiguration regCenterConfig ) { Preconditions . checkNotNull ( regCenterConfig , "Registry center configuration cannot be null." ) ; RegistryCenter result = newService ( regCenterConfig . getType ( ) , regCenterConfig . getProperties ( ) ) ; result . init ( regCenterConfig ) ; return result ; }
Load registry center from SPI .
16,083
public static String getExactlyValue ( final String value ) { return null == value ? null : CharMatcher . anyOf ( "[]`'\"" ) . removeFrom ( value ) ; }
Get exactly value for SQL expression .
16,084
public static String getExactlyExpression ( final String value ) { return null == value ? null : CharMatcher . anyOf ( " " ) . removeFrom ( value ) ; }
Get exactly SQL expression .
16,085
public static String getOriginalValue ( final String value , final DatabaseType databaseType ) { if ( DatabaseType . MySQL != databaseType ) { return value ; } try { DefaultKeyword . valueOf ( value . toUpperCase ( ) ) ; return String . format ( "`%s`" , value ) ; } catch ( final IllegalArgumentException ex ) { return getOriginalValueForMySQLKeyword ( value ) ; } }
Get original value for SQL expression .
16,086
public int skipWhitespace ( ) { int length = 0 ; while ( CharType . isWhitespace ( charAt ( offset + length ) ) ) { length ++ ; } return offset + length ; }
skip whitespace .
16,087
public int skipComment ( ) { char current = charAt ( offset ) ; char next = charAt ( offset + 1 ) ; if ( isSingleLineCommentBegin ( current , next ) ) { return skipSingleLineComment ( COMMENT_BEGIN_SYMBOL_LENGTH ) ; } else if ( '#' == current ) { return skipSingleLineComment ( MYSQL_SPECIAL_COMMENT_BEGIN_SYMBOL_LENGTH ) ; } else if ( isMultipleLineCommentBegin ( current , next ) ) { return skipMultiLineComment ( ) ; } return offset ; }
skip comment .
16,088
public Token scanVariable ( ) { int length = 1 ; if ( '@' == charAt ( offset + 1 ) ) { length ++ ; } while ( isVariableChar ( charAt ( offset + length ) ) ) { length ++ ; } return new Token ( Literals . VARIABLE , input . substring ( offset , offset + length ) , offset + length ) ; }
scan variable .
16,089
public Token scanIdentifier ( ) { if ( '`' == charAt ( offset ) ) { int length = getLengthUntilTerminatedChar ( '`' ) ; return new Token ( Literals . IDENTIFIER , input . substring ( offset , offset + length ) , offset + length ) ; } if ( '"' == charAt ( offset ) ) { int length = getLengthUntilTerminatedChar ( '"' ) ; return new Token ( Literals . IDENTIFIER , input . substring ( offset , offset + length ) , offset + length ) ; } if ( '[' == charAt ( offset ) ) { int length = getLengthUntilTerminatedChar ( ']' ) ; return new Token ( Literals . IDENTIFIER , input . substring ( offset , offset + length ) , offset + length ) ; } int length = 0 ; while ( isIdentifierChar ( charAt ( offset + length ) ) ) { length ++ ; } String literals = input . substring ( offset , offset + length ) ; if ( isAmbiguousIdentifier ( literals ) ) { return new Token ( processAmbiguousIdentifier ( offset + length , literals ) , literals , offset + length ) ; } return new Token ( dictionary . findTokenType ( literals , Literals . IDENTIFIER ) , literals , offset + length ) ; }
scan identifier .
16,090
public Token scanHexDecimal ( ) { int length = HEX_BEGIN_SYMBOL_LENGTH ; if ( '-' == charAt ( offset + length ) ) { length ++ ; } while ( isHex ( charAt ( offset + length ) ) ) { length ++ ; } return new Token ( Literals . HEX , input . substring ( offset , offset + length ) , offset + length ) ; }
scan hex decimal .
16,091
public Token scanNumber ( ) { int length = 0 ; if ( '-' == charAt ( offset + length ) ) { length ++ ; } length += getDigitalLength ( offset + length ) ; boolean isFloat = false ; if ( '.' == charAt ( offset + length ) ) { isFloat = true ; length ++ ; length += getDigitalLength ( offset + length ) ; } if ( isScientificNotation ( offset + length ) ) { isFloat = true ; length ++ ; if ( '+' == charAt ( offset + length ) || '-' == charAt ( offset + length ) ) { length ++ ; } length += getDigitalLength ( offset + length ) ; } if ( isBinaryNumber ( offset + length ) ) { isFloat = true ; length ++ ; } return new Token ( isFloat ? Literals . FLOAT : Literals . INT , input . substring ( offset , offset + length ) , offset + length ) ; }
scan number .
16,092
public Token scanSymbol ( ) { int length = 0 ; while ( CharType . isSymbol ( charAt ( offset + length ) ) ) { length ++ ; } String literals = input . substring ( offset , offset + length ) ; Symbol symbol ; while ( null == ( symbol = Symbol . literalsOf ( literals ) ) ) { literals = input . substring ( offset , offset + -- length ) ; } return new Token ( symbol , literals , offset + length ) ; }
scan symbol .
16,093
public static DataSourcePropertyProvider getProvider ( final DataSource dataSource ) { String dataSourceClassName = dataSource . getClass ( ) . getName ( ) ; return DATA_SOURCE_PROPERTY_PROVIDERS . containsKey ( dataSourceClassName ) ? DATA_SOURCE_PROPERTY_PROVIDERS . get ( dataSourceClassName ) : new DefaultDataSourcePropertyProvider ( ) ; }
Get data source property provider .
16,094
public static DataSource getDataSource ( final String dataSourceClassName , final Map < String , Object > dataSourceProperties ) throws ReflectiveOperationException { DataSource result = ( DataSource ) Class . forName ( dataSourceClassName ) . newInstance ( ) ; for ( Entry < String , Object > entry : dataSourceProperties . entrySet ( ) ) { callSetterMethod ( result , getSetterMethodName ( entry . getKey ( ) ) , null == entry . getValue ( ) ? null : entry . getValue ( ) . toString ( ) ) ; } return result ; }
Get data source .
16,095
public static SQLParser newInstance ( final DatabaseType dbType , final ShardingRule shardingRule , final LexerEngine lexerEngine , final ShardingTableMetaData shardingTableMetaData , final String sql ) { lexerEngine . nextToken ( ) ; TokenType tokenType = lexerEngine . getCurrentToken ( ) . getType ( ) ; if ( DQLStatement . isDQL ( tokenType ) ) { if ( DatabaseType . MySQL == dbType || DatabaseType . H2 == dbType ) { return new AntlrParsingEngine ( dbType , sql , shardingRule , shardingTableMetaData ) ; } return getDQLParser ( dbType , shardingRule , lexerEngine , shardingTableMetaData ) ; } if ( DMLStatement . isDML ( tokenType ) ) { if ( DatabaseType . MySQL == dbType || DatabaseType . H2 == dbType ) { return new AntlrParsingEngine ( dbType , sql , shardingRule , shardingTableMetaData ) ; } return getDMLParser ( dbType , tokenType , shardingRule , lexerEngine , shardingTableMetaData ) ; } if ( MySQLKeyword . REPLACE == tokenType ) { if ( DatabaseType . MySQL == dbType || DatabaseType . H2 == dbType ) { return new AntlrParsingEngine ( dbType , sql , shardingRule , shardingTableMetaData ) ; } } if ( TCLStatement . isTCL ( tokenType ) ) { return new AntlrParsingEngine ( dbType , sql , shardingRule , shardingTableMetaData ) ; } if ( DALStatement . isDAL ( tokenType ) ) { if ( DatabaseType . PostgreSQL == dbType && PostgreSQLKeyword . SHOW == tokenType ) { return new AntlrParsingEngine ( dbType , sql , shardingRule , shardingTableMetaData ) ; } return getDALParser ( dbType , ( Keyword ) tokenType , shardingRule , lexerEngine ) ; } lexerEngine . nextToken ( ) ; TokenType secondaryTokenType = lexerEngine . getCurrentToken ( ) . getType ( ) ; if ( DCLStatement . isDCL ( tokenType , secondaryTokenType ) ) { return new AntlrParsingEngine ( dbType , sql , shardingRule , shardingTableMetaData ) ; } if ( DDLStatement . isDDL ( tokenType , secondaryTokenType ) ) { return new AntlrParsingEngine ( dbType , sql , shardingRule , shardingTableMetaData ) ; } if ( TCLStatement . isTCLUnsafe ( dbType , tokenType , lexerEngine ) ) { return new AntlrParsingEngine ( dbType , sql , shardingRule , shardingTableMetaData ) ; } if ( DefaultKeyword . SET . equals ( tokenType ) ) { return SetParserFactory . newInstance ( ) ; } throw new SQLParsingUnsupportedException ( tokenType ) ; }
Create SQL parser .
16,096
public static SQLParser newInstance ( final DatabaseType dbType , final EncryptRule encryptRule , final ShardingTableMetaData shardingTableMetaData , final String sql ) { if ( DatabaseType . MySQL == dbType || DatabaseType . H2 == dbType ) { return new AntlrParsingEngine ( dbType , sql , encryptRule , shardingTableMetaData ) ; } throw new SQLParsingUnsupportedException ( String . format ( "Can not support %s" , dbType ) ) ; }
Create Encrypt SQL parser .
16,097
public static int roundHalfUp ( final Object obj ) { if ( obj instanceof Short ) { return ( short ) obj ; } if ( obj instanceof Integer ) { return ( int ) obj ; } if ( obj instanceof Long ) { return ( ( Long ) obj ) . intValue ( ) ; } if ( obj instanceof Double ) { return new BigDecimal ( ( double ) obj ) . setScale ( 0 , BigDecimal . ROUND_HALF_UP ) . intValue ( ) ; } if ( obj instanceof Float ) { return new BigDecimal ( ( float ) obj ) . setScale ( 0 , BigDecimal . ROUND_HALF_UP ) . intValue ( ) ; } if ( obj instanceof String ) { return new BigDecimal ( ( String ) obj ) . setScale ( 0 , BigDecimal . ROUND_HALF_UP ) . intValue ( ) ; } throw new ShardingException ( "Invalid value to transfer: %s" , obj ) ; }
Round half up .
16,098
public static Number getExactlyNumber ( final String value , final int radix ) { try { return getBigInteger ( value , radix ) ; } catch ( final NumberFormatException ex ) { return new BigDecimal ( value ) ; } }
Get exactly number value and type .
16,099
public void parse ( final InsertStatement insertStatement ) { lexerEngine . unsupportedIfEqual ( getUnsupportedKeywordsBeforeInto ( ) ) ; lexerEngine . skipUntil ( DefaultKeyword . INTO ) ; lexerEngine . nextToken ( ) ; tableReferencesClauseParser . parse ( insertStatement , true ) ; skipBetweenTableAndValues ( insertStatement ) ; }
Parse insert into .