idx int64 0 41.2k | question stringlengths 74 4.04k | target stringlengths 7 750 |
|---|---|---|
30,300 | public void setInteractive ( final boolean INTERACTIVE ) { if ( null == interactive ) { _interactive = INTERACTIVE ; fireUpdateEvent ( INTERACTIVITY_EVENT ) ; } else { interactive . set ( INTERACTIVE ) ; } } | Defines if the gauge is in interactive mode . This is currently implemented in the radial gauges that have a knob . If interactive == true the knob can be pressed to trigger something . |
30,301 | public void setButtonTooltipText ( final String TEXT ) { if ( null == buttonTooltipText ) { _buttonTooltipText = TEXT ; fireUpdateEvent ( REDRAW_EVENT ) ; } else { buttonTooltipText . set ( TEXT ) ; } } | Defines the text that will be shown in the button tooltip . The knob in the radial gauges acts as button if interactive == true . |
30,302 | public void setAlertMessage ( final String MESSAGE ) { if ( null == alertMessage ) { _alertMessage = MESSAGE ; fireUpdateEvent ( ALERT_EVENT ) ; } else { alertMessage . set ( MESSAGE ) ; } } | Defines the text that could be used in a tooltip as an alert message . |
30,303 | public void stop ( ) { setLedOn ( false ) ; if ( null != blinkFuture ) { blinkFuture . cancel ( true ) ; } if ( null != blinkService ) { blinkService . shutdownNow ( ) ; } } | Calling this method will stop all threads . This is needed when using JavaFX on mobile devices when the device goes to sleep mode . |
30,304 | public void setValue ( final double VALUE ) { if ( null == value ) { _value = VALUE ; } else { value . set ( VALUE ) ; } fireMarkerEvent ( VALUE_CHANGED_EVENT ) ; } | Defines the value for the marker |
30,305 | public void setText ( final String TEXT ) { if ( null == text ) { _text = TEXT ; } else { text . set ( TEXT ) ; } fireMarkerEvent ( TEXT_CHANGED_EVENT ) ; } | Defines a text for this marker . This text can be used as a description and will be used in tooltips . |
30,306 | public void setColor ( final Color COLOR ) { if ( null == color ) { _color = COLOR ; } else { color . set ( COLOR ) ; } fireMarkerEvent ( COLOR_CHANGED_EVENT ) ; } | Defines the color that will be used to colorize the marker . |
30,307 | public void setMarkerType ( final MarkerType TYPE ) { if ( null == markerType ) { _markerType = null == TYPE ? MarkerType . STANDARD : TYPE ; } else { markerType . set ( TYPE ) ; } fireMarkerEvent ( TYPE_CHANGED_EVENT ) ; } | Defines the shape that will be used to visualize the marker . The values are STANDARD DOT TRAPEZOID . |
30,308 | @ SuppressWarnings ( "unused" ) public void onPaymentSuccess ( String razorpayPaymentID ) { try { Toast . makeText ( this , "Payment Successful: " + razorpayPaymentID , Toast . LENGTH_SHORT ) . show ( ) ; } catch ( Exception e ) { Log . e ( TAG , "Exception in onPaymentSuccess" , e ) ; } } | The name of the function has to be onPaymentSuccess Wrap your code in try catch as shown to ensure that this method runs correctly |
30,309 | @ SuppressWarnings ( "unused" ) public void onPaymentError ( int code , String response ) { try { Toast . makeText ( this , "Payment failed: " + code + " " + response , Toast . LENGTH_SHORT ) . show ( ) ; } catch ( Exception e ) { Log . e ( TAG , "Exception in onPaymentError" , e ) ; } } | The name of the function has to be onPaymentError Wrap your code in try catch as shown to ensure that this method runs correctly |
30,310 | public static < T extends View > T mount ( T v , Renderable r ) { Mount m = new Mount ( v , r ) ; mounts . put ( v , m ) ; render ( v ) ; return v ; } | Mounts a renderable function defining the layout into a View . If host is a viewgroup it is assumed to be empty so the Renderable would define what its child views would be . |
30,311 | @ SuppressWarnings ( "unchecked" ) public static < T extends View > T currentView ( ) { if ( currentMount == null ) { return null ; } return ( T ) currentMount . iterator . currentView ( ) ; } | Returns currently rendered View . It allows to access the real view from inside the Renderable . |
30,312 | static public List < ? > getContent ( NDArray array ) { Object content = array . getContent ( ) ; return asJavaList ( array , ( List < ? > ) content ) ; } | Gets the payload of a one - dimensional array . |
30,313 | static public List < ? > getContent ( NDArray array , String key ) { Map < String , ? > content = ( Map < String , ? > ) array . getContent ( ) ; return asJavaList ( array , ( List < ? > ) content . get ( key ) ) ; } | Gets the payload of the specified dimension of a multi - dimensional array . |
30,314 | private void launchServer ( ) { try { log . info ( "Configuring Android SDK" ) ; if ( config . getAndroidHome ( ) != null ) { AndroidSdk . setAndroidHome ( config . getAndroidHome ( ) ) ; } if ( config . getAndroidSdkVersion ( ) != null ) { AndroidSdk . setAndroidSdkVersion ( config . getAndroidSdkVersion ( ) ) ; } if ( config . getBuildToolsVersion ( ) != null ) { AndroidSdk . setBuildToolsVersion ( config . getBuildToolsVersion ( ) ) ; } if ( config . getAvdManager ( ) != null ) { AndroidSdk . setAvdManagerHome ( config . getAvdManager ( ) ) ; } if ( config . getAdbHome ( ) != null ) { AndroidSdk . setAdbHome ( config . getAdbHome ( ) ) ; } log . info ( "Using Android SDK installed in: " + AndroidSdk . androidHome ( ) ) ; log . info ( "Using Android SDK version: " + AndroidSdk . androidSdkFolder ( ) . getAbsolutePath ( ) ) ; log . info ( "Using build-tools in: " + AndroidSdk . buildToolsFolder ( ) . getAbsolutePath ( ) ) ; log . info ( "Using adb in: " + AndroidSdk . adb ( ) . getAbsolutePath ( ) ) ; log . info ( "Starting Selendroid standalone on port " + config . getPort ( ) ) ; server = new SelendroidStandaloneServer ( config ) ; server . start ( ) ; } catch ( AndroidSdkException e ) { log . severe ( "Selendroid standalone was not able to interact with the Android SDK: " + e . getMessage ( ) ) ; log . severe ( "Please make sure you have the latest version with the latest updates installed: " ) ; log . severe ( "http://developer.android.com/sdk/index.html" ) ; throw Throwables . propagate ( e ) ; } catch ( Exception e ) { log . severe ( "Error building server: " + e . getMessage ( ) ) ; throw Throwables . propagate ( e ) ; } Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { public void run ( ) { log . info ( "Shutting down Selendroid standalone" ) ; stopSelendroid ( ) ; } } ) ; } | Starts the Selendroid standalone server and exits immediately . This method might return before the server is ready to receive requests . |
30,315 | public void launchSelendroid ( ) { launchServer ( ) ; if ( config . isGrid ( ) ) { HttpClientUtil . waitForServer ( server . getPort ( ) , 3 , TimeUnit . MINUTES ) ; } else { HttpClientUtil . waitForServer ( server . getPort ( ) , 20 , TimeUnit . SECONDS ) ; } } | Starts the Selendroid standalone server and waits until it s ready to accept requests . |
30,316 | public AndroidElement get ( String elementId ) { AndroidElement element = cache . get ( elementId ) ; if ( element instanceof AndroidNativeElement ) { if ( ! ViewHierarchyAnalyzer . getDefaultInstance ( ) . isViewChieldOfCurrentRootView ( ( ( AndroidNativeElement ) element ) . getView ( ) ) ) { return null ; } } return element ; } | Uses the generated Id to look up elements |
30,317 | public static List < CallLogEntry > getAllLogsOfDuration ( List < CallLogEntry > logs , int duration , boolean greaterthan ) { List < CallLogEntry > list = new ArrayList < CallLogEntry > ( ) ; for ( CallLogEntry log : logs ) { if ( log . duration < duration ^ greaterthan ) { list . add ( log ) ; } } return list ; } | duration specifies call duration to test against . |
30,318 | public static boolean containsLogFromNumber ( List < CallLogEntry > logs , String number ) { for ( CallLogEntry log : logs ) { if ( log . number . equals ( number ) ) { return true ; } } return false ; } | returns true if call log of specified number exists |
30,319 | private InputStream getResourceAsStream ( String resource ) { InputStream is = getClass ( ) . getResourceAsStream ( resource ) ; if ( is == null ) { try { is = new FileInputStream ( new File ( resource ) ) ; } catch ( FileNotFoundException e ) { } } if ( is == null ) { throw new SelendroidException ( "The resource '" + resource + "' was not found." ) ; } return is ; } | Loads resources as stream and the main reason for having the method is because it can be use while testing and in production for loading files from within jar file . |
30,320 | public void setSystemProperty ( String propertyName , String value ) { if ( Strings . isNullOrEmpty ( propertyName ) ) { throw new IllegalArgumentException ( "Property name can't be empty." ) ; } execute ( "-selendroid-setAndroidOsSystemProperty" , ImmutableMap . of ( "propertyName" , propertyName , "value" , value ) ) ; } | Sets a Java System Property . |
30,321 | private JSONObject getNodeConfig ( ) { JSONObject res = new JSONObject ( ) ; try { res . put ( "class" , "org.openqa.grid.common.RegistrationRequest" ) ; res . put ( "configuration" , getConfiguration ( ) ) ; JSONArray caps = new JSONArray ( ) ; JSONArray devices = driver . getSupportedDevices ( ) ; for ( int i = 0 ; i < devices . length ( ) ; i ++ ) { JSONObject device = ( JSONObject ) devices . get ( i ) ; for ( int x = 0 ; x < driver . getSupportedApps ( ) . length ( ) ; x ++ ) { caps . put ( getDeviceConfig ( device , driver . getSupportedApps ( ) . getJSONObject ( x ) ) ) ; } } res . put ( "capabilities" , caps ) ; } catch ( JSONException e ) { throw new SelendroidException ( e . getMessage ( ) , e ) ; } return res ; } | Get the node configuration and capabilities for Grid registration |
30,322 | private JSONObject getConfiguration ( ) throws JSONException { JSONObject configuration = new JSONObject ( ) ; configuration . put ( "port" , config . getPort ( ) ) ; configuration . put ( "register" , true ) ; if ( config . getProxy ( ) != null ) { configuration . put ( "proxy" , config . getProxy ( ) ) ; } else { configuration . put ( "proxy" , "org.openqa.grid.selenium.proxy.DefaultRemoteProxy" ) ; } configuration . put ( "role" , "node" ) ; configuration . put ( "registerCycle" , config . getRegisterCycle ( ) ) ; if ( config . getMaxSession ( ) == 0 ) { configuration . put ( "maxSession" , driver . getSupportedDevices ( ) . length ( ) ) ; } else { configuration . put ( "maxSession" , config . getMaxSession ( ) ) ; } configuration . put ( "browserTimeout" , config . getSessionTimeoutMillis ( ) / 1000 ) ; configuration . put ( "cleanupCycle" , config . getCleanupCycle ( ) ) ; configuration . put ( "timeout" , config . getTimeout ( ) ) ; configuration . put ( "nodePolling" , config . getNodePolling ( ) ) ; configuration . put ( "unregisterIfStillDownAfter" , config . getUnregisterIfStillDownAfter ( ) ) ; configuration . put ( "downPollingLimit" , config . getDownPollingLimit ( ) ) ; configuration . put ( "nodeStatusCheckTimeout" , config . getNodeStatusCheckTimeout ( ) ) ; configuration . put ( "hubHost" , hub . getHost ( ) ) ; configuration . put ( "hubPort" , hub . getPort ( ) ) ; configuration . put ( "seleniumProtocol" , "WebDriver" ) ; configuration . put ( "host" , config . getServerHost ( ) ) ; configuration . put ( "remoteHost" , "http://" + config . getServerHost ( ) + ":" + config . getPort ( ) ) ; return configuration ; } | Extracts the configuration . |
30,323 | protected void startServerImpl ( ) { SelendroidLogger . info ( "*** ServerInstrumentation#startServerImpl() ***" ) ; if ( serverThread != null && serverThread . isAlive ( ) ) { return ; } if ( serverThread != null ) { stopServer ( ) ; } serverThread = new HttpdThread ( this , serverPort ) ; serverThread . startServer ( ) ; } | specific logic to a subclass |
30,324 | public TouchActionBuilder pointerDown ( WebElement element , int x , int y ) { Preconditions . checkState ( ! isDown ) ; Map < String , Object > params = getTouchParameters ( element , x , y ) ; addAction ( TouchActionName . POINTER_DOWN , params ) ; isDown = true ; return this ; } | Places pointer down at an offset from the top left corner of the specified WebElement |
30,325 | public TouchActionBuilder pointerMove ( WebElement element , int x , int y ) { Preconditions . checkState ( isDown ) ; Map < String , Object > params = getTouchParameters ( element , x , y ) ; addAction ( TouchActionName . POINTER_MOVE , params ) ; return this ; } | Moves the pointer to a position offset from the top left corner of the specified WebElement This is only possible if the pointer is currently down . |
30,326 | protected void sleep ( ) { try { Thread . sleep ( sleepIntervalInMillis ) ; } catch ( InterruptedException exception ) { Thread . currentThread ( ) . interrupt ( ) ; throw new SelendroidException ( exception ) ; } } | Sleeps for a few milliseconds . |
30,327 | public void addToAppsStore ( File file ) throws AndroidSdkException { AndroidApp app = null ; try { app = selendroidApkBuilder . resignApp ( file ) ; } catch ( Exception e ) { throw new SessionNotCreatedException ( "An error occurred while resigning the app '" + file . getName ( ) + "'. " , e ) ; } String appId = null ; try { appId = app . getAppId ( ) ; } catch ( AndroidSdkException e ) { log . info ( "Ignoring app because an error occurred reading the app details: " + file . getAbsolutePath ( ) ) ; log . info ( e . getMessage ( ) ) ; } if ( appId != null && ! appsStore . containsKey ( appId ) ) { appsStore . put ( appId , app ) ; log . info ( "App " + appId + " has been added to selendroid standalone server." ) ; } } | This function will sign an android app and add it to the App Store . The function is made public because it also be invoked by the Folder Monitor each time a new application dropped into this folder . |
30,328 | private void startFolderMonitor ( ) { if ( serverConfiguration . getAppFolderToMonitor ( ) != null ) { try { folderMonitor = new FolderMonitor ( this , serverConfiguration ) ; folderMonitor . start ( ) ; } catch ( IOException e ) { log . warning ( "Could not monitor the given folder: " + serverConfiguration . getAppFolderToMonitor ( ) ) ; } } } | Applications folder . |
30,329 | private String readFile ( File file ) { BufferedReader reader = null ; try { reader = new BufferedReader ( new FileReader ( file ) ) ; String line = null ; StringBuilder sb = new StringBuilder ( ) ; String separator = System . getProperty ( "line.separator" ) ; while ( ( line = reader . readLine ( ) ) != null ) { sb . append ( line ) . append ( separator ) ; } return sb . toString ( ) ; } catch ( FileNotFoundException e ) { throw new RuntimeException ( "We already made sure the extra args file exists" , e ) ; } catch ( IOException e ) { throw new RuntimeException ( "Error while reading from extra args file" , e ) ; } finally { if ( reader != null ) { try { reader . close ( ) ; } catch ( IOException e ) { SelendroidLogger . error ( "Failed to close reader for args file" , e ) ; } } } } | There s no nio on Android and it s not worth importing Apache commons |
30,330 | public static Intent createStartActivityIntent ( Context context , String mainActivityName ) { Intent intent = new Intent ( ) ; intent . setClassName ( context , mainActivityName ) ; intent . addFlags ( Intent . FLAG_ACTIVITY_NEW_TASK | Intent . FLAG_ACTIVITY_REORDER_TO_FRONT | Intent . FLAG_ACTIVITY_SINGLE_TOP | Intent . FLAG_ACTIVITY_CLEAR_TOP ) ; intent . setAction ( Intent . ACTION_MAIN ) ; intent . addCategory ( Intent . CATEGORY_LAUNCHER ) ; return intent ; } | Create an intent to start an activity for both ServerInstrumentation and LightweightInstrumentation |
30,331 | public static Intent createUriIntent ( String intentAction , String intentUri ) { if ( intentAction == null ) { intentAction = Intent . ACTION_VIEW ; } return new Intent ( intentAction , Uri . parse ( intentUri ) ) . addFlags ( Intent . FLAG_ACTIVITY_NEW_TASK | Intent . FLAG_ACTIVITY_REORDER_TO_FRONT | Intent . FLAG_ACTIVITY_SINGLE_TOP | Intent . FLAG_ACTIVITY_CLEAR_TOP ) ; } | Create an implicit intent based on the given URI . |
30,332 | public static Intent createStartServiceIntent ( Context context , String serviceClassName , String intentAction ) { Intent intent = intentAction != null ? new Intent ( intentAction ) : new Intent ( ) ; return intent . setClassName ( context , serviceClassName ) ; } | Create an Intent to start a service using the given class name and action . |
30,333 | private List < String > getDomainsFromUrl ( URL url ) { String host = url . getHost ( ) ; String [ ] paths = new String [ ] { } ; if ( url . getPath ( ) != null ) { paths = url . getPath ( ) . split ( "/" ) ; } List < String > domains = new ArrayList < String > ( paths . length + 1 ) ; StringBuilder relative = new StringBuilder ( ) . append ( "http://" ) . append ( host ) . append ( "/" ) ; domains . add ( relative . toString ( ) ) ; for ( String path : paths ) { if ( path . length ( ) > 0 ) { relative . append ( path ) . append ( "/" ) ; domains . add ( relative . toString ( ) ) ; } } return domains ; } | Gets the list of domains associated to a URL . |
30,334 | public static SelendroidResponse forCatchAllError ( String sessionId , Throwable e ) { try { return new SelendroidResponse ( sessionId , StatusCode . UNKNOWN_ERROR . getCode ( ) , e , CATCH_ALL_ERROR_MESSAGE_PREFIX ) ; } catch ( JSONException err ) { return new SelendroidResponse ( sessionId , StatusCode . UNKNOWN_ERROR . getCode ( ) ) ; } } | It is currently hard to detect whether a test failed because of a legitimate error by a developer or because something is going wrong in selendroid internals . This response marks error responses from the server that indicate something has gone wrong in the internals of selendroid . |
30,335 | public void release ( AndroidDevice device , AndroidApp aut ) { log . info ( "Releasing device " + device ) ; if ( devicesInUse . contains ( device ) ) { if ( aut != null ) { try { device . kill ( aut ) ; } catch ( Exception e ) { log . log ( Level . WARNING , "Failed to kill android application when releasing device" , e ) ; } if ( clearData ) { try { device . clearUserData ( aut ) ; } catch ( AndroidSdkException e ) { log . log ( Level . WARNING , "Failed to clear user data of application" , e ) ; } } } if ( device instanceof AndroidEmulator && ! ( aut instanceof InstalledAndroidApp ) && ! keepEmulator ) { AndroidEmulator emulator = ( AndroidEmulator ) device ; try { emulator . stop ( ) ; } catch ( AndroidDeviceException e ) { log . severe ( "Failed to stop emulator: " + e . getMessage ( ) ) ; } androidEmulatorPortFinder . release ( emulator . getPort ( ) ) ; } devicesInUse . remove ( device ) ; } } | After a test session a device should be released . That means id will be removed from the list of devices in use and in case of an emulator it will be stopped . |
30,336 | protected synchronized void addDeviceToStore ( AndroidDevice device ) throws AndroidDeviceException { if ( androidDevices . containsKey ( device . getTargetPlatform ( ) ) ) { List < AndroidDevice > platformDevices = androidDevices . get ( device . getTargetPlatform ( ) ) ; if ( ! platformDevices . contains ( device ) ) { platformDevices . add ( device ) ; } } else { androidDevices . put ( device . getTargetPlatform ( ) , Lists . newArrayList ( device ) ) ; } } | Internal method to add an actual device to the store . |
30,337 | public void send ( final CharSequence text ) { final KeyCharacterMap characterMap = KeyCharacterMap . load ( KeyCharacterMap . VIRTUAL_KEYBOARD ) ; long timeout = System . currentTimeMillis ( ) + serverInstrumentation . getAndroidWait ( ) . getTimeoutInMillis ( ) ; SelendroidLogger . info ( "Using timeout of " + timeout + " milli seconds." ) ; done = false ; instrumentation . runOnMainSync ( new Runnable ( ) { public void run ( ) { for ( int i = 0 ; i < text . length ( ) ; i ++ ) { char c = text . charAt ( i ) ; int code = WebViewKeys . getKeyEventFromUnicodeKey ( c ) ; if ( code != - 1 ) { webview . dispatchKeyEvent ( new KeyEvent ( KeyEvent . ACTION_DOWN , code ) ) ; webview . dispatchKeyEvent ( new KeyEvent ( KeyEvent . ACTION_UP , code ) ) ; } else { KeyEvent [ ] arr = characterMap . getEvents ( new char [ ] { c } ) ; if ( arr != null ) { for ( int j = 0 ; j < arr . length ; j ++ ) { webview . dispatchKeyEvent ( arr [ j ] ) ; } } } } done = true ; } } ) ; } | Sends key strokes to the given text to the element in focus within the webview . |
30,338 | public SelendroidCapabilities addBootstrapClass ( String className ) { String currentClassNames = getBootstrapClassNames ( ) ; if ( currentClassNames == null || currentClassNames . isEmpty ( ) ) { setCapability ( BOOTSTRAP_CLASS_NAMES , className ) ; } else { setCapability ( BOOTSTRAP_CLASS_NAMES , currentClassNames + "," + className ) ; } return this ; } | Adds a class to run on app startup . Class names are stored as a string separated by commas . |
30,339 | private String getDefaultVersion ( Set < String > keys , String appName ) { SortedSet < String > listOfApps = new TreeSet < String > ( ) ; for ( String key : keys ) { if ( key . split ( ":" ) [ 0 ] . contentEquals ( appName ) ) { listOfApps . add ( key ) ; } } return listOfApps . size ( ) > 0 ? listOfApps . last ( ) : null ; } | the latest version of the app . |
30,340 | private Boolean getBooleanCapability ( String key ) { Object o = getRawCapabilities ( ) . get ( key ) ; if ( o == null ) { return null ; } else if ( o instanceof Boolean ) { return ( Boolean ) o ; } else if ( o instanceof String && ( "true" . equalsIgnoreCase ( ( String ) o ) || "false" . equalsIgnoreCase ( ( String ) o ) ) ) { return Boolean . valueOf ( ( String ) o ) ; } else { throw new ClassCastException ( String . format ( "DesiredCapability %s's value should be boolean: found value %s of type %s" , key , o . toString ( ) , o . getClass ( ) . getName ( ) ) ) ; } } | throws exception if user didn t pass the capability as a boolean or String parsable as boolean |
30,341 | public Point getLocation ( ) { JSONObject result = ( JSONObject ) driver . executeAtom ( AndroidAtoms . GET_TOP_LEFT_COORDINATES , null , this ) ; try { return new Point ( result . getInt ( "x" ) , result . getInt ( "y" ) ) ; } catch ( JSONException e ) { throw new SelendroidException ( e ) ; } } | Where on the page is the top left - hand corner of the rendered element? it s part of RenderedWebElement |
30,342 | protected void initializeAdbConnection ( ) { try { AndroidDebugBridge . init ( false ) ; } catch ( IllegalStateException e ) { if ( ! shouldKeepAdbAlive ) { log . log ( Level . WARNING , "AndroidDebugBridge may have been already initialized at this point. It is OK to proceed." , e ) ; } } bridge = AndroidDebugBridge . getBridge ( ) ; if ( bridge == null ) { bridge = AndroidDebugBridge . createBridge ( adbPath , false ) ; } IDevice [ ] devices = bridge . getDevices ( ) ; AndroidDebugBridge . addDeviceChangeListener ( this ) ; if ( devices . length > 0 ) { for ( int i = 0 ; i < devices . length ; i ++ ) { deviceConnected ( devices [ i ] ) ; log . info ( "my devices: " + devices [ i ] . getAvdName ( ) ) ; } } else { long timeout = System . currentTimeMillis ( ) + 2000 ; while ( ( devices = bridge . getDevices ( ) ) . length == 0 && System . currentTimeMillis ( ) < timeout ) { try { Thread . sleep ( 50 ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } if ( devices . length > 0 ) { for ( int i = 0 ; i < devices . length ; i ++ ) { deviceConnected ( devices [ i ] ) ; log . info ( "my devices: " + devices [ i ] . getAvdName ( ) ) ; } } } } | Initializes the AndroidDebugBridge and registers the DefaultHardwareDeviceManager with the AndroidDebugBridge device change listener . |
30,343 | public void shutdown ( ) { log . info ( "Notifying device listener about shutdown" ) ; for ( HardwareDeviceListener listener : deviceListeners ) { for ( AndroidDevice device : connectedDevices . values ( ) ) { listener . onDeviceDisconnected ( connectedDevices . get ( device ) ) ; } } log . info ( "Removing Device Manager listener from ADB" ) ; AndroidDebugBridge . removeDeviceChangeListener ( this ) ; if ( ! shouldKeepAdbAlive ) { AndroidDebugBridge . disconnectBridge ( ) ; } AndroidDebugBridge . terminate ( ) ; log . info ( "stopping Device Manager" ) ; } | Shutdown the AndroidDebugBridge and clean up all connected devices . |
30,344 | protected void onDraw ( Canvas canvas ) { super . onDraw ( canvas ) ; canvas . drawOval ( rectF , backgroundPaint ) ; float realProgress = progress * DEFAULT_MAX_VALUE / progressMax ; float angle = ( rightToLeft ? 360 : - 360 ) * realProgress / 100 ; canvas . drawArc ( rectF , startAngle , angle , false , foregroundPaint ) ; } | region Draw Method |
30,345 | protected void onMeasure ( int widthMeasureSpec , int heightMeasureSpec ) { final int height = getDefaultSize ( getSuggestedMinimumHeight ( ) , heightMeasureSpec ) ; final int width = getDefaultSize ( getSuggestedMinimumWidth ( ) , widthMeasureSpec ) ; final int min = Math . min ( width , height ) ; setMeasuredDimension ( min , min ) ; float highStroke = strokeWidth > backgroundStrokeWidth ? strokeWidth : backgroundStrokeWidth ; rectF . set ( 0 + highStroke / 2 , 0 + highStroke / 2 , min - highStroke / 2 , min - highStroke / 2 ) ; } | region Mesure Method |
30,346 | public void setProgressWithAnimation ( float progress , int duration ) { if ( progressAnimator != null ) { progressAnimator . cancel ( ) ; } progressAnimator = ValueAnimator . ofFloat ( this . progress , progress ) ; progressAnimator . setDuration ( duration ) ; progressAnimator . addUpdateListener ( new ValueAnimator . AnimatorUpdateListener ( ) { public void onAnimationUpdate ( ValueAnimator animation ) { float progress = ( Float ) animation . getAnimatedValue ( ) ; setProgress ( progress , true ) ; if ( indeterminateMode ) { float updateAngle = progress * 360 / 100 ; startAngle = DEFAULT_START_ANGLE + ( rightToLeft ? updateAngle : - updateAngle ) ; } } } ) ; progressAnimator . start ( ) ; } | Set the progress with an animation . |
30,347 | private int adjustAlpha ( int color , float factor ) { int alpha = Math . round ( Color . alpha ( color ) * factor ) ; int red = Color . red ( color ) ; int green = Color . green ( color ) ; int blue = Color . blue ( color ) ; return Color . argb ( alpha , red , green , blue ) ; } | Transparent the given color by the factor The more the factor closer to zero the more the color gets transparent |
30,348 | private JsonObject callGet ( final String urlString ) { return RetryUtils . retry ( new Callable < JsonObject > ( ) { public JsonObject call ( ) { return Json . parse ( RestClient . create ( urlString ) . withHeader ( "Authorization" , String . format ( "Bearer %s" , apiToken ) ) . withCaCertificate ( caCertificate ) . get ( ) ) . asObject ( ) ; } } , retries , NON_RETRYABLE_KEYWORDS ) ; } | Makes a REST call to Kubernetes API and returns the result JSON . |
30,349 | private SSLSocketFactory buildSslSocketFactory ( ) { try { KeyStore keyStore = KeyStore . getInstance ( KeyStore . getDefaultType ( ) ) ; keyStore . load ( null , null ) ; keyStore . setCertificateEntry ( "ca" , generateCertificate ( ) ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; tmf . init ( keyStore ) ; SSLContext context = SSLContext . getInstance ( "TLSv1.2" ) ; context . init ( null , tmf . getTrustManagers ( ) , null ) ; return context . getSocketFactory ( ) ; } catch ( Exception e ) { throw new KubernetesClientException ( "Failure in generating SSLSocketFactory" , e ) ; } } | Builds SSL Socket Factory with the public CA Certificate from Kubernetes Master . |
30,350 | private Certificate generateCertificate ( ) throws IOException , CertificateException { InputStream caInput = null ; try { CertificateFactory cf = CertificateFactory . getInstance ( "X.509" ) ; caInput = new ByteArrayInputStream ( caCertificate . getBytes ( "UTF-8" ) ) ; return cf . generateCertificate ( caInput ) ; } finally { IOUtil . closeResource ( caInput ) ; } } | Generates CA Certificate from the default CA Cert file or from the externally provided ca - certificate property . |
30,351 | public boolean isOK ( PublicKey key ) { try { final var digester = MessageDigest . getInstance ( get ( DIGEST_KEY ) . getString ( ) ) ; final var ser = unsigned ( ) ; final var digestValue = digester . digest ( ser ) ; final var cipher = Cipher . getInstance ( key . getAlgorithm ( ) ) ; cipher . init ( Cipher . DECRYPT_MODE , key ) ; final var sigDigest = cipher . doFinal ( getSignature ( ) ) ; return Arrays . equals ( digestValue , sigDigest ) ; } catch ( Exception e ) { return false ; } } | Returns true if the license is signed and the authenticity of the signature can be checked successfully using the key . |
30,352 | private Feature [ ] featuresSorted ( Set < String > excluded ) { return this . features . values ( ) . stream ( ) . filter ( f -> ! excluded . contains ( f . name ( ) ) ) . sorted ( Comparator . comparing ( Feature :: name ) ) . toArray ( Feature [ ] :: new ) ; } | Get all the features in an array except the excluded ones in sorted order . The sorting is done on the name . |
30,353 | public byte [ ] serialized ( ) { final var nameBuffer = name . getBytes ( StandardCharsets . UTF_8 ) ; final var typeLength = Integer . BYTES ; final var nameLength = Integer . BYTES + nameBuffer . length ; final var valueLength = type . fixedSize == VARIABLE_LENGTH ? Integer . BYTES + value . length : type . fixedSize ; final var buffer = ByteBuffer . allocate ( typeLength + nameLength + valueLength ) . putInt ( type . serialized ) . putInt ( nameBuffer . length ) ; if ( type . fixedSize == VARIABLE_LENGTH ) { buffer . putInt ( value . length ) ; } buffer . put ( nameBuffer ) . put ( value ) ; return buffer . array ( ) ; } | Convert a feature to byte array . The bytes will have the following structure |
30,354 | public License read ( IOFormat format ) throws IOException { switch ( format ) { case BINARY : return License . Create . from ( ByteArrayReader . readInput ( is ) ) ; case BASE64 : return License . Create . from ( Base64 . getDecoder ( ) . decode ( ByteArrayReader . readInput ( is ) ) ) ; case STRING : return License . Create . from ( new String ( ByteArrayReader . readInput ( is ) , StandardCharsets . UTF_8 ) ) ; } throw new IllegalArgumentException ( "License format " + format + " is unknown." ) ; } | Read the license from the input assuming that the format of the license on the input has the format specified by the argument . |
30,355 | public void write ( LicenseKeyPair pair , IOFormat format ) throws IOException { switch ( format ) { case BINARY : osPrivate . write ( pair . getPrivate ( ) ) ; osPublic . write ( pair . getPublic ( ) ) ; return ; case BASE64 : osPrivate . write ( Base64 . getEncoder ( ) . encode ( pair . getPrivate ( ) ) ) ; osPublic . write ( Base64 . getEncoder ( ) . encode ( pair . getPublic ( ) ) ) ; return ; } throw new IllegalArgumentException ( "Key format " + format + " is unknown." ) ; } | Write the key pair into the output files . |
30,356 | public void write ( License license , IOFormat format ) throws IOException { switch ( format ) { case BINARY : os . write ( license . serialized ( ) ) ; return ; case BASE64 : os . write ( Base64 . getEncoder ( ) . encode ( license . serialized ( ) ) ) ; return ; case STRING : os . write ( license . toString ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ; return ; } throw new IllegalArgumentException ( "License format " + format + " is unknown" ) ; } | Write the license into the output . |
30,357 | public byte [ ] getPrivate ( ) { keyNotNull ( pair . getPrivate ( ) ) ; Key key = pair . getPrivate ( ) ; return getKeyBytes ( key ) ; } | Get the byte representation of the private key as it is returned by the underlying security library . This is NOT the byte array that contains the algorithm at the start . This is the key in raw format . |
30,358 | public byte [ ] getPublic ( ) { keyNotNull ( pair . getPublic ( ) ) ; Key key = pair . getPublic ( ) ; return getKeyBytes ( key ) ; } | Get the byte representation of the public key as it is returned by the underlying security library . This is NOT the byte array that contains the algorithm at the start . This is the key in raw format . |
30,359 | public String getMachineIdString ( ) throws NoSuchAlgorithmException , SocketException , UnknownHostException { return calculator . getMachineIdString ( useNetwork , useHostName , useArchitecture ) ; } | Get the machine id as an UUID string . |
30,360 | public boolean assertUUID ( final UUID uuid ) throws NoSuchAlgorithmException , SocketException , UnknownHostException { return calculator . assertUUID ( uuid , useNetwork , useHostName , useArchitecture ) ; } | Asserts that the current machine has the UUID . |
30,361 | public String createSessionId ( final String sessionId ) { return isEncodeNodeIdInSessionId ( ) ? _sessionIdFormat . createSessionId ( sessionId , _nodeIdService . getMemcachedNodeId ( ) ) : sessionId ; } | Creates a new sessionId based on the given one usually by appending a randomly selected memcached node id . If the memcachedNodes were configured using a single node without nodeId the sessionId is returned unchanged . |
30,362 | public void setNodeAvailable ( final String nodeId , final boolean available ) { if ( _nodeIdService != null ) { _nodeIdService . setNodeAvailable ( nodeId , available ) ; } } | Mark the given nodeId as available as specified . |
30,363 | public boolean isValidForMemcached ( final String sessionId ) { if ( isEncodeNodeIdInSessionId ( ) ) { final String nodeId = _sessionIdFormat . extractMemcachedId ( sessionId ) ; if ( nodeId == null ) { LOG . debug ( "The sessionId does not contain a nodeId so that the memcached node could not be identified." ) ; return false ; } } return true ; } | Can be used to determine if the given sessionId can be used to interact with memcached . |
30,364 | public boolean canHitMemcached ( final String sessionId ) { if ( isEncodeNodeIdInSessionId ( ) ) { final String nodeId = _sessionIdFormat . extractMemcachedId ( sessionId ) ; if ( nodeId == null ) { LOG . debug ( "The sessionId does not contain a nodeId so that the memcached node could not be identified." ) ; return false ; } if ( ! _nodeIdService . isNodeAvailable ( nodeId ) ) { LOG . debug ( "The node " + nodeId + " is not available, therefore " + sessionId + " cannot be loaded from this memcached." ) ; return false ; } } return true ; } | Can be used to determine if the given sessionId can be used to interact with memcached . This also checks if the related memcached is available . |
30,365 | public String setNodeAvailableForSessionId ( final String sessionId , final boolean available ) { if ( _nodeIdService != null && isEncodeNodeIdInSessionId ( ) ) { final String nodeId = _sessionIdFormat . extractMemcachedId ( sessionId ) ; if ( nodeId != null ) { _nodeIdService . setNodeAvailable ( nodeId , available ) ; return nodeId ; } else { LOG . warn ( "Got sessionId without nodeId: " + sessionId ) ; } } return null ; } | Mark the memcached node encoded in the given sessionId as available or not . If nodeIds shall not be encoded in the sessionId or if the given sessionId does not contain a nodeId no action will be taken . |
30,366 | public String changeSessionIdForTomcatFailover ( final String sessionId , final String jvmRoute ) { final String newSessionId = jvmRoute != null && ! jvmRoute . trim ( ) . isEmpty ( ) ? _sessionIdFormat . changeJvmRoute ( sessionId , jvmRoute ) : _sessionIdFormat . stripJvmRoute ( sessionId ) ; if ( isEncodeNodeIdInSessionId ( ) ) { final String nodeId = _sessionIdFormat . extractMemcachedId ( newSessionId ) ; if ( _failoverNodeIds != null && _failoverNodeIds . contains ( nodeId ) ) { final String newNodeId = _nodeIdService . getAvailableNodeId ( nodeId ) ; if ( newNodeId != null ) { return _sessionIdFormat . createNewSessionId ( newSessionId , newNodeId ) ; } } } return newSessionId ; } | Changes the sessionId by setting the given jvmRoute and replacing the memcachedNodeId if it s currently set to a failoverNodeId . |
30,367 | public List < URI > getCouchbaseBucketURIs ( ) { if ( ! isCouchbaseBucketConfig ( ) ) throw new IllegalStateException ( "This is not a couchbase bucket configuration." ) ; final List < URI > result = new ArrayList < URI > ( _address2Ids . size ( ) ) ; final Matcher matcher = COUCHBASE_BUCKET_NODE_PATTERN . matcher ( _memcachedNodes ) ; while ( matcher . find ( ) ) { try { result . add ( new URI ( matcher . group ( ) ) ) ; } catch ( final URISyntaxException e ) { throw new RuntimeException ( e ) ; } } return result ; } | Returns a list of couchbase REST interface uris if the current configuration is a couchbase bucket configuration . |
30,368 | public void setMaxActiveSessions ( final int max ) { final int oldMaxActiveSessions = _maxActiveSessions ; _maxActiveSessions = max ; support . firePropertyChange ( "maxActiveSessions" , Integer . valueOf ( oldMaxActiveSessions ) , Integer . valueOf ( _maxActiveSessions ) ) ; } | Set the maximum number of active Sessions allowed or - 1 for no limit . |
30,369 | public void modifyingRequest ( final String requestId ) { if ( _log . isDebugEnabled ( ) ) { _log . debug ( "Registering modifying request: " + requestId ) ; } incrementOrPut ( _blacklist , requestId ) ; _readOnlyRequests . remove ( requestId ) ; } | Registers the given requestURI as a modifying request which can be seen as a blacklist for readonly requests . There s a limit on number and time for modifying requests beeing stored . |
30,370 | public boolean isReadOnlyRequest ( final String requestId ) { if ( _log . isDebugEnabled ( ) ) { _log . debug ( "Asked for readonly request: " + requestId + " (" + _readOnlyRequests . containsKey ( requestId ) + ")" ) ; } return _readOnlyRequests . containsKey ( requestId ) ; } | Determines if the given requestURI is a readOnly request and not blacklisted as a modifying request . |
30,371 | public ConcurrentMap < String , Object > deserializeAttributes ( final byte [ ] in ) { final InputStreamReader inputStream = new InputStreamReader ( new ByteArrayInputStream ( in ) ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "deserialize the stream" ) ; } try { return deserializer . deserializeInto ( inputStream , new ConcurrentHashMap < String , Object > ( ) ) ; } catch ( final RuntimeException e ) { LOG . warn ( "Caught Exception deserializing JSON " + e ) ; throw new TranscoderDeserializationException ( e ) ; } } | Return the deserialized map |
30,372 | protected void onBackupWithoutLoadedSession ( final String sessionId , final String requestId , final BackupSessionService backupSessionService ) { if ( ! _sessionIdFormat . isValid ( sessionId ) ) { return ; } try { final long start = System . currentTimeMillis ( ) ; final String validityKey = _sessionIdFormat . createValidityInfoKeyName ( sessionId ) ; final SessionValidityInfo validityInfo = loadSessionValidityInfoForValidityKey ( validityKey ) ; if ( validityInfo == null ) { _log . warn ( "Found no validity info for session id " + sessionId ) ; return ; } final int maxInactiveInterval = validityInfo . getMaxInactiveInterval ( ) ; final byte [ ] validityData = encode ( maxInactiveInterval , System . currentTimeMillis ( ) , System . currentTimeMillis ( ) ) ; final int expiration = maxInactiveInterval <= 0 ? 0 : maxInactiveInterval ; final Future < Boolean > validityResult = _storage . set ( validityKey , toMemcachedExpiration ( expiration ) , validityData ) ; if ( ! _manager . isSessionBackupAsync ( ) ) { validityResult . get ( _manager . getSessionBackupTimeout ( ) , TimeUnit . MILLISECONDS ) ; } final Callable < ? > backupSessionTask = new OnBackupWithoutLoadedSessionTask ( sessionId , _storeSecondaryBackup , validityKey , validityData , maxInactiveInterval ) ; _executor . submit ( backupSessionTask ) ; if ( _log . isDebugEnabled ( ) ) { _log . debug ( "Stored session validity info for session " + sessionId ) ; } _stats . registerSince ( NON_STICKY_ON_BACKUP_WITHOUT_LOADED_SESSION , start ) ; } catch ( final Throwable e ) { _log . warn ( "An error when trying to load/update validity info." , e ) ; } } | Is invoked for the backup of a non - sticky session that was not accessed for the current request . |
30,373 | protected void onAfterBackupSession ( final MemcachedBackupSession session , final boolean backupWasForced , final Future < BackupResult > result , final String requestId , final BackupSessionService backupSessionService ) { if ( ! _sessionIdFormat . isValid ( session . getIdInternal ( ) ) ) { return ; } try { final long start = System . currentTimeMillis ( ) ; final int maxInactiveInterval = session . getMaxInactiveInterval ( ) ; final byte [ ] validityData = encode ( maxInactiveInterval , session . getLastAccessedTimeInternal ( ) , session . getThisAccessedTimeInternal ( ) ) ; final String validityKey = _sessionIdFormat . createValidityInfoKeyName ( session . getIdInternal ( ) ) ; final int expiration = maxInactiveInterval <= 0 ? 0 : maxInactiveInterval ; final Future < Boolean > validityResult = _storage . set ( validityKey , toMemcachedExpiration ( expiration ) , validityData ) ; if ( ! _manager . isSessionBackupAsync ( ) ) { validityResult . get ( _manager . getSessionBackupTimeout ( ) , TimeUnit . MILLISECONDS ) ; } if ( _log . isDebugEnabled ( ) ) { _log . debug ( "Stored session validity info for session " + session . getIdInternal ( ) ) ; } final boolean pingSessionIfBackupWasSkipped = ! backupWasForced ; final boolean performAsyncTasks = pingSessionIfBackupWasSkipped || _storeSecondaryBackup ; if ( performAsyncTasks ) { final Callable < ? > backupSessionTask = new OnAfterBackupSessionTask ( session , result , pingSessionIfBackupWasSkipped , backupSessionService , _storeSecondaryBackup , validityKey , validityData ) ; _executor . submit ( backupSessionTask ) ; } _stats . registerSince ( NON_STICKY_AFTER_BACKUP , start ) ; } catch ( final Throwable e ) { _log . warn ( "An error occurred during onAfterBackupSession." , e ) ; } } | Is invoked after the backup of the session is initiated it s represented by the provided backupResult . The requestId is identifying the request . |
30,374 | protected void onAfterDeleteFromMemcached ( final String sessionId ) { final long start = System . currentTimeMillis ( ) ; final String validityInfoKey = _sessionIdFormat . createValidityInfoKeyName ( sessionId ) ; _storage . delete ( validityInfoKey ) ; if ( _storeSecondaryBackup ) { try { _storage . delete ( _sessionIdFormat . createBackupKey ( sessionId ) ) ; _storage . delete ( _sessionIdFormat . createBackupKey ( validityInfoKey ) ) ; } catch ( Exception e ) { _log . info ( "Could not delete backup data for session " + sessionId + " (not critical, data will be evicted by memcached automatically)." , e ) ; } } _stats . registerSince ( NON_STICKY_AFTER_DELETE_FROM_MEMCACHED , start ) ; } | Invoked after a non - sticky session is removed from memcached . |
30,375 | void startInternal ( ) throws LifecycleException { _log . info ( getClass ( ) . getSimpleName ( ) + " starts initialization... (configured" + " nodes definition " + _memcachedNodes + ", failover nodes " + _failoverNodes + ")" ) ; _statistics = Statistics . create ( _enableStatistics ) ; _memcachedNodesManager = createMemcachedNodesManager ( _memcachedNodes , _failoverNodes ) ; if ( _storage == null ) { _storage = createStorageClient ( _memcachedNodesManager , _statistics ) ; } final String sessionCookieName = _manager . getSessionCookieName ( ) ; _currentRequest = new CurrentRequest ( ) ; _trackingHostValve = createRequestTrackingHostValve ( sessionCookieName , _currentRequest ) ; final Context context = _manager . getContext ( ) ; context . getParent ( ) . getPipeline ( ) . addValve ( _trackingHostValve ) ; _trackingContextValve = createRequestTrackingContextValve ( sessionCookieName ) ; context . getPipeline ( ) . addValve ( _trackingContextValve ) ; initNonStickyLockingMode ( _memcachedNodesManager ) ; _transcoderService = createTranscoderService ( _statistics ) ; _backupSessionService = new BackupSessionService ( _transcoderService , _sessionBackupAsync , _sessionBackupTimeout , _backupThreadCount , _storage , _memcachedNodesManager , _statistics ) ; _log . info ( "--------\n- " + getClass ( ) . getSimpleName ( ) + " finished initialization:" + "\n- sticky: " + _sticky + "\n- operation timeout: " + _operationTimeout + "\n- node ids: " + _memcachedNodesManager . getPrimaryNodeIds ( ) + "\n- failover node ids: " + _memcachedNodesManager . getFailoverNodeIds ( ) + "\n- storage key prefix: " + _memcachedNodesManager . getStorageKeyFormat ( ) . prefix + "\n- locking mode: " + _lockingMode + " (expiration: " + _lockExpiration + "s)" + "\n--------" ) ; } | Initialize this manager . |
30,376 | public Future < BackupResult > backupSession ( final String sessionId , final boolean sessionIdChanged , final String requestId ) { if ( ! _enabled . get ( ) ) { return new SimpleFuture < BackupResult > ( BackupResult . SKIPPED ) ; } final MemcachedBackupSession msmSession = _manager . getSessionInternal ( sessionId ) ; if ( msmSession == null ) { if ( _log . isDebugEnabled ( ) ) _log . debug ( "No session found in session map for " + sessionId ) ; if ( ! _sticky ) { if ( ! _invalidSessionsCache . containsKey ( sessionId ) ) { _lockingStrategy . onBackupWithoutLoadedSession ( sessionId , requestId , _backupSessionService ) ; } } return new SimpleFuture < BackupResult > ( BackupResult . SKIPPED ) ; } if ( ! msmSession . isValidInternal ( ) ) { if ( _log . isDebugEnabled ( ) ) _log . debug ( "Non valid session found in session map for " + sessionId ) ; return new SimpleFuture < BackupResult > ( BackupResult . SKIPPED ) ; } if ( ! _sticky ) { synchronized ( _manager . getSessionsInternal ( ) ) { if ( msmSession . releaseReference ( ) > 0 ) { if ( _log . isDebugEnabled ( ) ) _log . debug ( "Session " + sessionId + " is still used by another request, skipping backup and (optional) lock handling/release." ) ; return new SimpleFuture < BackupResult > ( BackupResult . SKIPPED ) ; } msmSession . passivate ( ) ; _manager . removeInternal ( msmSession , false ) ; } } final boolean force = sessionIdChanged || msmSession . isSessionIdChanged ( ) || ! _sticky && ( msmSession . getSecondsSinceLastBackup ( ) >= msmSession . getMaxInactiveInterval ( ) ) ; final Future < BackupResult > result = _backupSessionService . backupSession ( msmSession , force ) ; if ( ! _sticky ) { _lockingStrategy . onAfterBackupSession ( msmSession , force , result , requestId , _backupSessionService ) ; } return result ; } | Backup the session for the provided session id in memcached if the session was modified or if the session needs to be relocated . In non - sticky session - mode the session should not be loaded from memcached for just storing it again but only metadata should be updated . |
30,377 | public String createSessionId ( final String sessionId , final String memcachedId ) { if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Creating new session id with orig id '" + sessionId + "' and memcached id '" + memcachedId + "'." ) ; } if ( memcachedId == null ) { return sessionId ; } final int idx = sessionId . indexOf ( '.' ) ; if ( idx < 0 ) { return sessionId + "-" + memcachedId ; } else { return sessionId . substring ( 0 , idx ) + "-" + memcachedId + sessionId . substring ( idx ) ; } } | Create a session id including the provided memcachedId . |
30,378 | public String extractMemcachedId ( final String sessionId ) { final int idxDash = sessionId . indexOf ( '-' ) ; if ( idxDash < 0 ) { return null ; } final int idxDot = sessionId . indexOf ( '.' ) ; if ( idxDot < 0 ) { return sessionId . substring ( idxDash + 1 ) ; } else if ( idxDot < idxDash ) { return null ; } else { return sessionId . substring ( idxDash + 1 , idxDot ) ; } } | Extract the memcached id from the given session id . |
30,379 | public String extractJvmRoute ( final String sessionId ) { final int idxDot = sessionId . indexOf ( '.' ) ; return idxDot < 0 ? null : sessionId . substring ( idxDot + 1 ) ; } | Extract the jvm route from the given session id if existing . |
30,380 | public String stripJvmRoute ( final String sessionId ) { final int idxDot = sessionId . indexOf ( '.' ) ; return idxDot < 0 ? sessionId : sessionId . substring ( 0 , idxDot ) ; } | Remove the jvm route from the given session id if existing . |
30,381 | public Future < BackupResult > backupSession ( final String sessionId , final boolean sessionIdChanged , final String requestId ) { final MemcachedBackupSession session = _manager . getSessionInternal ( sessionId ) ; if ( session == null ) { if ( _log . isDebugEnabled ( ) ) _log . debug ( "No session found in session map for " + sessionId ) ; return new SimpleFuture < BackupResult > ( BackupResult . SKIPPED ) ; } _log . info ( "Serializing session data for session " + session . getIdInternal ( ) ) ; final long startSerialization = System . currentTimeMillis ( ) ; final byte [ ] data = _transcoderService . serializeAttributes ( ( MemcachedBackupSession ) session , ( ( MemcachedBackupSession ) session ) . getAttributesFiltered ( ) ) ; _log . info ( String . format ( "Serializing %1$,.3f kb session data for session %2$s took %3$d ms." , ( double ) data . length / 1000 , session . getIdInternal ( ) , System . currentTimeMillis ( ) - startSerialization ) ) ; _sessionData . put ( session . getIdInternal ( ) , data ) ; _statistics . registerSince ( ATTRIBUTES_SERIALIZATION , startSerialization ) ; _statistics . register ( CACHED_DATA_SIZE , data . length ) ; return new SimpleFuture < BackupResult > ( new BackupResult ( BackupResultStatus . SUCCESS ) ) ; } | Store the provided session in memcached if the session was modified or if the session needs to be relocated . |
30,382 | private boolean filterAttribute ( final String name ) { if ( this . manager == null ) { throw new IllegalStateException ( "There's no manager set." ) ; } final Pattern pattern = ( ( SessionManager ) manager ) . getMemcachedSessionService ( ) . getSessionAttributePattern ( ) ; if ( pattern == null ) { return true ; } return pattern . matcher ( name ) . matches ( ) ; } | Check whether the given attribute name matches our name pattern and shall be stored in memcached . |
30,383 | int getMemcachedExpirationTime ( ) { if ( ! _sticky ) { throw new IllegalStateException ( "The memcached expiration time cannot be determined in non-sticky mode." ) ; } if ( _lastMemcachedExpirationTime == 0 ) { return 0 ; } final long timeIdleInMillis = _lastBackupTime == 0 ? 0 : System . currentTimeMillis ( ) - _lastBackupTime ; final int timeIdle = Math . round ( ( float ) timeIdleInMillis / 1000L ) ; final int expirationTime = _lastMemcachedExpirationTime - timeIdle ; return max ( 1 , expirationTime ) ; } | Gets the time in seconds when this session will expire in memcached . If the session was stored in memcached with expiration 0 this method will just return 0 . |
30,384 | public ConcurrentMap < String , Object > getAttributesFiltered ( ) { if ( this . manager == null ) { throw new IllegalStateException ( "There's no manager set." ) ; } final Pattern pattern = ( ( SessionManager ) manager ) . getMemcachedSessionService ( ) . getSessionAttributePattern ( ) ; final ConcurrentMap < String , Object > attributes = getAttributesInternal ( ) ; if ( pattern == null ) { return attributes ; } final ConcurrentMap < String , Object > result = new ConcurrentHashMap < String , Object > ( attributes . size ( ) ) ; for ( final Map . Entry < String , Object > entry : attributes . entrySet ( ) ) { if ( pattern . matcher ( entry . getKey ( ) ) . matches ( ) ) { result . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } return result ; } | Filter map of attributes using our name pattern . |
30,385 | public V put ( final K key , final V value ) { synchronized ( _map ) { final ManagedItem < V > previous = _map . put ( key , new ManagedItem < V > ( value , System . currentTimeMillis ( ) ) ) ; while ( _map . size ( ) > _size ) { _map . remove ( _map . keySet ( ) . iterator ( ) . next ( ) ) ; } return previous != null ? previous . _value : null ; } } | Put the key and value . |
30,386 | public V get ( final K key ) { synchronized ( _map ) { final ManagedItem < V > item = _map . get ( key ) ; if ( item == null ) { return null ; } if ( _ttl > - 1 && System . currentTimeMillis ( ) - item . _insertionTime > _ttl ) { _map . remove ( key ) ; return null ; } return item . _value ; } } | Returns the value that was stored to the given key . |
30,387 | public List < K > getKeys ( ) { synchronized ( _map ) { return new java . util . ArrayList < K > ( _map . keySet ( ) ) ; } } | The list of all keys whose order is the order in which its entries were last accessed from least - recently accessed to most - recently . |
30,388 | public List < K > getKeysSortedByValue ( final Comparator < V > comparator ) { synchronized ( _map ) { @ SuppressWarnings ( "unchecked" ) final Entry < K , ManagedItem < V > > [ ] a = _map . entrySet ( ) . toArray ( new Map . Entry [ _map . size ( ) ] ) ; final Comparator < Entry < K , ManagedItem < V > > > c = new Comparator < Entry < K , ManagedItem < V > > > ( ) { public int compare ( final Entry < K , ManagedItem < V > > o1 , final Entry < K , ManagedItem < V > > o2 ) { return comparator . compare ( o1 . getValue ( ) . _value , o2 . getValue ( ) . _value ) ; } } ; Arrays . sort ( a , c ) ; return new LRUCache . ArrayList < K , V > ( a ) ; } } | The keys sorted by the given value comparator . |
30,389 | public boolean isNodeAvailable ( final K key ) { final ManagedItem < Boolean > item = _map . get ( key ) ; if ( item == null ) { return updateIsNodeAvailable ( key ) ; } else if ( isExpired ( item ) ) { _map . remove ( key ) ; return updateIsNodeAvailable ( key ) ; } else { return item . _value ; } } | Determines if the node is available . If it s not cached it s loaded from the cache loader . |
30,390 | public Set < K > getUnavailableNodes ( ) { final Set < K > result = new HashSet < K > ( ) ; for ( final Map . Entry < K , ManagedItem < Boolean > > entry : _map . entrySet ( ) ) { if ( ! entry . getValue ( ) . _value . booleanValue ( ) && ! isExpired ( entry . getValue ( ) ) ) { result . add ( entry . getKey ( ) ) ; } } return result ; } | A set of nodes that are stored as unavailable . |
30,391 | @ Path ( "/health" ) @ Produces ( MediaType . APPLICATION_JSON ) public HealthStatus health ( ) throws ExecutionException , InterruptedException { final HealthStatus status = new HealthStatus ( ) ; final Future < HealthDetails > dbStatus = healthDBService . dbStatus ( ) ; final Future < List < HealthDetails > > networkStatus = healthNetworkService . networkStatus ( ) ; status . add ( dbStatus . get ( ) ) ; networkStatus . get ( ) . forEach ( status :: add ) ; return status ; } | Get health status |
30,392 | public String extractUsername ( ) { final KeycloakPrincipal principal = ( KeycloakPrincipal ) httpServletRequest . getUserPrincipal ( ) ; if ( principal != null ) { logger . debug ( "Running with Keycloak context" ) ; KeycloakSecurityContext kcSecurityContext = principal . getKeycloakSecurityContext ( ) ; return kcSecurityContext . getToken ( ) . getPreferredUsername ( ) ; } logger . debug ( "Running outside of Keycloak context" ) ; final String basicUsername = HttpBasicHelper . extractUsernameAndPasswordFromBasicHeader ( httpServletRequest ) [ 0 ] ; if ( ! basicUsername . isEmpty ( ) ) { logger . debug ( "running HttpBasic auth" ) ; return basicUsername ; } logger . debug ( "Running without any Auth context" ) ; return "admin" ; } | Extract the username to be used in multiple queries |
30,393 | public static String extractAeroGearSenderInformation ( final HttpServletRequest request ) { String client = request . getHeader ( "aerogear-sender" ) ; if ( hasValue ( client ) ) { return client ; } return request . getHeader ( "user-agent" ) ; } | Reads the aerogear - sender header to check if an AeroGear Sender client was used . If the header value is NULL the value of the standard user - agent header is returned |
30,394 | @ Path ( "/{androidID}" ) @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response updateAndroidVariant ( @ PathParam ( "pushAppID" ) String id , @ PathParam ( "androidID" ) String androidID , AndroidVariant updatedAndroidApplication ) { AndroidVariant androidVariant = ( AndroidVariant ) variantService . findByVariantID ( androidID ) ; if ( androidVariant != null ) { try { validateModelClass ( updatedAndroidApplication ) ; } catch ( ConstraintViolationException cve ) { logger . info ( "Unable to update Android Variant '{}'" , androidVariant . getVariantID ( ) ) ; logger . debug ( "Details: {}" , cve ) ; ResponseBuilder builder = createBadRequestResponse ( cve . getConstraintViolations ( ) ) ; return builder . build ( ) ; } androidVariant . setGoogleKey ( updatedAndroidApplication . getGoogleKey ( ) ) ; androidVariant . setProjectNumber ( updatedAndroidApplication . getProjectNumber ( ) ) ; androidVariant . setName ( updatedAndroidApplication . getName ( ) ) ; androidVariant . setDescription ( updatedAndroidApplication . getDescription ( ) ) ; logger . trace ( "Updating Android Variant '{}'" , androidID ) ; variantService . updateVariant ( androidVariant ) ; return Response . ok ( androidVariant ) . build ( ) ; } return Response . status ( Status . NOT_FOUND ) . entity ( "Could not find requested Variant" ) . build ( ) ; } | Update Android Variant |
30,395 | public static boolean isValidDeviceTokenForVariant ( final String deviceToken , final VariantType type ) { switch ( type ) { case IOS : return IOS_DEVICE_TOKEN . matcher ( deviceToken ) . matches ( ) ; case ANDROID : return ANDROID_DEVICE_TOKEN . matcher ( deviceToken ) . matches ( ) ; case WINDOWS_WNS : return WINDOWS_DEVICE_TOKEN . matcher ( deviceToken ) . matches ( ) ; } return false ; } | Helper to run quick up - front validations . |
30,396 | private boolean tryToDispatchTokens ( MessageHolderWithTokens msg ) { try { dispatchTokensEvent . fire ( msg ) ; return true ; } catch ( MessageDeliveryException e ) { Throwable cause = e . getCause ( ) ; if ( isQueueFullException ( cause ) ) { return false ; } throw e ; } } | Tries to dispatch tokens ; returns true if tokens were successfully queued . Detects when queue is full and in that case returns false . |
30,397 | private int delete ( String urlS ) throws IOException { URL url = new URL ( urlS ) ; HttpURLConnection conn = prepareAuthorizedConnection ( url ) ; conn . setRequestMethod ( "DELETE" ) ; conn . connect ( ) ; return conn . getResponseCode ( ) ; } | Sends DELETE HTTP request to provided URL . Request is authorized using Google API key . |
30,398 | private String get ( String urlS ) throws IOException { URL url = new URL ( urlS ) ; HttpURLConnection conn = prepareAuthorizedConnection ( url ) ; conn . setRequestMethod ( "GET" ) ; StringBuilder result = new StringBuilder ( ) ; try ( BufferedReader rd = new BufferedReader ( new InputStreamReader ( conn . getInputStream ( ) ) ) ) { String line ; while ( ( line = rd . readLine ( ) ) != null ) { result . append ( line ) ; } } return result . toString ( ) ; } | Sends GET HTTP request to provided URL . Request is authorized using Google API key . |
30,399 | public static boolean isCategoryOnlyCriteria ( final Criteria criteria ) { return isEmpty ( criteria . getAliases ( ) ) && isEmpty ( criteria . getDeviceTypes ( ) ) && ! isEmpty ( criteria . getCategories ( ) ) ; } | Helper method to check if only categories are applied . Useful in FCM land where we use topics |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.