idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
39,600
|
public int waitForWindowPageChanged ( String windowName ) { if ( getScopeServices ( ) . getConnection ( ) == null ) { throw new CommunicationException ( "waiting for a window failed because Opera is not connected." ) ; } return getScopeServices ( ) . waitForDesktopWindowPageChanged ( windowName , OperaIntervals . WINDOW_EVENT_TIMEOUT . getMs ( ) ) ; }
|
Waits until new page is shown in the window is shown and then returns the window id of the window
|
39,601
|
public int waitForWindowLoaded ( String windowName ) { if ( getScopeServices ( ) . getConnection ( ) == null ) { throw new CommunicationException ( "waiting for a window failed because Opera is not connected." ) ; } return getScopeServices ( ) . waitForDesktopWindowLoaded ( windowName , OperaIntervals . PAGE_LOAD_TIMEOUT . getMs ( ) ) ; }
|
Waits until the window is loaded and then returns the window id of the window .
|
39,602
|
public String waitForMenuShown ( String menuName ) { if ( getScopeServices ( ) . getConnection ( ) == null ) { throw new CommunicationException ( "waiting for a window failed because Opera is not connected." ) ; } return getScopeServices ( ) . waitForMenuShown ( menuName , OperaIntervals . MENU_EVENT_TIMEOUT . getMs ( ) ) ; }
|
Waits until the menu is shown and then returns the name of the window
|
39,603
|
public String waitForMenuItemPressed ( String menuItemText ) { if ( getScopeServices ( ) . getConnection ( ) == null ) { throw new CommunicationException ( "waiting for a menu item to be pressed failed because Opera is not connected." ) ; } return getScopeServices ( ) . waitForMenuItemPressed ( menuItemText , OperaIntervals . MENU_EVENT_TIMEOUT . getMs ( ) ) ; }
|
Waits until the menu item is pressed and then returns the text of the menu item pressed
|
39,604
|
public void resetOperaPrefs ( String newPrefs ) { if ( ! firstTestRun || new File ( newPrefs ) . exists ( ) ) { if ( ! profileUtils . isMainProfile ( smallPreferencesPath ) && ! profileUtils . isMainProfile ( largePreferencesPath ) && ! profileUtils . isMainProfile ( cachePreferencesPath ) ) { quitOpera ( ) ; if ( Platform . getCurrent ( ) . is ( Platform . WINDOWS ) ) { try { Thread . sleep ( 2000 ) ; } catch ( InterruptedException e ) { } } if ( ! profileUtils . deleteProfile ( ) ) { logger . severe ( "Could not delete profile" ) ; } if ( ! new File ( newPrefs ) . exists ( ) ) { logger . finer ( "The '" + newPrefs + "' directory doesn't exist, omitting profile copying." ) ; } else if ( ! profileUtils . copyProfile ( newPrefs ) ) { logger . severe ( "Failed to copy profile from '" + newPrefs ) ; } else { logger . finer ( "Profile from '" + newPrefs + "' copied OK" ) ; } startOpera ( ) ; } else { logger . warning ( "Running tests in main user profile" ) ; } } firstTestRun = false ; }
|
meaning operaBinaryLocation will be set already
|
39,605
|
public void deleteOperaPrefs ( ) { if ( runner != null && ! runner . isOperaRunning ( ) ) { if ( ! profileUtils . deleteProfile ( ) ) { logger . severe ( "Could not delete profile" ) ; } } else { logger . warning ( "Cannot delete profile while Opera is running" ) ; } }
|
Deletes the profile for the connected Opera instance .
|
39,606
|
public static String sum ( byte [ ] bytes ) { String result = "" ; for ( byte b : bytes ) { result += Integer . toString ( ( b & 0xff ) + 0x100 , 16 ) . substring ( 1 ) ; } return result ; }
|
Return the MD5 HEX sum of a hashed MD5 byte array .
|
39,607
|
public static byte [ ] hash ( File file ) throws IOException { return Files . hash ( file , Hashing . md5 ( ) ) . asBytes ( ) ; }
|
Get the MD5 hash of the given file .
|
39,608
|
public static int parseDuration ( String duration ) { if ( duration == null ) { return 60 * 60 * 24 * 30 ; } Integer toAdd = null ; if ( days . matcher ( duration ) . matches ( ) ) { Matcher matcher = days . matcher ( duration ) ; matcher . matches ( ) ; toAdd = Integer . parseInt ( matcher . group ( 1 ) ) * ( 60 * 60 ) * 24 ; } else if ( hours . matcher ( duration ) . matches ( ) ) { Matcher matcher = hours . matcher ( duration ) ; matcher . matches ( ) ; toAdd = Integer . parseInt ( matcher . group ( 1 ) ) * ( 60 * 60 ) ; } else if ( minutes . matcher ( duration ) . matches ( ) ) { Matcher matcher = minutes . matcher ( duration ) ; matcher . matches ( ) ; toAdd = Integer . parseInt ( matcher . group ( 1 ) ) * ( 60 ) ; } else if ( seconds . matcher ( duration ) . matches ( ) ) { Matcher matcher = seconds . matcher ( duration ) ; matcher . matches ( ) ; toAdd = Integer . parseInt ( matcher . group ( 1 ) ) ; } else if ( "forever" . equals ( duration ) ) { toAdd = - 1 ; } if ( toAdd == null ) { throw new IllegalArgumentException ( "Invalid duration pattern : " + duration ) ; } return toAdd ; }
|
Parse a duration
|
39,609
|
public static File find ( OperaProduct product ) { File binary = findBinaryBasedOnEnvironmentVariable ( ) ; if ( binary != null ) { return binary ; } return findBinaryBasedOnPlatform ( product ) ; }
|
Locate the binary of the given product on the local system . If no binary is found null is returned .
|
39,610
|
public static String assertBasic ( String symbol , IContext context ) { if ( symbol . contains ( "_utils.sep(\"" ) ) return symbol ; String s = symbol ; boolean isSimple = Patterns . VarName . matches ( s ) ; IContext ctx = context ; if ( ! isSimple ) { throw new TemplateParser . ComplexExpressionException ( ctx ) ; } return s ; }
|
Return symbol with transformer extension stripped off
|
39,611
|
public void take ( ) throws AWTException { Rectangle area = new Rectangle ( dimensions ) ; Robot robot = new Robot ( ) ; BufferedImage image = robot . createScreenCapture ( area ) ; data = getByteArray ( image ) ; }
|
Takes the screen capture of the designated area . If no dimensions are specified it will take a screenshot of the full screen by default .
|
39,612
|
public String getMd5 ( ) throws IOException { checkCaptureTaken ( ) ; try { return MD5 . of ( getData ( ) ) ; } catch ( IOException e ) { throw new IOException ( "Unable to open stream or file: " + e . getMessage ( ) , e ) ; } }
|
Get the MD5 hash sum of the byte array of the data of the screen capture .
|
39,613
|
public static ScreenCapture of ( Dimension dimensions ) throws IOException { ScreenCapture capture = new ScreenCapture ( dimensions ) ; try { capture . take ( ) ; } catch ( AWTException e ) { throw new IOException ( e ) ; } return capture ; }
|
Takes a screen capture of the given dimensions .
|
39,614
|
private static byte [ ] getByteArray ( BufferedImage image ) { checkNotNull ( image ) ; ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; try { ImageIO . write ( image , "png" , stream ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } return stream . toByteArray ( ) ; }
|
Get a byte array of the data of a buffered image .
|
39,615
|
public boolean deleteProfile ( ) { String [ ] profileDirs = { smallPrefsFolder , largePrefsFolder , cachePrefsFolder } ; for ( String profileDir : profileDirs ) { if ( isMainProfile ( profileDir ) ) { logger . finer ( "Skipping profile deletion since '" + profileDir + "' is the main profile." ) ; return false ; } } for ( String profileDir : profileDirs ) { File currentDirHandle = new File ( profileDir ) ; if ( ! currentDirHandle . exists ( ) ) { logger . finer ( "Skipping profile deletion for '" + profileDir + "' since it doesn't exist." ) ; continue ; } boolean deleted = deleteFolder ( profileDir ) ; if ( ! deleted ) { final int retryIntervalMs = 500 ; final int retryMaxCount = 10 ; int retryCount = 0 ; boolean ok = false ; logger . warning ( "Profile could not be deleted, retrying..." ) ; do { try { Thread . sleep ( retryIntervalMs ) ; } catch ( InterruptedException e ) { } ok = deleteFolder ( profileDir ) ; retryCount ++ ; if ( retryCount > retryMaxCount ) { break ; } } while ( ! ok ) ; if ( ! ok ) { logger . severe ( "Could not delete profile in '" + profileDir + "'. Skipping further deletion." ) ; return false ; } else { logger . warning ( "Deleted profile, retry count = " + retryCount ) ; } } else { logger . finer ( "Deleted profile in '" + profileDir + "'" ) ; } } return true ; }
|
Deletes prefs folders for Does nothing if prefs folders are default main user profile
|
39,616
|
private void initializeWindows ( ) { clearFilter ( ) ; Response response = executeMessage ( WindowManagerMessage . LIST_WINDOWS , null ) ; WindowList . Builder builder = WindowList . newBuilder ( ) ; buildPayload ( response , builder ) ; WindowList list = builder . build ( ) ; List < WindowInfo > windowsList = list . getWindowListList ( ) ; windows . clear ( ) ; for ( WindowInfo window : windowsList ) { windows . put ( window . getWindowID ( ) , window ) ; } windows . putIfAbsent ( findActiveWindow ( ) . getWindowID ( ) , null ) ; }
|
Set the filter to include all windows so we can get a list and maintain a list of windows .
|
39,617
|
public static boolean isDouble ( String string ) { if ( string == null ) { return false ; } try { Double . parseDouble ( string ) ; } catch ( NumberFormatException e ) { return false ; } return true ; }
|
Checks whether given string has a double value .
|
39,618
|
public static boolean isInteger ( String string ) { if ( string == null ) { return false ; } try { Integer . parseInt ( string ) ; } catch ( NumberFormatException e ) { return false ; } return true ; }
|
Checks whether the given string has an integer value .
|
39,619
|
public static String escapeJsString ( String string , String quote ) { Pattern escapePattern = Pattern . compile ( "([^\\\\])" + quote ) ; Matcher m = escapePattern . matcher ( " " + string ) ; StringBuffer sb = new StringBuffer ( ) ; while ( m . find ( ) ) { m . appendReplacement ( sb , "$1\\\\" + quote ) ; } m . appendTail ( sb ) ; return sb . substring ( 1 ) ; }
|
Escape characters for safe insertion in a JavaScript string .
|
39,620
|
public ScreenCaptureReply captureScreen ( long timeout , List < String > knownMD5s ) throws OperaRunnerException { assertLauncherAlive ( ) ; String resultMd5 ; byte [ ] resultBytes ; boolean blank = false ; try { LauncherScreenshotRequest . Builder request = LauncherScreenshotRequest . newBuilder ( ) ; request . addAllKnownMD5S ( knownMD5s ) ; request . setKnownMD5STimeoutMs ( ( int ) timeout ) ; ResponseEncapsulation res = protocol . sendRequest ( MessageType . MSG_SCREENSHOT , request . build ( ) . toByteArray ( ) ) ; LauncherScreenshotResponse response = ( LauncherScreenshotResponse ) res . getResponse ( ) ; resultMd5 = response . getMd5 ( ) ; resultBytes = response . getImagedata ( ) . toByteArray ( ) ; if ( response . hasBlank ( ) ) { blank = response . getBlank ( ) ; } } catch ( SocketTimeoutException e ) { throw new OperaRunnerException ( "Could not get screenshot from launcher" , e ) ; } catch ( IOException e ) { throw new OperaRunnerException ( "Could not get screenshot from launcher" , e ) ; } ScreenCaptureReply . Builder builder = ScreenCaptureReply . builder ( ) ; builder . setMD5 ( resultMd5 ) ; builder . setPNG ( resultBytes ) ; builder . setBlank ( blank ) ; builder . setCrashed ( this . hasOperaCrashed ( ) ) ; return builder . build ( ) ; }
|
Take screenshot using external program . Will not trigger a screen repaint .
|
39,621
|
private StatusType handleStatusMessage ( GeneratedMessage msg ) { LauncherStatusResponse response = ( LauncherStatusResponse ) msg ; logger . finest ( "[LAUNCHER] Status: " + response . getStatus ( ) . toString ( ) ) ; if ( response . hasExitcode ( ) ) { logger . finest ( "[LAUNCHER] Status: exitCode=" + response . getExitcode ( ) ) ; } if ( response . hasCrashlog ( ) ) { logger . finest ( "[LAUNCHER] Status: crashLog=yes" ) ; } else { logger . finest ( "[LAUNCHER] Status: crashLog=no" ) ; } if ( response . getLogmessagesCount ( ) > 0 ) { for ( String message : response . getLogmessagesList ( ) ) { logger . finest ( "[LAUNCHER LOG] " + message ) ; } } else { logger . finest ( "[LAUNCHER LOG] No log..." ) ; } StatusType status = response . getStatus ( ) ; if ( status == StatusType . CRASHED ) { if ( response . hasCrashlog ( ) ) { crashlog = response . getCrashlog ( ) . toStringUtf8 ( ) ; } else { crashlog = "" ; } } else { crashlog = null ; } return status ; }
|
Handle status message and updates state .
|
39,622
|
public static void assertLauncherGood ( File launcher ) throws IOException { if ( ! launcher . exists ( ) ) { throw new IOException ( "Unknown file: " + launcher . getPath ( ) ) ; } if ( ! launcher . isFile ( ) ) { throw new IOException ( "Not a real file: " + launcher . getPath ( ) ) ; } if ( ! FileHandler . canExecute ( launcher ) ) { throw new IOException ( "Not executable: " + launcher . getPath ( ) ) ; } }
|
Asserts whether given launcher exists is a file and that it s executable .
|
39,623
|
private static String launcherNameForOS ( ) { switch ( Platform . getCurrent ( ) ) { case LINUX : case UNIX : Architecture architecture = Architecture . getCurrent ( ) ; String launcherPrefix = "launcher-linux-%s" ; switch ( architecture ) { case X86 : return String . format ( launcherPrefix , "i386" ) ; case X64 : return String . format ( launcherPrefix , "amd64" ) ; case ARM : return String . format ( launcherPrefix , "arm" ) ; default : throw new WebDriverException ( "Unsupported processor architecture: " + architecture ) ; } case MAC : return "launcher-mac" ; case WINDOWS : case VISTA : case XP : return "launcher-win32-i86pc.exe" ; default : throw new WebDriverException ( "Could not find a platform that supports bundled launchers, please set it manually" ) ; } }
|
Get the launcher s binary file name based on what flavour of operating system and what kind of architecture the user is using .
|
39,624
|
public static boolean isBoolesque ( String string ) { checkNotNull ( string ) ; assertBoolesque ( string ) ; return isFalsy ( string ) || isTruthy ( string ) ; }
|
Whether string holds a boolean - like value . It should equal 0 1 true or false . This method says nothing about whether the object is true or false .
|
39,625
|
public boolean isJavaExtension ( String s ) { for ( IJavaExtension ext : _extensions ) { if ( S . isEqual ( s , ext . methodName ( ) ) ) { return true ; } } return false ; }
|
Is a specified method name a java extension?
|
39,626
|
public static Map < String , Object > from ( Pair ... pairs ) { Map < String , Object > map = new HashMap < String , Object > ( pairs . length ) ; for ( Pair p : pairs ) { map . put ( p . key , p . value ) ; } return map ; }
|
construct me from the given pairs
|
39,627
|
public String getSubstitutedString ( String [ ] args , boolean stripAmpersand ) { String stringId = args [ 0 ] ; String rawString = getString ( stringId , stripAmpersand ) ; logger . finer ( String . format ( "String \"%s\" fetched as \"%s\"" , stringId , rawString ) ) ; StringBuffer buf = new StringBuffer ( ) ; int curArg = 0 ; int formattersCount = 0 ; boolean orderedMode ; String orderedFormatterRegexp = "%(\\d+)" ; Pattern pattern = Pattern . compile ( SUBSTITUTED_STRING_REGEXP ) ; Matcher matcher = pattern . matcher ( rawString ) ; if ( matcher . find ( ) ) { logger . finer ( "Parsing with standard formatters" ) ; matcher . reset ( ) ; orderedMode = false ; } else { logger . finer ( "Parsing with ordered formatters" ) ; pattern = Pattern . compile ( orderedFormatterRegexp ) ; matcher = pattern . matcher ( rawString ) ; orderedMode = true ; } while ( matcher . find ( ) ) { formattersCount ++ ; String replaceStr = matcher . group ( ) ; String substitution = "" ; if ( replaceStr . equals ( "%%" ) ) { substitution = "%" ; } else { if ( orderedMode ) { curArg = Integer . parseInt ( replaceStr . substring ( 1 ) ) ; } else { curArg ++ ; } if ( curArg < args . length ) { substitution = args [ curArg ] ; if ( substitution . isEmpty ( ) ) { substitution = WatirUtils . ANY_MATCHER ; } } else { substitution = replaceStr ; } } matcher . appendReplacement ( buf , substitution ) ; } matcher . appendTail ( buf ) ; if ( formattersCount != ( args . length - 1 ) ) { logger . warning ( String . format ( "Argument count incorrect for %s, got %d, expected %d" , stringId , ( args . length - 1 ) , formattersCount ) ) ; } String result = buf . toString ( ) ; logger . finer ( "Final string: '" + result + "'" ) ; return result ; }
|
Fetches a translated string fetched basing on a string id and substitutes the printf formatters in it . Each substitution argument needs to be a string . The printf formatter types are ignored and the given string argument is substituted .
|
39,628
|
public V putIfAbsent ( K k , V v ) { synchronized ( map ) { if ( ! containsKey ( k ) ) { list . addFirst ( k ) ; return map . put ( k , v ) ; } else { list . remove ( k ) ; } list . addFirst ( k ) ; return null ; } }
|
Puts a key to top of the map if absent if the key is present in stack it is removed
|
39,629
|
public static CompilerException compilerException ( String className , int line , String message ) { CompilerException e = new CompilerException ( ) ; e . javaLineNumber = line ; e . message = ExpressionParser . reversePositionPlaceHolder ( message ) ; e . className = className ; return e ; }
|
create a compiler exception for the given className line number and message
|
39,630
|
public static void turnOffSandbox ( String code ) { if ( ! sandboxLive ) return ; rsm ( ) . forbiddenIfCodeNotMatch ( code ) ; sandboxLive = false ; System . setSecurityManager ( null ) ; }
|
Turn off sandbox mode . Used by Rythm unit testing program
|
39,631
|
private static String sanitize ( String key ) { for ( OperaArgumentSign sign : OperaArgumentSign . values ( ) ) { if ( hasSwitch ( key , sign . sign ) ) { return key . substring ( sign . sign . length ( ) ) ; } } return key ; }
|
Sanitizes an argument that contains a sign . By default we sanitize all added arguments meaning - foo will be sanitized to foo .
|
39,632
|
private static Boolean hasSwitch ( String key , String sign ) { return ( key . length ( ) > sign . length ( ) ) && key . substring ( 0 , sign . length ( ) ) . equals ( sign ) ; }
|
Determines whether given argument key contains given argument sign .
|
39,633
|
private ScreenWatcherResult executeScreenWatcher ( ScreenWatcher . Builder builder , long timeout ) { if ( timeout <= 0 ) { timeout = 1 ; } builder . setTimeOut ( ( int ) timeout ) ; builder . setWindowID ( services . getWindowManager ( ) . getActiveWindowId ( ) ) ; Response response = executeMessage ( ExecMessage . SETUP_SCREEN_WATCHER , builder , OperaIntervals . RESPONSE_TIMEOUT . getMs ( ) + timeout ) ; ScreenWatcherResult . Builder watcherBuilder = ScreenWatcherResult . newBuilder ( ) ; buildPayload ( response , watcherBuilder ) ; return watcherBuilder . build ( ) ; }
|
Executes a screenwatcher with the given timeout and returns the result .
|
39,634
|
protected String buildEvalString ( List < WebElement > elements , String script , Object ... params ) { String toSend ; if ( params != null && params . length > 0 ) { StringBuilder builder = new StringBuilder ( ) ; for ( Object object : params ) { if ( builder . toString ( ) . length ( ) > 0 ) { builder . append ( ',' ) ; } if ( object instanceof Collection < ? > ) { builder . append ( '[' ) ; Collection < ? > collection = ( Collection < ? > ) object ; for ( Object argument : collection ) { processArgument ( argument , builder , elements ) ; builder . append ( ',' ) ; } int lastCharIndex = builder . length ( ) - 1 ; if ( builder . charAt ( lastCharIndex ) != '[' ) { builder . deleteCharAt ( lastCharIndex ) ; } builder . append ( ']' ) ; } else { processArgument ( object , builder , elements ) ; } } String arguments = builder . toString ( ) ; toSend = String . format ( "(function(){%s})(%s)" , script , arguments ) ; } else { toSend = script ; } return toSend ; }
|
Build the script to send with arguments .
|
39,635
|
private static String stripOuterBrackets ( String s ) { try { if ( S . isEmpty ( s ) ) return s ; if ( R_ . search ( s ) ) { s = R_ . stringMatched ( ) ; s = s . substring ( 1 ) ; s = s . substring ( 0 , s . length ( ) - 1 ) ; } } catch ( RuntimeException re ) { throw re ; } return s ; }
|
strip the outer brackets of the given string s
|
39,636
|
public QuickWidget getQuickWidget ( QuickWidgetType type , int windowId , QuickWidgetSearchType property , String value , String parentName ) { if ( windowId < 0 ) { windowId = getActiveQuickWindowId ( ) ; } List < QuickWidget > widgets = getQuickWidgetList ( windowId ) ; for ( QuickWidget widget : widgets ) { if ( widget . getType ( ) == type ) { if ( property . equals ( QuickWidgetSearchType . NAME ) ) { if ( ( parentName . length ( ) == 0 || widget . getParentName ( ) . equals ( parentName ) ) && widget . getName ( ) . equals ( value ) ) { return widget ; } } else if ( property . equals ( QuickWidgetSearchType . TEXT ) ) { if ( ( parentName . length ( ) == 0 || widget . getParentName ( ) . equals ( parentName ) ) && WatirUtils . textMatchesWithANY ( widget . getText ( ) , value ) ) { return widget ; } } } } return null ; }
|
parentName is set to name pos or text depending on widget . getParentType
|
39,637
|
public QuickMenuItem getQuickMenuItemByAction ( String action ) { List < QuickMenuItem > itemList = getQuickMenuItemList ( ) ; for ( QuickMenuItem item : itemList ) { if ( item . getActionName ( ) . equals ( action ) ) { return item ; } } return null ; }
|
and unique within a single menu given either shortcutletter or pos
|
39,638
|
public void init ( ) { waitForHandshake ( ) ; availableServices = buildAvailableServices ( getHostInfo ( ) ) ; connect ( ) ; if ( OperaDefaults . ENABLE_DEBUGGER && ! ( requiredServices . contains ( ScopeService . ECMASCRIPT ) || requiredServices . contains ( ScopeService . ECMASCRIPT_DEBUGGER ) ) ) { if ( availableServices . containsKey ( ScopeService . ECMASCRIPT ) ) { requiredServices . add ( ScopeService . ECMASCRIPT ) ; } else { requiredServices . add ( ScopeService . ECMASCRIPT_DEBUGGER ) ; } } else { debugger = new MockEcmascriptDebugger ( ) ; } services = createServices ( requiredServices ) ; enableServices ( services . values ( ) ) ; initializeServices ( services . values ( ) ) ; }
|
Gets the supported services from Opera and calls methods to enable the ones we requested .
|
39,639
|
private Map < ScopeService , Service > createServices ( final Set < ScopeService > services ) { Map < ScopeService , Service > actualServices = Maps . newTreeMap ( ) ; for ( ScopeService requiredService : services ) { if ( availableServices . containsKey ( requiredService ) ) { for ( ScopeService availableService : availableServices . keySet ( ) ) { if ( availableService == requiredService ) { actualServices . put ( requiredService , requiredService . newInstance ( this ) ) ; } } } } return actualServices ; }
|
Build and construct the given services .
|
39,640
|
private HostInfo getHostInfo ( ) { Response response = executeMessage ( ScopeMessage . HOST_INFO , null ) ; try { return HostInfo . parseFrom ( response . getPayload ( ) ) ; } catch ( InvalidProtocolBufferException e ) { throw new CommunicationException ( "Error while parsing host info" , e ) ; } }
|
Gets information on available services and their versions from Opera . This includes the STP version core version platform operating system user agent string and a list of available services .
|
39,641
|
private void connect ( ) { ClientInfo . Builder info = ClientInfo . newBuilder ( ) . setFormat ( "protobuf" ) ; executeMessage ( ScopeMessage . CONNECT , info ) ; }
|
Connects and resets any settings and services that the client used earlier .
|
39,642
|
public void waitForOperaIdle ( long timeout ) { logger . finest ( "idle: Waiting for (timeout = " + timeout + ")" ) ; waitState . waitForOperaIdle ( timeout ) ; logger . finest ( "idle: Finished waiting" ) ; }
|
Waits for an OperaIdle event before continuing .
|
39,643
|
public Response executeMessage ( Message message , Builder < ? > builder ) { return executeMessage ( message , builder , OperaIntervals . RESPONSE_TIMEOUT . getMs ( ) ) ; }
|
Sends a message and wait for the response .
|
39,644
|
public ResponseEncapsulation sendRequest ( MessageType type , byte [ ] body ) throws IOException { sendRequestHeader ( type , ( body != null ) ? body . length : 0 ) ; if ( body != null ) { os . write ( body ) ; } return recvMessage ( ) ; }
|
Send a request and receive a result .
|
39,645
|
public void sendRequestWithoutResponse ( MessageType type , byte [ ] body ) throws IOException { sendRequestHeader ( type , ( body != null ) ? body . length : 0 ) ; if ( body != null ) { os . write ( body ) ; } }
|
Send a request without a response . Used for shutdown .
|
39,646
|
private ResponseEncapsulation recvMessage ( ) throws IOException { GeneratedMessage msg = null ; byte [ ] headers = new byte [ 8 ] ; recv ( headers , headers . length ) ; if ( headers [ 0 ] != 'L' || headers [ 1 ] != '1' ) { throw new IOException ( "Wrong launcher protocol header" ) ; } ByteBuffer buf = ByteBuffer . allocate ( 4 ) ; buf . order ( ByteOrder . BIG_ENDIAN ) ; buf . put ( headers , 4 , 4 ) ; buf . flip ( ) ; int size = buf . getInt ( ) ; logger . finest ( "RECV: type=" + ( ( int ) headers [ 3 ] ) + ", command=" + ( ( int ) headers [ 2 ] ) + ", size=" + size ) ; byte [ ] data = new byte [ size ] ; recv ( data , size ) ; boolean success = ( headers [ 3 ] == ( byte ) 1 ) ; MessageType type = MessageType . get ( headers [ 2 ] ) ; if ( type == null ) { throw new IOException ( "Unable to determine message type" ) ; } if ( ( headers [ 3 ] != ( byte ) 1 ) && ( headers [ 3 ] != ( byte ) 2 ) ) { throw new IOException ( "Unable to determine success or error" ) ; } switch ( type ) { case MSG_HELLO : { LauncherHandshakeResponse . Builder response = LauncherHandshakeResponse . newBuilder ( ) ; buildMessage ( response , data ) ; msg = response . build ( ) ; break ; } case MSG_START : case MSG_STATUS : case MSG_STOP : { LauncherStatusResponse . Builder response = LauncherStatusResponse . newBuilder ( ) ; buildMessage ( response , data ) ; msg = response . build ( ) ; break ; } case MSG_SCREENSHOT : { LauncherScreenshotResponse . Builder response = LauncherScreenshotResponse . newBuilder ( ) ; buildMessage ( response , data ) ; msg = response . build ( ) ; break ; } } return new ResponseEncapsulation ( success , msg ) ; }
|
Receive a message response .
|
39,647
|
public final String callMethod ( String method ) { parent . assertConnected ( ) ; return debugger . callFunctionOnObject ( method , objectId ) ; }
|
Calls the method and parses the result the result must be a string
|
39,648
|
private void executeMethod ( String script ) { parent . assertConnected ( ) ; debugger . callFunctionOnObject ( script , objectId , false ) ; }
|
Executes the given script with the element s object ID but does not parse the response .
|
39,649
|
@ SuppressWarnings ( "unused" ) public void middleClick ( ) { Point point = coordinates . inViewPort ( ) ; exec . mouseAction ( point . x , point . y , OperaMouseKeys . MIDDLE ) ; }
|
Click the middle mouse button at the top left corner of the element .
|
39,650
|
public Point getLocation ( ) { assertElementNotStale ( ) ; String coordinates = debugger . callFunctionOnObject ( "var coords = " + OperaAtom . GET_LOCATION + "(locator); return coords.x + ',' + coords.y;" , objectId ) ; if ( coordinates . isEmpty ( ) ) { logger . warning ( "Falling back to non-atom positioning code in getLocation" ) ; coordinates = debugger . callFunctionOnObject ( "var coords = locator.getBoundingClientRect();" + "return (coords.left-window.pageXOffset)+','+(coords.top-window.pageYOffset)" , objectId ) ; } String [ ] location = coordinates . split ( "," ) ; return new Point ( Integer . valueOf ( location [ 0 ] ) , Integer . valueOf ( location [ 1 ] ) ) ; }
|
Click top left can be modified to click in the middle
|
39,651
|
public String getImageHash ( long timeout , List < String > hashes ) { return saveScreenshot ( "" , timeout , false , hashes ) ; }
|
Takes a screenshot after timeout milliseconds of the area this element s bounding - box covers and returns the MD5 hash .
|
39,652
|
public String saveScreenshot ( String filename , long timeout ) { return saveScreenshot ( filename , timeout , true , new ArrayList < String > ( ) ) ; }
|
Take a screenshot of the area this element covers . Saves a copy of the image to the given filename .
|
39,653
|
public String saveScreenshot ( String filename , long timeout , boolean includeImage , List < String > hashes ) { assertElementNotStale ( ) ; Canvas canvas = buildCanvas ( ) ; ScreenCaptureReply reply = exec . screenWatcher ( canvas , timeout , includeImage , hashes ) ; if ( includeImage && reply . getPng ( ) != null ) { FileChannel stream ; try { stream = new FileOutputStream ( filename ) . getChannel ( ) ; stream . write ( ByteBuffer . wrap ( reply . getPng ( ) ) ) ; stream . close ( ) ; } catch ( IOException e ) { throw new WebDriverException ( "Failed to write file: " + e . getMessage ( ) , e ) ; } } return reply . getMd5 ( ) ; }
|
Take a screenshot of the area this element covers . If the hash of the image matches any of the given hashes then no image is saved otherwise it saves a copy of the image to the given filename .
|
39,654
|
@ SuppressWarnings ( "unused" ) public boolean containsColor ( OperaColors ... colors ) { assertElementNotStale ( ) ; Canvas canvas = buildCanvas ( ) ; ScreenCaptureReply reply = exec . containsColor ( canvas , 100L , colors ) ; List < ColorResult > results = reply . getColorResults ( ) ; for ( ColorResult result : results ) { if ( result . getCount ( ) > 0 ) { return true ; } } return false ; }
|
Check if the current page contains any of the given colors . Used on tests that use red to show a failure .
|
39,655
|
private Canvas buildCanvas ( ) { Canvas canvas = new Canvas ( ) ; Dimension dimension = getSize ( ) ; Point point = coordinates . inViewPort ( ) ; int x = point . x ; int y = point . y ; int w = Math . max ( dimension . width , 1 ) ; int h = Math . max ( dimension . height , 1 ) ; canvas . setX ( x ) ; canvas . setY ( y ) ; canvas . setHeight ( h ) ; canvas . setWidth ( w ) ; canvas . setViewPortRelative ( true ) ; return canvas ; }
|
Create a canvas which is an object that specifies a rectangle to take a screenshot of .
|
39,656
|
public void close ( ) { if ( socketChannel == null ) { return ; } monitor . remove ( socketChannel ) ; try { socketChannel . close ( ) ; } catch ( IOException ignored ) { } finally { socketChannel = null ; } }
|
Switches the wait state and wakes up the selector to process .
|
39,657
|
private Map < String , Object > _processConf ( Map < String , ? > conf ) { Map < String , Object > m = new HashMap < String , Object > ( conf . size ( ) ) ; for ( String s : conf . keySet ( ) ) { Object o = conf . get ( s ) ; if ( s . startsWith ( "rythm." ) ) s = s . replaceFirst ( "rythm\\." , "" ) ; m . put ( s , o ) ; } return m ; }
|
trim rythm . from conf keys
|
39,658
|
@ SuppressWarnings ( "unchecked" ) public String renderString ( String key , String template , Object ... args ) { boolean typeInferenceEnabled = conf ( ) . typeInferenceEnabled ( ) ; if ( typeInferenceEnabled ) { ParamTypeInferencer . registerParams ( this , args ) ; } if ( typeInferenceEnabled ) { key += ParamTypeInferencer . uuid ( ) ; } try { TemplateClass tc = classes ( ) . getByTemplate ( key , false ) ; if ( null == tc ) { tc = new TemplateClass ( new StringTemplateResource ( key , template ) , this ) ; } ITemplate t = tc . asTemplate ( this ) ; setRenderArgs ( t , args ) ; return t . render ( ) ; } finally { renderCleanUp ( ) ; } }
|
Render result from a direct template content . The template key has been provided as well
|
39,659
|
public String renderIfTemplateExists ( String template , Object ... args ) { boolean typeInferenceEnabled = conf ( ) . typeInferenceEnabled ( ) ; if ( typeInferenceEnabled ) { ParamTypeInferencer . registerParams ( this , args ) ; } if ( nonExistsTemplates . contains ( template ) ) return "" ; String key = template ; if ( typeInferenceEnabled ) { key += ParamTypeInferencer . uuid ( ) ; } try { TemplateClass tc = classes ( ) . getByTemplate ( template ) ; if ( null == tc ) { ITemplateResource rsrc = resourceManager ( ) . getResource ( template ) ; if ( rsrc . isValid ( ) ) { tc = new TemplateClass ( rsrc , this ) ; } else { nonExistsTemplates . add ( template ) ; if ( isDevMode ( ) && nonExistsTemplatesChecker == null ) { nonExistsTemplatesChecker = new NonExistsTemplatesChecker ( ) ; } return "" ; } } ITemplate t = tc . asTemplate ( this ) ; setRenderArgs ( t , args ) ; return t . render ( ) ; } finally { renderCleanUp ( ) ; } }
|
Render template if specified template exists otherwise return empty string
|
39,660
|
public Object eval ( String script ) { return eval ( script , Collections . < String , Object > emptyMap ( ) ) ; }
|
Evaluate a script and return executing result . Note the API is not mature yet don t use it in your application
|
39,661
|
public void invalidate ( TemplateClass parent ) { if ( mode ( ) . isProd ( ) ) return ; Set < TemplateClass > children = extendMap . get ( parent ) ; if ( null == children ) return ; for ( TemplateClass child : children ) { invalidate ( child ) ; child . reset ( ) ; } }
|
called to invalidate all template class which extends the parent
|
39,662
|
public void shutdown ( ) { if ( zombie ) { return ; } logger . info ( "Shutting down Rythm Engine: [%s]" , id ( ) ) ; if ( null != _cacheService ) { try { _cacheService . shutdown ( ) ; } catch ( Exception e ) { logger . error ( e , "Error shutdown cache service" ) ; } } if ( null != _secureExecutor ) { try { _secureExecutor . shutdown ( ) ; } catch ( Exception e ) { logger . error ( e , "Error shutdown secure executor" ) ; } } if ( null != _resourceManager ) { try { _resourceManager . shutdown ( ) ; } catch ( Exception e ) { logger . error ( e , "Error shutdown resource manager" ) ; } } if ( null != shutdownListener ) { try { shutdownListener . onShutdown ( ) ; } catch ( Exception e ) { logger . error ( e , "Error execute shutdown listener" ) ; } } if ( null != nonExistsTemplatesChecker ) { nonExistsTemplatesChecker . onShutdown ( ) ; } if ( null != _templates ) _templates . clear ( ) ; if ( null != _classes ) _classes . clear ( ) ; if ( null != _nonExistsTags ) _nonExistsTags . clear ( ) ; if ( null != nonExistsTemplates ) nonExistsTemplates . clear ( ) ; if ( null != _nonTmpls ) _nonTmpls . clear ( ) ; _classLoader = null ; Rythm . RenderTime . clear ( ) ; zombie = true ; }
|
Shutdown this rythm engine
|
39,663
|
public void sendMessage ( CharArrayWriter message ) throws IOException { SyslogMessage syslogMessage = new SyslogMessage ( ) . withAppName ( defaultAppName ) . withFacility ( defaultFacility ) . withHostname ( defaultMessageHostname ) . withSeverity ( defaultSeverity ) . withMsg ( message ) ; sendMessage ( syslogMessage ) ; }
|
Send the given text message
|
39,664
|
public void setSdParams ( List < SDParam > sdParams ) { if ( null == sdParams ) { throw new IllegalArgumentException ( "sdParams list cannot be null" ) ; } this . sdParams . addAll ( sdParams ) ; }
|
Set the value of sdParams
|
39,665
|
public SDElement addSDParam ( String paramName , String paramValue ) { return addSDParam ( new SDParam ( paramName , paramValue ) ) ; }
|
Adds a SDParam
|
39,666
|
@ SuppressWarnings ( "unchecked" ) public < V > Key < V > getRoot ( ) { if ( this . getParent ( ) == null ) { return ( Key < V > ) this ; } else { return this . getParent ( ) . getRoot ( ) ; } }
|
Gets the root of a parent graph of keys . If a Key has no parent it is the root .
|
39,667
|
public boolean equivalent ( Ref < T > other ) { return ( other == null ) ? false : equals ( other . key ( ) ) ; }
|
A type - safe equivalence comparison
|
39,668
|
public static < V > Key < V > key ( com . google . appengine . api . datastore . Key raw ) { if ( raw == null ) { return null ; } else { return new Key < V > ( raw ) ; } }
|
Easy null - safe conversion of the raw key .
|
39,669
|
public static com . google . appengine . api . datastore . Key raw ( Key < ? > typed ) { if ( typed == null ) { return null ; } else { return typed . getRaw ( ) ; } }
|
Easy null - safe conversion of the typed key .
|
39,670
|
public static UUID fromString ( String name ) { UUID newUUID = new UUID ( ) ; newUUID . uuidValue = name ; return newUUID ; }
|
Constructs a new UUID from a string representation .
|
39,671
|
private void traceWriterInfo ( Object value , JsonWriter writer ) { if ( getLogger ( ) . isLoggable ( Level . INFO ) ) { getLogger ( ) . log ( Level . INFO , "Error on value <" + value + ">. Current output : <" + writer . getOutput ( ) + ">" ) ; } }
|
Trace the current writer state
|
39,672
|
private JClassType extractMappedType ( JClassType interfaceClass ) throws UnableToCompleteException { JClassType intf = interfaceClass . isInterface ( ) ; if ( intf == null ) { logger . log ( TreeLogger . Type . ERROR , "Expected " + interfaceClass + " to be an interface." ) ; throw new UnableToCompleteException ( ) ; } JClassType [ ] intfs = intf . getImplementedInterfaces ( ) ; for ( JClassType t : intfs ) { if ( t . getQualifiedSourceName ( ) . equals ( OBJECT_MAPPER_CLASS ) ) { return extractParameterizedType ( OBJECT_MAPPER_CLASS , t . isParameterized ( ) ) ; } else if ( t . getQualifiedSourceName ( ) . equals ( OBJECT_READER_CLASS ) ) { return extractParameterizedType ( OBJECT_READER_CLASS , t . isParameterized ( ) ) ; } else if ( t . getQualifiedSourceName ( ) . equals ( OBJECT_WRITER_CLASS ) ) { return extractParameterizedType ( OBJECT_WRITER_CLASS , t . isParameterized ( ) ) ; } } logger . log ( TreeLogger . Type . ERROR , "Expected " + interfaceClass + " to extend one of the following interface : " + OBJECT_MAPPER_CLASS + ", " + OBJECT_READER_CLASS + " or " + OBJECT_WRITER_CLASS ) ; throw new UnableToCompleteException ( ) ; }
|
Extract the type to map from the interface .
|
39,673
|
private JClassType extractParameterizedType ( String clazz , JParameterizedType parameterizedType ) throws UnableToCompleteException { if ( parameterizedType == null ) { logger . log ( TreeLogger . Type . ERROR , "Expected the " + clazz + " declaration to specify a parameterized type." ) ; throw new UnableToCompleteException ( ) ; } JClassType [ ] typeParameters = parameterizedType . getTypeArgs ( ) ; if ( typeParameters == null || typeParameters . length != 1 ) { logger . log ( TreeLogger . Type . ERROR , "Expected the " + clazz + " declaration to specify 1 parameterized type." ) ; throw new UnableToCompleteException ( ) ; } return typeParameters [ 0 ] ; }
|
Extract the parameter s type .
|
39,674
|
private MethodSpec buildConstructor ( JClassType mappedTypeClass ) { Optional < JsonRootName > jsonRootName = findFirstEncounteredAnnotationsOnAllHierarchy ( configuration , mappedTypeClass , JsonRootName . class ) ; String rootName ; if ( ! jsonRootName . isPresent ( ) || Strings . isNullOrEmpty ( jsonRootName . get ( ) . value ( ) ) ) { rootName = mappedTypeClass . getSimpleSourceName ( ) ; } else { rootName = jsonRootName . get ( ) . value ( ) ; } return MethodSpec . constructorBuilder ( ) . addModifiers ( Modifier . PUBLIC ) . addStatement ( "super($S)" , rootName ) . build ( ) ; }
|
Build the constructor .
|
39,675
|
private MethodSpec buildNewDeserializerMethod ( JClassType mappedTypeClass ) throws UnableToCompleteException { JDeserializerType type ; try { type = getJsonDeserializerFromType ( mappedTypeClass ) ; } catch ( UnsupportedTypeException e ) { logger . log ( Type . ERROR , "Cannot generate mapper due to previous errors : " + e . getMessage ( ) ) ; throw new UnableToCompleteException ( ) ; } return MethodSpec . methodBuilder ( "newDeserializer" ) . addModifiers ( Modifier . PROTECTED ) . addAnnotation ( Override . class ) . returns ( parameterizedName ( JsonDeserializer . class , mappedTypeClass ) ) . addStatement ( "return $L" , type . getInstance ( ) ) . build ( ) ; }
|
Build the new deserializer method .
|
39,676
|
private MethodSpec buildNewSerializerMethod ( JClassType mappedTypeClass ) throws UnableToCompleteException { JSerializerType type ; try { type = getJsonSerializerFromType ( mappedTypeClass ) ; } catch ( UnsupportedTypeException e ) { logger . log ( Type . ERROR , "Cannot generate mapper due to previous errors : " + e . getMessage ( ) ) ; throw new UnableToCompleteException ( ) ; } return MethodSpec . methodBuilder ( "newSerializer" ) . addModifiers ( Modifier . PROTECTED ) . addAnnotation ( Override . class ) . returns ( ParameterizedTypeName . get ( ClassName . get ( JsonSerializer . class ) , DEFAULT_WILDCARD ) ) . addStatement ( "return $L" , type . getInstance ( ) ) . build ( ) ; }
|
Build the new serializer method .
|
39,677
|
private static boolean hasTz ( String pattern ) { boolean inQuote = false ; for ( int i = 0 ; i < pattern . length ( ) ; i ++ ) { char ch = pattern . charAt ( i ) ; if ( inQuote ) { if ( ch == '\'' ) { if ( i + 1 < pattern . length ( ) && pattern . charAt ( i + 1 ) == '\'' ) { ++ i ; } else { inQuote = false ; } } continue ; } if ( "Zzv" . indexOf ( ch ) >= 0 ) { return true ; } if ( ch == '\'' ) { if ( i + 1 < pattern . length ( ) && pattern . charAt ( i + 1 ) == '\'' ) { i ++ ; } else { inQuote = true ; } } } return false ; }
|
Find if a pattern contains informations about the timezone .
|
39,678
|
protected T deserializeNullValue ( JsonReader reader , JsonDeserializationContext ctx , JsonDeserializerParameters params ) { reader . skipValue ( ) ; return null ; }
|
Deserialize the null value . This method allows children to override the default behaviour .
|
39,679
|
public void setBackReference ( String referenceName , Object reference , T value , JsonDeserializationContext ctx ) { throw new JsonDeserializationException ( "Cannot set a back reference to the type managed by this deserializer" ) ; }
|
Set the back reference .
|
39,680
|
public T deserialize ( String key , JsonDeserializationContext ctx ) throws JsonDeserializationException { if ( null == key ) { return null ; } return doDeserialize ( key , ctx ) ; }
|
Deserializes a key into an object .
|
39,681
|
public static < T extends Annotation > boolean isAnnotationPresent ( Class < T > annotation , List < ? extends HasAnnotations > hasAnnotationsList ) { for ( HasAnnotations accessor : hasAnnotationsList ) { if ( accessor . isAnnotationPresent ( annotation ) ) { return true ; } } return false ; }
|
Returns true when one of the type has the specified annotation
|
39,682
|
public int compareTo ( GeoPt o ) { int latResult = ( ( Float ) latitude ) . compareTo ( o . latitude ) ; if ( latResult != 0 ) { return latResult ; } return ( ( Float ) longitude ) . compareTo ( o . longitude ) ; }
|
Sort first by latitude then by longitude
|
39,683
|
public void serializePropertyName ( JsonWriter writer , T bean , JsonSerializationContext ctx ) { writer . unescapeName ( propertyName ) ; }
|
Serializes the property name
|
39,684
|
public void serialize ( JsonWriter writer , T bean , JsonSerializationContext ctx ) { getSerializer ( ) . serialize ( writer , getValue ( bean , ctx ) , ctx , getParameters ( ) ) ; }
|
Serializes the property defined for this instance .
|
39,685
|
public Optional < JClassType > getMixInAnnotations ( JType type ) { return Optional . fromNullable ( mixInAnnotations . get ( type . getQualifiedSourceName ( ) ) ) ; }
|
Return the mixin type for the given type
|
39,686
|
private void traceReaderInfo ( JsonReader reader ) { if ( null != reader && getLogger ( ) . isLoggable ( Level . INFO ) ) { getLogger ( ) . log ( Level . INFO , "Error at line " + reader . getLineNumber ( ) + " and column " + reader . getColumnNumber ( ) + " of input <" + reader . getInput ( ) + ">" ) ; } }
|
Trace the current reader state
|
39,687
|
protected final BeanJsonMapperInfo getMapperInfo ( JClassType beanType ) throws UnableToCompleteException { BeanJsonMapperInfo mapperInfo = typeOracle . getBeanJsonMapperInfo ( beanType ) ; if ( null != mapperInfo ) { return mapperInfo ; } boolean samePackage = true ; String packageName = beanType . getPackage ( ) . getName ( ) ; if ( packageName . startsWith ( "java." ) ) { packageName = "gwtjackson." + packageName ; samePackage = false ; } BeanInfo beanInfo = BeanProcessor . processBean ( logger , typeOracle , configuration , beanType ) ; PropertiesContainer properties = PropertyProcessor . findAllProperties ( configuration , logger , typeOracle , beanInfo , samePackage ) ; beanInfo = BeanProcessor . processProperties ( configuration , logger , typeOracle , beanInfo , properties ) ; StringBuilder builder = new StringBuilder ( beanType . getSimpleSourceName ( ) ) ; JClassType enclosingType = beanType . getEnclosingType ( ) ; while ( null != enclosingType ) { builder . insert ( 0 , enclosingType . getSimpleSourceName ( ) + "_" ) ; enclosingType = enclosingType . getEnclosingType ( ) ; } boolean isSpecificToMapper = configuration . isSpecificToMapper ( beanType ) ; if ( isSpecificToMapper ) { JClassType rootMapperClass = configuration . getRootMapperClass ( ) ; builder . insert ( 0 , '_' ) . insert ( 0 , configuration . getRootMapperHash ( ) ) . insert ( 0 , '_' ) . insert ( 0 , rootMapperClass . getSimpleSourceName ( ) ) ; } String simpleSerializerClassName = builder . toString ( ) + "BeanJsonSerializerImpl" ; String simpleDeserializerClassName = builder . toString ( ) + "BeanJsonDeserializerImpl" ; mapperInfo = new BeanJsonMapperInfo ( beanType , packageName , samePackage , simpleSerializerClassName , simpleDeserializerClassName , beanInfo , properties . getProperties ( ) ) ; typeOracle . addBeanJsonMapperInfo ( beanType , mapperInfo ) ; return mapperInfo ; }
|
Returns the mapper information for the given type . The result is cached .
|
39,688
|
private CodeBlock constructorCallCode ( ClassName className , ImmutableList < ? extends JParameterizedMapper > parameters ) { CodeBlock . Builder builder = CodeBlock . builder ( ) ; builder . add ( "new $T" , className ) ; return methodCallCodeWithJParameterizedMapperParameters ( builder , parameters ) ; }
|
Build the code to call the constructor of a class
|
39,689
|
private CodeBlock . Builder initMethodCallCode ( MapperInstance instance ) { CodeBlock . Builder builder = CodeBlock . builder ( ) ; if ( null == instance . getInstanceCreationMethod ( ) . isConstructor ( ) ) { builder . add ( "$T.$L" , rawName ( instance . getMapperType ( ) ) , instance . getInstanceCreationMethod ( ) . getName ( ) ) ; } else { builder . add ( "new $T" , typeName ( instance . getMapperType ( ) ) ) ; } return builder ; }
|
Initialize the code builder to create a mapper .
|
39,690
|
public static byte [ ] fromBase64 ( String data ) { if ( data == null ) { return null ; } int len = data . length ( ) ; assert ( len % 4 ) == 0 ; if ( len == 0 ) { return new byte [ 0 ] ; } char [ ] chars = new char [ len ] ; data . getChars ( 0 , len , chars , 0 ) ; int olen = 3 * ( len / 4 ) ; if ( chars [ len - 2 ] == '=' ) { -- olen ; } if ( chars [ len - 1 ] == '=' ) { -- olen ; } byte [ ] bytes = new byte [ olen ] ; int iidx = 0 ; int oidx = 0 ; while ( iidx < len ) { int c0 = base64Values [ chars [ iidx ++ ] & 0xff ] ; int c1 = base64Values [ chars [ iidx ++ ] & 0xff ] ; int c2 = base64Values [ chars [ iidx ++ ] & 0xff ] ; int c3 = base64Values [ chars [ iidx ++ ] & 0xff ] ; int c24 = ( c0 << 18 ) | ( c1 << 12 ) | ( c2 << 6 ) | c3 ; bytes [ oidx ++ ] = ( byte ) ( c24 >> 16 ) ; if ( oidx == olen ) { break ; } bytes [ oidx ++ ] = ( byte ) ( c24 >> 8 ) ; if ( oidx == olen ) { break ; } bytes [ oidx ++ ] = ( byte ) c24 ; } return bytes ; }
|
Decode a base64 string into a byte array .
|
39,691
|
private void buildNewInstanceMethodForBuilder ( MethodSpec . Builder newInstanceMethodBuilder ) { newInstanceMethodBuilder . addStatement ( "return new $T(builderDeserializer.deserializeInline(reader, ctx, params, null, null, null, bufferedProperties).build(), bufferedProperties)" , parameterizedName ( Instance . class , beanInfo . getType ( ) ) ) ; }
|
Generate the instance builder class body for a builder .
|
39,692
|
private void buildNewInstanceMethodForDefaultConstructor ( MethodSpec . Builder newInstanceMethodBuilder , MethodSpec createMethod ) { newInstanceMethodBuilder . addStatement ( "return new $T($N(), bufferedProperties)" , parameterizedName ( Instance . class , beanInfo . getType ( ) ) , createMethod ) ; }
|
Generate the instance builder class body for a default constructor . We directly instantiate the bean at the builder creation and we set the properties to it
|
39,693
|
private void buildNewInstanceMethodForConstructorOrFactoryMethodDelegation ( MethodSpec . Builder newInstanceMethodBuilder , MethodSpec createMethod ) { String param = String . format ( "%s%s.deserialize(reader, ctx)" , INSTANCE_BUILDER_DESERIALIZER_PREFIX , String . format ( INSTANCE_BUILDER_VARIABLE_FORMAT , 0 ) ) ; newInstanceMethodBuilder . addStatement ( "return new $T($N($L), bufferedProperties)" , parameterizedName ( Instance . class , beanInfo . getType ( ) ) , createMethod , param ) ; }
|
Generate the instance builder class body for a constructor or factory method with delegation .
|
39,694
|
private void buildConstructor ( TypeSpec . Builder typeBuilder ) { MethodSpec . Builder constructorBuilder = MethodSpec . constructorBuilder ( ) . addModifiers ( Modifier . PUBLIC ) ; if ( ! beanInfo . getParameterizedTypes ( ) . isEmpty ( ) ) { Class mapperClass ; String mapperNameFormat ; if ( isSerializer ( ) ) { mapperClass = Serializer . class ; mapperNameFormat = TYPE_PARAMETER_SERIALIZER_FIELD_NAME ; } else { mapperClass = Deserializer . class ; mapperNameFormat = TYPE_PARAMETER_DESERIALIZER_FIELD_NAME ; } for ( int i = 0 ; i < beanInfo . getParameterizedTypes ( ) . size ( ) ; i ++ ) { JClassType argType = beanInfo . getParameterizedTypes ( ) . get ( i ) ; String mapperName = String . format ( mapperNameFormat , i ) ; TypeName mapperType = parameterizedName ( mapperClass , argType ) ; FieldSpec field = FieldSpec . builder ( mapperType , mapperName , Modifier . PRIVATE , Modifier . FINAL ) . build ( ) ; typeBuilder . addField ( field ) ; ParameterSpec parameter = ParameterSpec . builder ( mapperType , mapperName ) . build ( ) ; constructorBuilder . addParameter ( parameter ) ; constructorBuilder . addStatement ( "this.$N = $N" , field , parameter ) ; } } typeBuilder . addMethod ( constructorBuilder . build ( ) ) ; }
|
Build the constructor and the final fields .
|
39,695
|
private MethodSpec buildClassGetterMethod ( ) { return MethodSpec . methodBuilder ( isSerializer ( ) ? "getSerializedType" : "getDeserializedType" ) . addModifiers ( Modifier . PUBLIC ) . addAnnotation ( Override . class ) . returns ( Class . class ) . addStatement ( "return $T.class" , rawName ( beanInfo . getType ( ) ) ) . build ( ) ; }
|
Build the method that returns the class of the mapped type .
|
39,696
|
protected final void buildCommonPropertyParameters ( CodeBlock . Builder paramBuilder , PropertyInfo property ) { if ( property . getFormat ( ) . isPresent ( ) ) { JsonFormat format = property . getFormat ( ) . get ( ) ; if ( ! Strings . isNullOrEmpty ( format . pattern ( ) ) ) { paramBuilder . add ( "\n.setPattern($S)" , format . pattern ( ) ) ; } paramBuilder . add ( "\n.setShape($T.$L)" , Shape . class , format . shape ( ) . name ( ) ) ; if ( ! Strings . isNullOrEmpty ( format . locale ( ) ) && ! JsonFormat . DEFAULT_LOCALE . equals ( format . locale ( ) ) ) { logger . log ( Type . WARN , "JsonFormat.locale is not supported by default" ) ; paramBuilder . add ( "\n.setLocale($S)" , format . locale ( ) ) ; } } if ( property . getIgnoredProperties ( ) . isPresent ( ) ) { for ( String ignoredProperty : property . getIgnoredProperties ( ) . get ( ) ) { paramBuilder . add ( "\n.addIgnoredProperty($S)" , ignoredProperty ) ; } } }
|
Add the common property parameters to the code builder .
|
39,697
|
public DockerVersionInfo getVersionInfo ( ) { String json = getServiceEndPoint ( ) . path ( "/version" ) . request ( MediaType . APPLICATION_JSON_TYPE ) . get ( String . class ) ; return toObject ( json , DockerVersionInfo . class ) ; }
|
Returns the Docker version information
|
39,698
|
public String commitContainer ( String container , Optional < String > repo , Optional < String > tag , Optional < String > comment , Optional < String > author ) { WebTarget request = getServiceEndPoint ( ) . path ( "/commit" ) . queryParam ( "container" , container ) . queryParam ( "repo" , repo . orElse ( null ) ) . queryParam ( "tag" , tag . orElse ( null ) ) . queryParam ( "comment" , comment . orElse ( null ) ) . queryParam ( "author" , author . orElse ( null ) ) ; String json = request . request ( MediaType . APPLICATION_JSON_TYPE ) . method ( HttpMethod . POST , String . class ) ; ContainerCommitResponse result = toObject ( json , ContainerCommitResponse . class ) ; return result . getId ( ) ; }
|
Create a new image from a container s changes
|
39,699
|
public String buildImage ( byte [ ] tarArchive , Optional < String > name , Optional < String > buildArguments ) { Response response = getServiceEndPoint ( ) . path ( "/build" ) . queryParam ( "q" , true ) . queryParam ( "t" , name . orElse ( null ) ) . queryParam ( "buildargs" , UriComponent . encode ( buildArguments . orElse ( null ) , UriComponent . Type . QUERY_PARAM_SPACE_ENCODED ) ) . queryParam ( "forcerm" ) . request ( MediaType . APPLICATION_JSON_TYPE ) . header ( REGISTRY_AUTH_HEADER , getRegistryAuthHeaderValue ( ) ) . post ( Entity . entity ( tarArchive , "application/tar" ) ) ; InputStream inputStream = ( InputStream ) response . getEntity ( ) ; String imageId = parseSteamForImageId ( inputStream ) ; if ( imageId == null ) { throw new DockerException ( "Can't obtain ID from build output stream." ) ; } return imageId ; }
|
Builds an image based on the passed tar archive . Optionally names & ; tags the image
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.