signature:
public class LogPersister { /** * Set the maximum size of the local log file . Once the maximum file size is reached ,
 * no more data will be appended . Consider that this file is sent to a server .
 * @ param bytes maximum size of the file in bytes , minimum 10000 */
static public void setMaxLogStoreSize ( final int bytes ) { } }

implementation:
// TODO : also check if bytes is bigger than remaining disk space ?
if ( bytes >= 10000 ) { logFileMaxSize = bytes ; } if ( null != context ) { SharedPreferences prefs = context . getSharedPreferences ( SHARED_PREF_KEY , Context . MODE_PRIVATE ) ; prefs . edit ( ) . putInt ( SHARED_PREF_KEY_logFileMaxSize , logFileMaxSize ) . commit ( ) ; }


signature:
public class LogPersister { /** * See { @ link # send ( ) }
 * @ param listener { @ link com . ibm . mobilefirstplatform . clientsdk . android . core . api . ResponseListener } which specifies a success and failure callback */
static public void send ( ResponseListener listener ) { } }

implementation: if ( sendingLogs ) { return ; } else { sendingLogs = true ; sendFiles ( LogPersister . FILENAME , listener ) ; }


signature:
public class LogPersister { /** * @ exclude
 * Send the accumulated log data when the persistent log buffer exists and is not empty . The data
 * accumulates in the log buffer from the use of { @ link LogPersister } with capture
 * ( see { @ link LogPersister # setAnalyticsCapture ( boolean ) } ) turned on .
 * @ param listener { @ link com . ibm . mobilefirstplatform . clientsdk . android . core . api . ResponseListener } which specifies a success and failure callback */
static public void sendAnalytics ( ResponseListener listener ) { } }

implementation: if ( sendingAnalyticsLogs ) { return ; } else { sendingAnalyticsLogs = true ; sendFiles ( LogPersister . ANALYTICS_FILENAME , listener ) ; }


signature:
public class LogPersister { /** * Ask the Logger if an uncaught exception , which often appears to the user as a crashed app , is present in the persistent capture buffer .
 * This method should not be called after calling { @ link com . ibm . mobilefirstplatform . clientsdk . android . core . api . BMSClient # initialize ( Context , String , String , String ) } . If it is called too early , an error message is issued and false is returned .
 * @ return boolean if an uncaught exception log entry is currently in the persistent log buffer */
static public boolean isUnCaughtExceptionDetected ( ) { } }

implementation: if ( context == null ) { if ( ! context_null_msg_already_printed ) { Log . w ( LOG_TAG_NAME , CONTEXT_NULL_MSG ) ; context_null_msg_already_printed = true ; } return false ; } return context . getSharedPreferences ( SHARED_PREF_KEY , Context . MODE_PRIVATE ) . getBoolean ( SHARED_PREF_KEY_CRASH_DETECTED , false ) ;


signature:
public class LogPersister { /** * @ exclude
 * All log calls flow through here . Use this method when you want to control the timestamp , attach additional metadata ,
 * and attach a Throwable ' s call stack to the log output .
 * @ param calledLevel specify the Logger . LEVEL ( a null parameter results in no log entry )
 * @ param message ( optional ) the data for the log entry
 * @ param timestamp the number of milliseconds since January 1 , 1970 , 00:00:00 GMT
 * @ param t ( optional ) an Exception or Throwable , may be null */
public static void doLog ( final Logger . LEVEL calledLevel , String message , final long timestamp , final Throwable t , JSONObject additionalMetadata , final String loggerName , final boolean isInternalLogger , final Object loggerObject ) { } }

implementation:
// we do this outside of the thread , otherwise we can ' t find the caller to attach the call stack metadata
JSONObject metadata = appendStackMetadata ( additionalMetadata ) ; ThreadPoolWorkQueue . execute ( new DoLogRunnable ( calledLevel , message , timestamp , metadata , t , loggerName , isInternalLogger , loggerObject ) ) ;


signature:
public class LogPersister { /** * if we have callstack metadata , prepend it to the message */
protected static String prependMetadata ( String message , JSONObject metadata ) { } }

implementation:
try { if ( null != metadata ) { String clazz = "" ; String method = "" ; String file = "" ; String line = "" ; if ( metadata . has ( "$class" ) ) { clazz = metadata . getString ( "$class" ) ; clazz = clazz . substring ( clazz . lastIndexOf ( '.' ) + 1 , clazz . length ( ) ) ; } if ( metadata . has ( "$method" ) ) { method = metadata . getString ( "$method" ) ; } if ( metadata . has ( "$file" ) ) { file = metadata . getString ( "$file" ) ; } if ( metadata . has ( "$line" ) ) { line = metadata . getString ( "$line" ) ; } if ( ! ( clazz + method + file + line ) . equals ( "" ) ) { // we got something . . .
message = clazz + "." + method + " in " + file + ":" + line + " :: " + message ; } } } catch ( Exception e ) { // ignore . . . it ' s best effort anyway
} return message ;


signature:
public class LogPersister { /** * Get stack trace caused by Logger exceptions
 * @ return Returns the JSONObject with stack metadata */
protected static JSONObject appendStackMetadata ( JSONObject additionalMetadata ) { } }

implementation:
JSONObject jsonMetadata ; if ( additionalMetadata != null ) { jsonMetadata = additionalMetadata ; } else { jsonMetadata = new JSONObject ( ) ; } try { // try / catch Exception wraps all because I don ' t know yet if I can trust getStackTrace . . . needs more testing
// below is slightly more performant than : Thread . currentThread ( ) . getStackTrace ( ) ;
StackTraceElement [ ] stackTraceElements = new Exception ( ) . getStackTrace ( ) ; int index = 0 ; // find the start of the Logger call stack :
while ( ! stackTraceElements [ index ] . getClassName ( ) . equals ( LogPersister . class . getName ( ) ) ) { index ++ ; } // then find the caller :
while ( stackTraceElements [ index ] . getClassName ( ) . equals ( LogPersister . class . getName ( ) ) || stackTraceElements [ index ] . getClassName ( ) . startsWith ( JULHandler . class . getName ( ) ) || stackTraceElements [ index ] . getClassName ( ) . startsWith ( java . util . logging . Logger . class . getName ( ) ) || stackTraceElements [ index ] . getClassName ( ) . startsWith ( BMSAnalytics . class . getName ( ) ) ) { index ++ ; } jsonMetadata . put ( "$class" , stackTraceElements [ index ] . getClassName ( ) ) ; jsonMetadata . put ( "$file" , stackTraceElements [ index ] . getFileName ( ) ) ; jsonMetadata . put ( "$method" , stackTraceElements [ index ] . getMethodName ( ) ) ; jsonMetadata . put ( "$line" , stackTraceElements [ index ] . getLineNumber ( ) ) ; jsonMetadata . put ( "$src" , "java" ) ; } catch ( Exception e ) { Log . e ( LOG_TAG_NAME , "Could not generate jsonMetadata object." , e ) ; } return jsonMetadata ;


signature:
public class LogPersister { /** * Will create JSONObject with the passed parameters , and other relevant information . See class - level documentation .
 * @ param level
 * @ param message
 * @ param t a Throwable whose stack trace is converted to string and logged , and passed through as - is to android . util . Log
 * @ return a JSONObject as shown in the class introduction */
private static JSONObject createJSONObject ( final Logger . LEVEL level , final String pkg , final String message , long timestamp , final JSONObject jsonMetadata , final Throwable t ) { } }

implementation: JSONObject jsonObject = new JSONObject ( ) ; try { jsonObject . put ( "timestamp" , timestamp ) ; jsonObject . put ( "level" , level . toString ( ) ) ; jsonObject . put ( "pkg" , pkg ) ; jsonObject . put ( "msg" , message ) ; jsonObject . put ( "threadid" , Thread . currentThread ( ) . getId ( ) ) ; if ( null != jsonMetadata ) { jsonObject . put ( "metadata" , jsonMetadata ) ; } if ( null != t ) { jsonObject . put ( "metadata" , appendFullStackTrace ( jsonMetadata , t ) ) ; } } catch ( JSONException e ) { Log . e ( LOG_TAG_NAME , "Error adding JSONObject key/value pairs" , e ) ; } return jsonObject ;


signature:
public class LogPersister { /** * append the full stacktrace to a $ stacktrace key JSONArray in the passed jsonMetadata object
 * and return it . */
private static JSONObject appendFullStackTrace ( JSONObject jsonMetadata , Throwable t ) { } }

implementation:
JSONArray stackArray = new JSONArray ( ) ; Throwable throwable = t ; StackTraceElement [ ] stackTraceElements ; boolean first = true ; // walk up the throwable ' s call stack :
while ( throwable != null ) { stackArray . put ( ( first ? "Exception " : "Caused by: " ) + throwable . getClass ( ) . getName ( ) + ( throwable . getMessage ( ) != null ? ": " + throwable . getMessage ( ) : "" ) ) ; stackTraceElements = throwable . getStackTrace ( ) ; for ( int i = 0 ; i < stackTraceElements . length ; i ++ ) { stackArray . put ( stackTraceElements [ i ] . toString ( ) ) ; } throwable = throwable . getCause ( ) ; first = false ; } try { if ( null == jsonMetadata ) { jsonMetadata = new JSONObject ( ) ; } jsonMetadata . put ( "$stacktrace" , stackArray ) ; jsonMetadata . put ( "$exceptionMessage" , t . getLocalizedMessage ( ) ) ; jsonMetadata . put ( "$exceptionClass" , t . getClass ( ) . getName ( ) ) ; } catch ( JSONException e ) { // ignore . getting the stacktrace is best effort
} return jsonMetadata ;


signature:
public class LogPersister { /** * We only persist ( append ) to the log file if the passed jsonObject parameter has data ,
 * the Logger capture flag is set to true , and the log file size is less than
 * FILE _ SIZE _ LOG _ THRESHOLD .
 * @ param jsonObject the object to write into the log file . */
private synchronized static void captureToFile ( final JSONObject jsonObject , Logger . LEVEL calledLevel ) { } }

implementation:
boolean cap = getCaptureSync ( ) ; boolean analyticsCap = getAnalyticsCaptureSync ( ) ; if ( context == null ) { if ( ! context_null_msg_already_printed ) { Log . w ( LOG_TAG_NAME , CONTEXT_NULL_MSG ) ; context_null_msg_already_printed = true ; } return ; } if ( jsonObject . length ( ) == 0 ) { return ; } try { // Determine whether is needs to go to analytics or logger
if ( analyticsCap && calledLevel . equals ( Logger . LEVEL . ANALYTICS ) ) { fileLoggerInstance . log ( jsonObject , ANALYTICS_FILENAME ) ; } else if ( cap ) { fileLoggerInstance . log ( jsonObject , FILENAME ) ; } } catch ( Exception e ) { Log . e ( LOG_TAG_NAME , "An error occurred capturing data to file." , e ) ; }


signature:
public class BMSAnalytics { /** * Initialize BMSAnalytics API .
 * This must be called before any other BMSAnalytics . * methods
 * @ param app Android Application to instrument with MFPAnalytics .
 * @ param applicationName Application ' s common name . Should be consistent across platforms .
 * @ param clientApiKey The Client API Key used to communicate with your MFPAnalytics service .
 * @ param hasUserContext If false , Analytics only records one user per device . If true , setting the user identity will keep a record of all users .
 * @ param collectLocation If true , Analytics will begin to record location metadeta
 * @ param contexts One or more context attributes MFPAnalytics will register event listeners for . */
static public void init ( Application app , String applicationName , String clientApiKey , boolean hasUserContext , boolean collectLocation , Analytics . DeviceEvent ... contexts ) { } }

implementation:
Context context = app . getApplicationContext ( ) ; if ( collectLocation ) { locationService = MFPAnalyticsLocationListener . getInstance ( context ) ; } // Initialize LogPersister
LogPersister . setLogLevel ( Logger . getLogLevel ( ) ) ; LogPersister . setContext ( context ) ; // Instrument Logger with LogPersisterDelegate
LogPersisterDelegate logPersisterDelegate = new LogPersisterDelegate ( ) ; Logger . setLogPersister ( logPersisterDelegate ) ; MFPInAppFeedBackListner . setContext ( context ) ; Analytics . setAnalyticsDelegate ( new BMSAnalyticsDelegate ( ) ) ; BMSAnalytics . clientApiKey = clientApiKey ; if ( contexts != null ) { for ( Analytics . DeviceEvent event : contexts ) { switch ( event ) { case LIFECYCLE : MFPActivityLifeCycleCallbackListener . init ( app ) ; break ; case NETWORK : isRecordingNetworkEvents = true ; break ; case ALL : MFPActivityLifeCycleCallbackListener . init ( app ) ; isRecordingNetworkEvents = true ; break ; case NONE : break ; } } } // if ( ! hasUserContext ) {
// Use device ID as default user ID :
if ( collectLocation ) { BMSAnalytics . collectLocation = collectLocation ; locationService . init ( ) ; } DEFAULT_USER_ID = getDeviceID ( context ) ; if ( ! collectLocation ) { setUserIdentity ( DEFAULT_USER_ID , true ) ; } BMSAnalytics . hasUserContext = hasUserContext ; appName = applicationName ; // Intercept requests to add device metadata header
BaseRequest . registerInterceptor ( new MetadataHeaderInterceptor ( context . getApplicationContext ( ) ) ) ; BaseRequest . registerInterceptor ( new NetworkLoggingInterceptor ( ) ) ; enable ( ) ; MFPInAppFeedBackListner . sendAppFeedback ( ) ;


signature:
public class BMSAnalytics { /** * Initialize MFPAnalytics API .
 * This must be called before any other MFPAnalytics . * methods
 * @ deprecated As of release 1.1.0 , replaced by { @ link # init ( Application , String , String , boolean , boolean , Analytics . DeviceEvent . . . ) } }
 * please use the new init with user collection boolean . Using this method will
 * only collect anonymous users and throw exceptions when trying to set user identity
 * @ param app Android Application to instrument with MFPAnalytics .
 * @ param applicationName Application ' s common name . Should be consistent across platforms .
 * @ param clientApiKey The Client API Key used to communicate with your MFPAnalytics service .
 * @ param contexts One or more context attributes MFPAnalytics will register event listeners for . */
@ Deprecated static public void init ( Application app , String applicationName , String clientApiKey , Analytics . DeviceEvent ... contexts ) { } }

implementation: init ( app , applicationName , clientApiKey , false , false , contexts ) ;


signature:
public class BMSAnalytics { /** * Log location event */
public static void logLocation ( ) { } }

implementation:
if ( ! BMSAnalytics . collectLocation ) { logger . error ( "You must enable collectLocation before location can be logged" ) ; return ; } if ( ! locationService . getInitLocationRequests ( ) ) { logger . error ( "locationService  Initialization has failed" ) ; return ; } // Create metadata object to log
JSONObject metadata = new JSONObject ( ) ; String hashedUserID = UUID . nameUUIDFromBytes ( DEFAULT_USER_ID . getBytes ( ) ) . toString ( ) ; try { metadata . put ( CATEGORY , LOG_LOCATION_KEY ) ; metadata . put ( LATITUDE_KEY , locationService . getLatitude ( ) ) ; metadata . put ( LONGITUDE_KEY , locationService . getLongitude ( ) ) ; metadata . put ( TIMESTAMP_KEY , ( new Date ( ) ) . getTime ( ) ) ; metadata . put ( APP_SESSION_ID_KEY , MFPAnalyticsActivityLifecycleListener . getAppSessionID ( ) ) ; metadata . put ( USER_ID_KEY , hashedUserID ) ; } catch ( JSONException e ) { logger . debug ( "JSONException encountered logging change in user context: " + e . getMessage ( ) ) ; } log ( metadata ) ;


signature:
public class BMSAnalytics { /** * Specify current application user . This value will be hashed to ensure privacy .
 * If your application does not have user context , then nothing will happen .
 * @ param user User User id for current app user .
 * @ param isInitialCtx True if it ' s a user in the initial context ( i . e . when app first starts ) */
private static void setUserIdentity ( final String user , boolean isInitialCtx ) { } }

implementation:
if ( ! isInitialCtx && ! BMSAnalytics . hasUserContext ) { // log it to file :
logger . error ( "Cannot set user identity with anonymous user collection enabled." ) ; return ; } // Create metadata object to log
JSONObject metadata = new JSONObject ( ) ; DEFAULT_USER_ID = user ; String hashedUserID = UUID . nameUUIDFromBytes ( user . getBytes ( ) ) . toString ( ) ; try { if ( isInitialCtx ) { metadata . put ( CATEGORY , INITIAL_CTX_CATEGORY ) ; } else { metadata . put ( CATEGORY , USER_SWITCH_CATEGORY ) ; } if ( BMSAnalytics . collectLocation ) { if ( locationService . getInitLocationRequests ( ) ) { metadata . put ( LONGITUDE_KEY , locationService . getLongitude ( ) ) ; metadata . put ( LATITUDE_KEY , locationService . getLatitude ( ) ) ; } } metadata . put ( TIMESTAMP_KEY , ( new Date ( ) ) . getTime ( ) ) ; metadata . put ( APP_SESSION_ID_KEY , MFPAnalyticsActivityLifecycleListener . getAppSessionID ( ) ) ; metadata . put ( USER_ID_KEY , hashedUserID ) ; } catch ( JSONException e ) { logger . debug ( "JSONException encountered logging change in user context: " + e . getMessage ( ) ) ; } MFPInAppFeedBackListner . setUserIdentity ( user ) ; log ( metadata ) ;


signature:
public class FileLogger { /** * Callers should pass a JSONObject in the format described in the class - level documentation . It will be
 * placed as - is , using JSONObject . toString ( ) , with no additional contextual information automatically appended .
 * We use java . util . logging simply to take advantage of its built - in thread - safety and log rollover .
 * @ param logData JSONObject , placed in log file as - is using JSONObject . toString ( )
 * @ throws IOException
 * @ throws SecurityException */
public synchronized void log ( final JSONObject logData , String fileName ) throws SecurityException , IOException { } }

implementation: if ( null != singleton ) { filePath = context . getFilesDir ( ) + System . getProperty ( "file.separator" ) + fileName ; FileHandler handler = null ; handler = new FileHandler ( filePath , LogPersister . getMaxLogStoreSize ( ) , LogPersister . MAX_NUM_LOG_FILES , true ) ; handler . setFormatter ( formatter ) ; singleton . addHandler ( handler ) ; singleton . log ( Level . FINEST , logData . toString ( ) + "," ) ; singleton . getHandlers ( ) [ 0 ] . close ( ) ; singleton . removeHandler ( handler ) ; }


signature:
public class FileLogger { /** * public for testing only */
private byte [ ] getByteArrayFromFile ( final String file ) throws UnsupportedEncodingException { } }

implementation: String ret = "" ; File fl = new File ( context . getFilesDir ( ) , file ) ; if ( fl . exists ( ) ) { try { FileInputStream fin = new FileInputStream ( fl ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ( int ) fl . length ( ) ) ; copyStream ( fin , baos ) ; return baos . toByteArray ( ) ; } catch ( IOException e ) { Log . e ( LogPersister . LOG_TAG_NAME , "problem reading file " + fl . toString ( ) , e ) ; } } return ret . getBytes ( "UTF-8" ) ;


signature:
public class MFPAnalyticsLocationListener { /** * Starting the location updates */
protected void startLocationUpdates ( ) { } }

implementation:
if ( ActivityCompat . checkSelfPermission ( Context , Manifest . permission . ACCESS_FINE_LOCATION ) != PackageManager . PERMISSION_GRANTED && ActivityCompat . checkSelfPermission ( Context , Manifest . permission . ACCESS_COARSE_LOCATION ) != PackageManager . PERMISSION_GRANTED ) { // TODO : Consider calling
// ActivityCompat # requestPermissions
// here to request the missing permissions , and then overriding
// public void onRequestPermissionsResult ( int requestCode , String [ ] permissions ,
// int [ ] grantResults )
// to handle the case where the user grants the permission . See the documentation
// for ActivityCompat # requestPermissions for more details .
return ; } LocationServices . FusedLocationApi . requestLocationUpdates ( mGoogleApiClient , mLocationRequest , this ) ;


signature:
public class ObjectSizing { /** * Calculates and logs the size of first numEntries in the region .
 * @ param region the region to size
 * @ param numEntries the number of entries
 * The number of entries to calculate the size for . If 0
 * all the entries in the region are included . */
public void sizeRegion ( Region < ? , ? > region , int numEntries ) { } }

implementation: if ( region == null ) { throw new IllegalArgumentException ( "Region is null." ) ; } if ( region instanceof PartitionedRegion ) { sizePartitionedRegion ( region , numEntries ) ; } else { sizeReplicatedOrLocalRegion ( region , numEntries ) ; }


signature:
public class ObjectSizing { /** * Sizes numEntries of a partitioned region , or all the entries if
 * numEntries is 0.
 * @ param numEntries
 * Number of entries to size . If the value is 0 , all the
 * entries are sized . */
private void sizePartitionedRegion ( Region < ? , ? > region , int numEntries ) { } }

implementation: Region < ? , ? > primaryDataSet = PartitionRegionHelper . getLocalData ( region ) ; int regionSize = primaryDataSet . size ( ) ; if ( numEntries == 0 ) { numEntries = primaryDataSet . size ( ) ; } else if ( numEntries > regionSize ) { numEntries = regionSize ; } int count = 0 ; for ( Iterator < ? > i = primaryDataSet . entrySet ( ) . iterator ( ) ; i . hasNext ( ) ; ) { if ( count == numEntries ) { break ; } EntrySnapshot entry = ( EntrySnapshot ) i . next ( ) ; RegionEntry re = entry . getRegionEntry ( ) ; dumpSizes ( entry , re ) ; } dumpTotalAndAverageSizes ( numEntries ) ; clearTotals ( ) ;


signature:
public class ObjectSizing { /** * Sizes numEntries of a replicated or local region , or all the entries if
 * numEntries is 0.
 * @ param numEntries Number of entries to size . If the value is 0 , all the
 * entries are sized . */
private void sizeReplicatedOrLocalRegion ( Region < ? , ? > region , int numEntries ) { } }

implementation: Set < ? > entries = region . entrySet ( ) ; int regionSize = entries . size ( ) ; if ( numEntries == 0 ) { numEntries = entries . size ( ) ; } else if ( numEntries > regionSize ) { numEntries = regionSize ; } int count = 0 ; for ( Iterator < ? > i = entries . iterator ( ) ; i . hasNext ( ) ; ) { if ( count == numEntries ) { break ; } LocalRegion . NonTXEntry entry = ( LocalRegion . NonTXEntry ) i . next ( ) ; RegionEntry re = entry . getRegionEntry ( ) ; dumpSizes ( entry , re ) ; } dumpTotalAndAverageSizes ( numEntries ) ; clearTotals ( ) ;


signature: public class GeodeSettings { @ SuppressWarnings ( "unchecked" ) public String getLocators ( ) { } }

implementation: StringBuilder locatorList = new StringBuilder ( ) ; Map < String , ? > credentials = getCredentials ( ) ; if ( credentials == null ) return null ; List < String > locators = ( List < String > ) credentials . get ( "locators" ) ; for ( String locator : locators ) { if ( locatorList . length ( ) != 0 ) locatorList . append ( "," ) ; locatorList . append ( locator ) ; } return locatorList . toString ( ) ;


signature: public class GeodeSettings { @ SuppressWarnings ( "unchecked" ) public List < URI > getLocatorUrlList ( ) { } }

implementation:
List < URI > locatorList = new ArrayList < URI > ( ) ; Map < String , ? > credentials = getCredentials ( ) ; List < String > locators = null ; if ( credentials != null ) locators = ( List < String > ) credentials . get ( "locators" ) ; try { if ( locators == null || locators . isEmpty ( ) ) { // get for LOCATORS env
String locatorsConfig = Config . getProperty ( GeodeConfigConstants . LOCATORS_PROP , "" ) ; if ( locatorsConfig . length ( ) == 0 ) return null ; String [ ] parsedLocators = locatorsConfig . split ( "," ) ; if ( parsedLocators == null || parsedLocators . length == 0 ) return null ; locators = Arrays . asList ( parsedLocators ) ; } for ( String locator : locators ) { Matcher m = regExpPattern . matcher ( locator ) ; if ( ! m . matches ( ) ) { throw new IllegalStateException ( "Unexpected locator format. expected host[port], but got:" + locator ) ; } locatorList . add ( new URI ( "locator://" + m . group ( 1 ) + ":" + m . group ( 2 ) ) ) ; } return locatorList ; } catch ( URISyntaxException e ) { throw new ConfigException ( "One of the provided locators has an incorrect syntax:" + locatorList ) ; }


signature: public class GeodeSettings { @ SuppressWarnings ( { } }

implementation: "unchecked" , "rawtypes" } ) public SecuredToken getSecuredToken ( String username , String token ) { Map < String , ? > credentials = getCredentials ( ) ; if ( credentials == null ) return null ; List < Map < String , String > > users = ( List ) credentials . get ( "users" ) ; if ( users == null ) return null ; Map < String , String > map = null ; if ( username == null || username . trim ( ) . length ( ) == 0 ) { map = users . iterator ( ) . next ( ) ; } else { map = users . stream ( ) . filter ( m -> username . equals ( m . get ( "username" ) ) ) . findFirst ( ) . orElse ( null ) ; } if ( map == null ) return null ; String password = map . get ( "password" ) ; if ( password == null ) password = "" ; return new UserSecuredCredentials ( map . get ( "username" ) , password . toCharArray ( ) , token ) ;


signature: public class GeodeSettings { public void constructPoolLocator ( ClientCacheFactory factory ) { } }

implementation: List < URI > list = this . getLocatorUrlList ( ) ; if ( list != null && ! list . isEmpty ( ) ) { for ( URI uri : list ) { factory . addPoolLocator ( uri . getHost ( ) , uri . getPort ( ) ) ; } } else { factory . addPoolLocator ( this . host , this . port ) ; }


implementation: "unchecked" , "rawtypes" } ) private List < Map < String , ? > > getGemFireService ( Map services ) { List < Map < String , ? > > l = ( List ) services . get ( "p-cloudcache" ) ; return l ;


signature:
public class SnapshotRecordReader { /** * Reads a snapshot entry . If the last entry has been read , a null value will be returned .
 * @ return the entry or null
 * @ throws IOException unable to read entry
 * @ throws ClassNotFoundException unable to create entry */
public SnapshotRecord readSnapshotRecord ( ) throws IOException , ClassNotFoundException { } }

implementation: byte [ ] key = DataSerializer . readByteArray ( dis ) ; if ( key == null ) { return null ; } byte [ ] value = DataSerializer . readByteArray ( dis ) ; return new SnapshotRecord ( key , value ) ;


signature: public class GenericCsvStatsVisitor { @ Override public void visitResourceInst ( ResourceInst resourceInst ) { } }

implementation:
String name = resourceInst . getName ( ) ; ResourceType resourceType = resourceInst . getType ( ) ; boolean skip = resourceType == null || resourceType . getName ( ) == null || ( this . typeName != null && ! resourceType . getName ( ) . toUpperCase ( ) . contains ( this . typeName ) ) ; if ( skip ) { System . out . println ( "skipping resourceType:" + resourceType + " name:" + name ) ; return ; } ArrayList < String > values = new ArrayList < String > ( ) ; ArrayList < String > headers = new ArrayList < String > ( ) ; headers . add ( "name" ) ; values . add ( name ) ; StatValue [ ] statValues = resourceInst . getStatValues ( ) ; if ( statValues == null ) return ; for ( StatValue statValue : statValues ) { String statName = statValue . getDescriptor ( ) . getName ( ) ; if ( this . statNames != null && this . statNames . length > 0 ) { if ( Arrays . binarySearch ( statNames , statName ) < 0 ) continue ; // skip
} StatValue dataStoreEntryCount = resourceInst . getStatValue ( statName ) ; StatDescriptor statDescriptor = resourceInst . getType ( ) . getStat ( statName ) ; headers . add ( statName + "        " + statDescriptor . getDescription ( ) ) ; values . add ( String . valueOf ( dataStoreEntryCount . getSnapshotsMaximum ( ) ) ) ; } writeCsv ( resourceInst , headers , values ) ;


signature: public class GenericCsvStatsVisitor { void writeCsv ( ResourceInst resourceInst , List < String > headers , List < String > values ) { } }

implementation: File file = null ; if ( this . statsFile == null ) file = csvFile ; else file = Paths . get ( this . outputDirectory . toFile ( ) . getAbsolutePath ( ) , this . statsFile . getName ( ) + "." + resourceInst . getType ( ) . getName ( ) + ".csv" ) . toFile ( ) ; CsvWriter csvWriter = new CsvWriter ( file ) ; try { csvWriter . writeHeader ( headers ) ; csvWriter . appendRow ( values ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; }


signature:
public class TimeStampSeries { /** * elapsed millis from base */
void dump ( PrintWriter stream ) { } }

implementation: stream . print ( "[size=" + count ) ; for ( int i = 0 ; i < count ; i ++ ) { if ( i != 0 ) { stream . print ( ", " ) ; stream . print ( timeStamps [ i ] - timeStamps [ i - 1 ] ) ; } else { stream . print ( " " + timeStamps [ i ] ) ; } } stream . println ( "]" ) ;


signature:
public class TimeStampSeries { /** * Returns an array of time stamp values the first of which has the
 * specified index . Each returned time stamp is the number of millis since
 * midnight , Jan 1 , 1970 UTC . */
double [ ] getTimeValuesSinceIdx ( int idx ) { } }

implementation: int resultSize = this . count - idx ; double [ ] result = new double [ resultSize ] ; for ( int i = 0 ; i < resultSize ; i ++ ) { result [ i ] = getMilliTimeStamp ( idx + i ) ; } return result ;


signature: public class RegistrationDTO { public UserProfileDetails toUserDetails ( Collection < String > authorities ) { } }

implementation: if ( this . userName == null || this . userName . length ( ) == 0 ) throw new IllegalArgumentException ( "userName is required" ) ; if ( password == null || password . length == 0 ) throw new IllegalArgumentException ( "Password is required" ) ; if ( authorities == null || authorities . isEmpty ( ) ) throw new IllegalArgumentException ( "authorities is required" ) ; Collection < GrantedAuthority > grantAuthorities = authorities . stream ( ) . map ( a -> new SimpleGrantedAuthority ( a ) ) . collect ( Collectors . toSet ( ) ) ; UserProfileDetails user = new UserProfileDetails ( this . userName , String . valueOf ( password ) , grantAuthorities ) ; user . setEmail ( email ) ; user . setFirstName ( firstName ) ; user . setLastName ( lastName ) ; return user ;


signature:
public class StatsToChart { /** * Accepts a file or directory contain the statistics files
 * @ param file the file or directory
 * @ return the chart for files */
public Chart convert ( File file ) { } }

implementation:
if ( file == null ) return null ; try { if ( file . isDirectory ( ) ) { // Process for all files
Set < File > statsFiles = IO . listFileRecursive ( file , "*.gfs" ) ; if ( statsFiles == null || statsFiles . isEmpty ( ) ) return null ; for ( File statFile : statsFiles ) { GfStatsReader reader = new GfStatsReader ( statFile . getAbsolutePath ( ) ) ; reader . accept ( visitor ) ; } } else { GfStatsReader reader = new GfStatsReader ( file . getAbsolutePath ( ) ) ; reader . accept ( visitor ) ; } return visitor . getChart ( ) ; } catch ( IOException e ) { throw new RuntimeException ( "File:" + file + " ERROR:" + e . getMessage ( ) , e ) ; }


signature:
public class AbstractValue { /** * Calculates each stat given the result of calling getSnapshots */
protected void calcStats ( double [ ] values ) { } }

implementation: if ( statsValid ) { return ; } size = values . length ; if ( size == 0 ) { min = 0.0 ; max = 0.0 ; avg = 0.0 ; stddev = 0.0 ; mostRecent = 0.0 ; } else { min = values [ 0 ] ; max = values [ 0 ] ; mostRecent = values [ values . length - 1 ] ; double total = values [ 0 ] ; for ( int i = 1 ; i < size ; i ++ ) { total += values [ i ] ; if ( values [ i ] < min ) { min = values [ i ] ; } else if ( values [ i ] > max ) { max = values [ i ] ; } } avg = total / size ; stddev = 0.0 ; if ( size > 1 ) { for ( int i = 0 ; i < size ; i ++ ) { double dv = values [ i ] - avg ; stddev += ( dv * dv ) ; } stddev /= ( size - 1 ) ; stddev = Math . sqrt ( stddev ) ; } } statsValid = true ;


signature:
public class GemFireJmxClient { /** * @ param distributedRegionMXBean the distributed region JMX bean
 * @ return return if region . getRegionType contains the term REPLICATE */
public static boolean isReplicatedRegion ( DistributedRegionMXBean distributedRegionMXBean ) { } }

implementation: if ( distributedRegionMXBean == null ) return true ; String type = distributedRegionMXBean . getRegionType ( ) ; return type != null && type . toUpperCase ( Locale . US ) . contains ( "REPLICATE" ) ;


signature: public class GemFireJmxClient { public static DistributedRegionMXBean getRegionMBean ( String regionName , JMX jmx ) { } }

implementation: ObjectName on = getRegionObjectName ( regionName , jmx ) ; if ( on == null ) return null ; DistributedRegionMXBean region = jmx . newBean ( DistributedRegionMXBean . class , on ) ; return region ;


signature:
public class GemFireJmxClient { /** * Dynamically create a GemFire pool with just the server
 * @ param serverName the server name to create a pool for
 * @ param jmx the JMX connection
 * @ return the pool with the server name and its host / port configured
 * @ throws InstanceNotFoundException when the server name does not exist */
public static synchronized Pool getPoolForServer ( String serverName , JMX jmx ) throws InstanceNotFoundException { } }

implementation:
Pool pool = PoolManager . find ( serverName ) ; if ( pool != null ) return pool ; PoolFactory poolFactory = PoolManager . createFactory ( ) ; // LogWriter logWriter = getClientCache ( jmx ) . getLogger ( ) ;
try { // get host name
// ex : object GemFire : type = Member , member = server _ 1
ObjectName objectName = new ObjectName ( new StringBuilder ( "GemFire:type=Member,member=" ) . append ( serverName ) . toString ( ) ) ; String host = jmx . getAttribute ( objectName , "Host" ) ; if ( host == null || host . length ( ) == 0 ) throw new IllegalArgumentException ( "host not found for serverName:" + serverName + " not found" ) ; host = lookupNetworkHost ( host ) ; String findJmxPort = new StringBuilder ( "GemFire:service=CacheServer,port=*,type=Member,member=" ) . append ( serverName ) . toString ( ) ; // search ObjectNames
Set < ObjectName > objectNames = jmx . searchObjectNames ( findJmxPort ) ; if ( objectNames == null || objectNames . isEmpty ( ) ) throw new IllegalArgumentException ( "Unable to to find port with server name:" + serverName ) ; ObjectName portObjectName = objectNames . iterator ( ) . next ( ) ; Integer port = jmx . getAttribute ( portObjectName , "Port" ) ; if ( port == null ) throw new IllegalArgumentException ( "Unable to obtain port for objectName:" + portObjectName + " for server:" + serverName ) ; System . out . println ( "Found cache server host" + host + " port:" + port ) ; poolFactory = poolFactory . addServer ( host , port . intValue ( ) ) ; return poolFactory . create ( serverName ) ; } catch ( InstanceNotFoundException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( "Unable to create pool for servername:" + serverName + " error:" + e . getMessage ( ) , e ) ; }


signature:
public class GemFireJmxClient { /** * This methods create a pool for connecting to a locator
 * @ param jmx the JMX connection
 * @ return the pool instance */
public static synchronized Pool getPoolForLocator ( JMX jmx ) { } }

implementation: String locatorsPoolName = jmx . getHost ( ) + "[" + jmx . getPort ( ) + "]" ; Pool pool = PoolManager . find ( locatorsPoolName ) ; if ( pool != null ) return pool ; PoolFactory poolFactory = PoolManager . createFactory ( ) ; try { int port = getLocatorPort ( jmx ) ; poolFactory = poolFactory . addLocator ( jmx . getHost ( ) , port ) ; return poolFactory . create ( locatorsPoolName ) ; } catch ( Exception e ) { throw new RuntimeException ( "Unable to create pool for locator:" + jmx . getHost ( ) + " error:" + e . getMessage ( ) , e ) ; }


signature:
public class GemFireJmxClient { /** * Get region based on a given name ( create the region if it exists on the server , but not on the client ) .
 * @ param regionName the region name the obtains
 * @ param jmx the GemFire JMX connection
 * @ param < K > the key type
 * @ param < V > the value type
 * @ return the created region */
@ SuppressWarnings ( "unchecked" ) public static < K , V > Region < K , V > getRegion ( String regionName , JMX jmx ) { } }

implementation:
Region < K , V > region = getClientCache ( jmx ) . getRegion ( regionName ) ; if ( region == null ) { // check if region exist on server
if ( isExistingRegionOnServer ( regionName , jmx ) ) { // create it locally
region = ( Region < K , V > ) clientCache . createClientRegionFactory ( ClientRegionShortcut . PROXY ) . create ( regionName ) ; } } return region ;


signature:
public class GemFireJmxClient { /** * < pre >
 * List all regions that match a wildcard expression ( ex : R * ) .
 * Note that special internal regions that begin with the name _ _ will be skipped .
 * < / pre >
 * @ param regionPattern the region pattern
 * @ param jmx the JMX manager connection
 * @ return the collection of region */
public static Collection < Region < ? , ? > > listRootRegions ( String regionPattern , JMX jmx ) { } }

implementation:
// Use JMX to query for distributed regions
// Ex : name GemFire : service = Region , name = / exampleRegion , type = Distributed
String regionJmxPattern = String . format ( "GemFire:service=Region,name=/%s,type=Distributed" , regionPattern ) ; // this . getLogger ( ) . info ( " Searching for JMX region patterns : " + regionJmxPattern ) ;
Set < ObjectName > regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; if ( regionObjNameSet == null || regionObjNameSet . isEmpty ( ) ) { // search with quotes
regionJmxPattern = String . format ( "GemFire:service=Region,name=\"/%s\",type=Distributed" , regionPattern ) ; regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; } if ( regionObjNameSet == null || regionObjNameSet . isEmpty ( ) ) { // this . getLogger ( ) . warn ( " No regions found " ) ;
return null ; } // sort the list
regionObjNameSet = new TreeSet < ObjectName > ( regionObjNameSet ) ; ArrayList < Region < ? , ? > > regionSet = new ArrayList < Region < ? , ? > > ( regionObjNameSet . size ( ) ) ; String regionName = null ; try { for ( ObjectName regionObjectName : regionObjNameSet ) { regionName = jmx . getAttribute ( regionObjectName , "Name" ) ; if ( regionName . startsWith ( "__" ) ) { continue ; // skip special regions
} regionSet . add ( getRegion ( regionName , jmx ) ) ; } return regionSet ; } catch ( InstanceNotFoundException e ) { throw new RuntimeException ( "Cannot list regions:" + regionPattern + " ERROR:" + e . getMessage ( ) , e ) ; }


signature:
public class GemFireJmxClient { /** * Return the client cache based on the JMX connection ( if no cache instance )
 * @ param jmx the gemfire JMX manager connection
 * @ return the Client cache instance */
public static synchronized ClientCache getClientCache ( JMX jmx ) { } }

implementation:
try { if ( clientCache == null || clientCache . isClosed ( ) ) { try { clientCache = ClientCacheFactory . getAnyInstance ( ) ; } catch ( CacheClosedException e ) { clientCache = null ; } if ( clientCache != null ) return clientCache ; // Get Locator port
// locator bean GemFire : service = Locator , type = Member , member = locator
String locatorNamePattern = "GemFire:type=Member,member=*" ; QueryExp queryExp = Query . eq ( Query . attr ( "Manager" ) , Query . value ( true ) ) ; Set < ObjectName > objectNames = jmx . searchObjectNames ( locatorNamePattern , queryExp ) ; if ( objectNames == null || objectNames . isEmpty ( ) ) { throw new RuntimeException ( "Data export error: no manager locators found through JMX connection" ) ; } ObjectName locatorJmxMgrObjName = objectNames . iterator ( ) . next ( ) ; String locatorMemberName = jmx . getAttribute ( locatorJmxMgrObjName , "Member" ) ; ObjectName locatorServiceObjName = new ObjectName ( String . format ( "GemFire:service=Locator,type=Member,member=%s" , locatorMemberName ) ) ; // get port
int port = jmx . getAttribute ( locatorServiceObjName , "Port" ) ; String host = jmx . getAttribute ( locatorJmxMgrObjName , "Host" ) ; host = lookupNetworkHost ( host ) ; clientCache = new ClientCacheFactory ( ) . addPoolLocator ( host , port ) . setPoolSubscriptionEnabled ( false ) . setPdxReadSerialized ( Boolean . valueOf ( System . getProperty ( "PdxReadSerialized" , "false" ) ) . booleanValue ( ) ) . create ( ) ; } return clientCache ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new RuntimeException ( "JMX connection error " + e . getMessage ( ) , e ) ; }


signature:
public class GemFireJmxClient { /** * Determine if a given region exists
 * @ param regionName the region to create
 * @ param jmx the GemFire JMX manager connection
 * @ return true if the region exists , else false */
private static boolean isExistingRegionOnServer ( String regionName , JMX jmx ) { } }

implementation:
String regionJmxPattern = String . format ( "GemFire:service=Region,name=/%s,type=Distributed" , regionName ) ; // System . out . println ( " searching for : " + regionJmxPattern ) ;
Set < ObjectName > regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; if ( regionObjNameSet == null || regionObjNameSet . isEmpty ( ) ) { // search with quotes
regionJmxPattern = String . format ( "GemFire:service=Region,name=\"/%s\",type=Distributed" , regionName ) ; // System . out . println ( " searching for : " + regionJmxPattern ) ;
regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; } return regionObjNameSet != null && ! regionObjNameSet . isEmpty ( ) ;


signature: public class GemFireJmxClient { private static ObjectName getRegionObjectName ( String regionName , JMX jmx ) { } }

implementation:
String regionJmxPattern = String . format ( "GemFire:service=Region,name=/%s,type=Distributed" , regionName ) ; // System . out . println ( " searching for : " + regionJmxPattern ) ;
Set < ObjectName > regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; if ( regionObjNameSet == null || regionObjNameSet . isEmpty ( ) ) { // search with quotes
// GemFire : service = Region , name = " / ui - test - region " , type = Distributed
regionJmxPattern = String . format ( "GemFire:service=Region,name=\"/%s\",type=Distributed" , regionName ) ; // System . out . println ( " searching for : " + regionJmxPattern ) ;
regionObjNameSet = jmx . searchObjectNames ( regionJmxPattern ) ; } if ( regionObjNameSet == null ) return null ; return regionObjNameSet . iterator ( ) . next ( ) ;


signature:
public class GemFireJmxClient { /** * Obtain a GemFire JMX client
 * @ param name the JMX client name
 * @ param jmx the JMX connection
 * @ return JMX member object */
public static MemberMXBean getMember ( String name , JMX jmx ) { } }

implementation: try { String pattern = "GemFire:type=Member,member=" + name ; Set < ObjectName > objectNames = jmx . searchObjectNames ( pattern ) ; if ( objectNames == null || objectNames . isEmpty ( ) ) return null ; ObjectName serverName = new ObjectName ( pattern ) ; return jmx . newBean ( MemberMXBean . class , serverName ) ; } catch ( MalformedObjectNameException e ) { throw new RuntimeException ( "Unable to get member " + name + " ERROR:" + e . getMessage ( ) , e ) ; }


signature: public class GemFireJmxClient { static DistributedSystemMXBean getDistributedSystemMXBean ( JMX jmx ) throws Exception { } }

implementation: DistributedSystemMXBean system = jmx . newBean ( DistributedSystemMXBean . class , new ObjectName ( "GemFire:service=System,type=Distributed" ) ) ; return system ;


signature: public class GemFireJmxClient { public static Collection < GatewayReceiverMXBean > listGatewayReceivers ( JMX jmx ) throws Exception { } }

implementation: DistributedSystemMXBean system = jmx . newBean ( DistributedSystemMXBean . class , new ObjectName ( "GemFire:service=System,type=Distributed" ) ) ; ObjectName [ ] objectNames = system . listGatewayReceiverObjectNames ( ) ; if ( objectNames == null ) return null ; GatewayReceiverMXBean gatewayReceiver = null ; ArrayList < GatewayReceiverMXBean > list = new ArrayList < GatewayReceiverMXBean > ( objectNames . length ) ; for ( ObjectName objectName : objectNames ) { gatewayReceiver = jmx . newBean ( GatewayReceiverMXBean . class , objectName ) ; list . add ( gatewayReceiver ) ; } return list ;


signature:
public class GemFireJmxClient { /** * Determines the unique set of the host names for the distributed system
 * @ param jmx the JMX connection
 * @ return string of server host names */
public static Collection < String > listHosts ( JMX jmx ) { } }

implementation: Set < ObjectName > objectNames = jmx . searchObjectNames ( "GemFire:type=Member,member=*" ) ; if ( objectNames == null || objectNames . isEmpty ( ) ) { return null ; } HashSet < String > hostLists = new HashSet < String > ( objectNames . size ( ) ) ; MemberMXBean memberMXBean = null ; for ( ObjectName objectName : objectNames ) { memberMXBean = jmx . newBean ( MemberMXBean . class , objectName ) ; hostLists . add ( memberMXBean . getHost ( ) ) ; } return hostLists ;


signature:
public class GemFireJmxClient { /** * Supports resolving host network lookup issues
 * @ param host the host to resolve the IP
 * @ return the resolved host ( or original if mapping does not exists ) */
static synchronized String lookupNetworkHost ( String host ) { } }

implementation: try { if ( _bundle == null ) { URL url = GemFireJmxClient . class . getResource ( hostPropFileName ) ; String filePath = null ; if ( url == null ) filePath = hostPropFileName ; else filePath = url . toString ( ) ; System . out . println ( new StringBuilder ( "Loading IP addresses from " ) . append ( filePath ) . toString ( ) ) ; _bundle = ResourceBundle . getBundle ( "host" ) ; } System . out . println ( new StringBuilder ( "Looking for host name \"" ) . append ( host ) . append ( "\" IP address in " ) . append ( hostPropFileName ) . toString ( ) ) ; String newHost = _bundle . getString ( host ) ; System . out . println ( new StringBuilder ( host ) . append ( "=" ) . append ( newHost ) . toString ( ) ) ; return newHost ; } catch ( RuntimeException e ) { System . out . println ( "Using host:" + host ) ; return host ; }


signature: public class ExampleClient { public User getUSer ( String email ) { } }

implementation: try { ExampleFunctionService userService = appContext . getBean ( ExampleFunctionService . class ) ; return userService . findUserByEmail ( email ) ; } finally { appContext . close ( ) ; }


signature:
public class GemFireIO { /** * Determine if the data should be sent
 * @ param resultSender the result sender implementation
 * @ param data the data
 * @ return true if data is an exception */
public static boolean isErrorAndSendException ( ResultSender < Object > resultSender , Object data ) { } }

implementation: if ( data instanceof Throwable ) { Throwable e = ( Throwable ) data ; resultSender . sendException ( e ) ; return true ; } return false ;


signature:
public class GemFireIO { /** * Execute a function with the given execution settings
 * @ param execution the function service execution settings
 * @ param function the function to be execute
 * @ param < T > the type
 * @ return the flatten results from one or more servers
 * @ throws Exception when remote execution errors occur */
@ SuppressWarnings ( "unchecked" ) public static < T > Collection < T > exeWithResults ( Execution < ? , ? , ? > execution , Function < ? > function ) throws Exception { } }

implementation:
ResultCollector < ? , ? > resultCollector ; try { resultCollector = execution . execute ( function ) ; } catch ( FunctionException e ) { if ( e . getCause ( ) instanceof NullPointerException ) throw new RuntimeException ( "Unable to execute function:" + function . getId ( ) + " assert hostnames(s) for locators and cache server can be resovled. " + " If you do not have access to the host file, create host.properties and add to the CLASSPATH. " + " Example: locahost=127.1.0.0 " + " also assert that all cache servers have been initialized. Check if the server's cache.xml has all required <initializer>..</initializer> configurations" , e ) ; else throw e ; } Object resultsObject = resultCollector . getResult ( ) ; // Return a result in collection ( for a single response )
Collection < Object > collectionResults = ( Collection < Object > ) resultsObject ; // if empty return null
if ( collectionResults . isEmpty ( ) ) return null ; Collection < Object > list = new ArrayList < Object > ( collectionResults . size ( ) ) ; flatten ( collectionResults , list ) ; if ( list . isEmpty ( ) ) return null ; return ( Collection < T > ) list ;


signature:
public class GemFireIO { /** * Used to flatten results from multiple servers
 * @ param input the unflatten input
 * @ param flattenOutput the flatten results
 * @ param < T > the return type of collection objects
 * @ throws Exception if an any input collection items are exceptions */
@ SuppressWarnings ( "unchecked" ) public static < T > void flatten ( Collection < Object > input , Collection < Object > flattenOutput ) throws Exception { } }

implementation: if ( input == null || input . isEmpty ( ) || flattenOutput == null ) return ; for ( Object inputObj : input ) { if ( inputObj instanceof Exception ) throw ( Exception ) inputObj ; if ( inputObj == null ) continue ; if ( inputObj instanceof Collection ) flatten ( ( Collection < Object > ) inputObj , flattenOutput ) ; else flattenOutput . add ( inputObj ) ; }


signature: public class GemFireIO { @ SuppressWarnings ( { } }

implementation: "unchecked" , "rawtypes" } ) public static < T > Collection < T > collectResults ( ResultCollector < ? , ? > resultCollector ) throws Exception { if ( resultCollector == null ) return null ; Collection < Object > results = ( Collection ) resultCollector . getResult ( ) ; if ( results == null || results . isEmpty ( ) ) return null ; ArrayList < Object > output = new ArrayList < > ( 10 ) ; flatten ( results , output ) ; if ( output . isEmpty ( ) ) return null ; output . trimToSize ( ) ; return ( Collection ) output ;


signature:
public class Querier { /** * Select results for OQL
 * @ param < ReturnType > the collection return type
 * @ param queryObj the query object
 * @ param rfc the region function context
 * @ param params the bind variables
 * @ return collection of results
 * @ throws FunctionDomainException function error occurs
 * @ throws TypeMismatchException type error occurs
 * @ throws NameResolutionException name resolution exception occurs
 * @ throws QueryInvocationTargetException when query invocation target exception occurs */
@ SuppressWarnings ( "unchecked" ) public static < ReturnType > Collection < ReturnType > query ( Query queryObj , RegionFunctionContext rfc , Object ... params ) throws FunctionDomainException , TypeMismatchException , NameResolutionException , QueryInvocationTargetException { } }

implementation:
SelectResults < ReturnType > selectResults ; // Execute Query locally . Returns results set .
if ( rfc == null || JvmRegionFunctionContext . class . isAssignableFrom ( rfc . getClass ( ) ) ) { if ( params == null || params . length == 0 ) { selectResults = ( SelectResults < ReturnType > ) queryObj . execute ( ) ; } else { selectResults = ( SelectResults < ReturnType > ) queryObj . execute ( params ) ; } if ( selectResults == null || selectResults . isEmpty ( ) ) return null ; ArrayList < ReturnType > results = new ArrayList < ReturnType > ( selectResults . size ( ) ) ; results . addAll ( selectResults . asList ( ) ) ; return results ; } else { if ( params == null || params . length == 0 ) { selectResults = ( SelectResults < ReturnType > ) queryObj . execute ( rfc ) ; } else { selectResults = ( SelectResults < ReturnType > ) queryObj . execute ( rfc , params ) ; } if ( selectResults == null || selectResults . isEmpty ( ) ) return null ; return selectResults ; }


signature:
public class CacheListenerBridge { /** * Factory method for put events registration
 * @ param < K > the key type
 * @ param < V > the value type
 * @ param consumer the observer to notify
 * @ return the listener */
public static < K , V > CacheListenerBridge < K , V > forAfterPut ( Consumer < EntryEvent < K , V > > consumer ) { } }

implementation: return new CacheListenerBridge < K , V > ( consumer , null ) ;


signature:
public class CacheListenerBridge { /** * Factory method for delete events registration
 * @ param < K > the key type
 * @ param < V > the value type
 * @ param consumer the observer to notify
 * @ return the listener */
public static < K , V > CacheListenerBridge < K , V > forAfterDelete ( Consumer < EntryEvent < K , V > > consumer ) { } }

implementation: return new CacheListenerBridge < K , V > ( null , consumer ) ;


signature: public class CacheListenerBridge { private void updateRemoveConsumer ( EntryEvent < K , V > event ) { } }

implementation: if ( this . removeConsumers == null || this . removeConsumers . isEmpty ( ) ) return ; for ( Consumer < EntryEvent < K , V > > removeConsumer : this . removeConsumers ) { removeConsumer . accept ( event ) ; }


signature: public class CacheListenerBridge { private void updatePutConsumer ( EntryEvent < K , V > event ) { } }

implementation: if ( this . putConsumers == null || this . putConsumers . isEmpty ( ) ) return ; for ( Consumer < EntryEvent < K , V > > putConsumer : putConsumers ) { putConsumer . accept ( event ) ; }


signature:
public class GeodeRegionRestService { /** * Put a new records
 * @ param region the region name
 * @ param type teh class name type
 * @ param key the region key
 * @ param value the region value
 * @ return previous Region values in JSON
 * @ throws Exception when an unknown error occurs */
@ PostMapping ( path = "{region}/{type}/{key}" , produces = "application/json" ) public String putEntry ( @ PathVariable String region , @ PathVariable String type , @ PathVariable String key , @ RequestBody String value ) throws Exception { } }

implementation: if ( region == null || region . length ( ) == 0 || key == null || value == null ) return null ; if ( type == null || type . length ( ) == 0 ) throw new IllegalArgumentException ( "type is required. URL pattern {region}/{type}/{key}" ) ; try { Region < String , Object > gemRegion = geode . getRegion ( region ) ; System . out . println ( "Putting key $key in region $region" ) ; Class < ? > clz = Class . forName ( type ) ; Object obj = gson . fromJson ( value , clz ) ; Object response = gemRegion . put ( key , obj ) ; if ( response == null ) return null ; return gson . toJson ( response ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw e ; }


signature:
public class GeodeRegionRestService { /** * Delete a region entry by a key
 * @ param regionName the region name
 * @ param key the region key
 * @ return the deleted region value in JSON format */
@ DeleteMapping ( path = "{regionName}/{key}" , produces = "application/json" ) public String delete ( @ PathVariable String regionName , @ PathVariable String key ) { } }

implementation: Region < String , PdxInstance > region = this . geode . getRegion ( regionName ) ; PdxInstance pdx = region . remove ( key ) ; if ( pdx == null ) return null ; return JSONFormatter . toJSON ( pdx ) ;


signature:
public class GeodeRegionRestService { /** * Get a value by a given key
 * @ param region the region name
 * @ param key the region key
 * @ return the value of the region in JSON format */
@ GetMapping ( path = "{region}/{key}" , produces = "application/json" ) String getValueByKey ( @ PathVariable String region , @ PathVariable String key ) { } }

implementation: try { if ( region == null || region . length ( ) == 0 || key == null ) return null ; Region < String , Object > gemRegion = geode . getRegion ( region ) ; Object value = gemRegion . get ( key ) ; if ( value == null ) return null ; return gson . toJson ( value ) ; } catch ( ServerOperationException serverError ) { Throwable cause = serverError . getRootCause ( ) ; if ( cause instanceof RegionDestroyedException ) { throw new DataServiceSystemException ( "Region \"" + region + "\" not found" ) ; } throw new DataServiceSystemException ( serverError . getMessage ( ) , serverError ) ; } catch ( RuntimeException e ) { e . printStackTrace ( ) ; throw new DataServiceSystemException ( e . getMessage ( ) , e ) ; }


signature:
public class GeodeRegionRestService { /** * Handling exceptions in general for REST responses
 * @ param request the HTTP request
 * @ param response the HTTP reponse
 * @ param e the exception
 * @ return Data Error details */
@ ExceptionHandler ( Exception . class ) private DataError handleException ( HttpServletRequest request , HttpServletResponse response , Exception e ) { } }

implementation: return faultAgent . handleException ( request , response , e ) ;


signature: public class CqQueueListener { @ Override public void close ( ) { } }

implementation: if ( cqQuery != null ) { try { cqQuery . close ( ) ; } catch ( Exception e ) { Debugger . println ( e . getMessage ( ) ) ; } }


signature:
public class FunctionFacts { /** * On region filter facts determine how to parse the inputs typically for CICS to grid calls
 * @ return the onRegionFilterKeyFacts */
public OnRegionFilterKeyFacts [ ] getOnRegionFilterKeyFacts ( ) { } }

implementation: if ( onRegionFilterKeyFacts == null ) return null ; return Arrays . copyOf ( onRegionFilterKeyFacts , onRegionFilterKeyFacts . length ) ;


signature:
public class ReadExportFunction { /** * This function will use the JsonExportFunction function
 * to export json data and read the results to be returned to callers */
@ Override public void execute ( FunctionContext < Object > functionContext ) { } }

implementation:
ResultSender < Object > sender = functionContext . getResultSender ( ) ; Cache cache = CacheFactory . getAnyInstance ( ) ; Logger logWriter = LogManager . getLogger ( getClass ( ) ) ; try { // export data
String [ ] args = ( String [ ] ) functionContext . getArguments ( ) ; if ( args == null || args . length != 2 ) throw new FunctionException ( "Required array args: [region,extension]" ) ; String extensionArg = args [ 0 ] ; if ( extensionArg == null || extensionArg . length ( ) == 0 ) { throw new IllegalArgumentException ( "File extension required" ) ; } ExportFileType extension = ExportFileType . valueOf ( extensionArg ) ; String regionName = args [ 1 ] ; // TODO : accept multiple regions
Region < Object , Object > region = cache . getRegion ( regionName ) ; if ( region == null ) { sender . lastResult ( null ) ; return ; } // TODO : get file from functions
File file = new File ( new StringBuilder ( directoryPath ) . append ( "/" ) . append ( regionName ) . append ( "." ) . append ( extensionArg ) . toString ( ) ) ; // get server name
String serverName = cache . getDistributedSystem ( ) . getDistributedMember ( ) . getName ( ) ; switch ( extension ) { case gfd : new GfdExportFunction ( ) . exportRegion ( region ) ; break ; default : throw new IllegalArgumentException ( "Unsupported extension file type:" + extension ) ; } Serializable content = readContent ( file , extension , logWriter ) ; Serializable [ ] arrayResults = { serverName , content , file . getAbsolutePath ( ) } ; sender . lastResult ( arrayResults ) ; } catch ( Exception e ) { String stackTrace = Debugger . stackTrace ( e ) ; logWriter . error ( stackTrace ) ; throw new FunctionException ( stackTrace ) ; }


signature: public class ReadExportFunction { private Serializable readContent ( File file , ExportFileType exportFileType , Logger logWriter ) throws IOException { } }

implementation: String filePath = file . getAbsolutePath ( ) ; logWriter . info ( "reading " + filePath ) ; switch ( exportFileType ) { case gfd : return IO . readBinaryFile ( file ) ; case json : return IO . readFile ( file . getAbsolutePath ( ) , StandardCharsets . UTF_8 ) ; default : throw new RuntimeException ( "Unknown extension file type:" + exportFileType ) ; }


signature: public class GeodeUserDetailsService { public UserProfileDetails findUserProfileDetailsByUserName ( String userName ) throws UsernameNotFoundException { } }

implementation: UserDetails user = this . loadUserByUsername ( userName ) ; return ( UserProfileDetails ) user ;


signature: public class FunctionAttribute { public int compareTo ( Object aOther ) { } }

implementation:
FunctionAttribute other = ( FunctionAttribute ) aOther ; // compare names
return other . getName ( ) . compareTo ( this . getName ( ) ) ;


signature: public class RegionOps { public static int size ( Region < ? , ? > region ) { } }

implementation: Set < ? > set = region . keySetOnServer ( ) ; if ( set == null || set . isEmpty ( ) ) return 0 ; return set . size ( ) ;


signature: public class QuerierMgr { @ Override public < ReturnType > Collection < ReturnType > query ( String query , Object ... params ) { } }

implementation: return Querier . query ( query , params ) ;


signature:
public class GemFireInspector { /** * List the unique set of host name
 * @ param jmx the JMX connection
 * @ return set of host names */
public static Set < String > listHosts ( JMX jmx ) { } }

implementation:
Set < ObjectName > memberObjects = jmx . searchObjectNames ( "GemFire:type=Member,member=*" ) ; if ( memberObjects == null || memberObjects . isEmpty ( ) ) { return null ; } HashSet < String > hostList = new HashSet < String > ( memberObjects . size ( ) ) ; MemberMXBean bean = null ; for ( ObjectName objectName : memberObjects ) { bean = jmx . newBean ( MemberMXBean . class , objectName ) ; try { hostList . add ( bean . getHost ( ) ) ; } catch ( UndeclaredThrowableException e ) { // will not be added
} } return hostList ;


signature: public class GemFireInspector { public static boolean checkMemberStatus ( String serverName , JMX jmx ) { } }

implementation: try { ObjectName objectName = new ObjectName ( "GemFire:type=Member,member=" + serverName ) ; String status = ( String ) jmx . invoke ( objectName , "status" , null , null ) ; boolean isOnline = status != null && status . contains ( "online" ) ; Debugger . println ( "member:" + serverName + " isOnline:" + isOnline ) ; return isOnline ; } catch ( MalformedObjectNameException e ) { throw new CommunicationException ( e . getMessage ( ) + " server=" + serverName ) ; }


signature:
public class LuceneSearchFunction { /** * Execute the search on Region */
@ SuppressWarnings ( { } }

implementation:
"unchecked" , "rawtypes" } ) @ Override public void execute ( FunctionContext functionContext ) { Cache cache = CacheFactory . getAnyInstance ( ) ; try { // Function must be executed on REgion
if ( ! ( functionContext instanceof RegionFunctionContext ) ) { throw new FunctionException ( "Execute on a region" ) ; } Object args = functionContext . getArguments ( ) ; if ( args == null ) throw new FunctionException ( "arguments is required" ) ; TextPageCriteria criteria = null ; if ( args instanceof PdxInstance ) { PdxInstance pdxInstance = ( PdxInstance ) args ; try { criteria = ( TextPageCriteria ) ( pdxInstance . getObject ( ) ) ; } catch ( PdxSerializationException e ) { throw new FunctionException ( e . getMessage ( ) + " JSON:" + JSONFormatter . toJSON ( pdxInstance ) ) ; } } else { criteria = ( TextPageCriteria ) args ; } Region < String , Collection < Object > > pagingRegion = cache . getRegion ( criteria . getPageRegionName ( ) ) ; Region < ? , ? > region = cache . getRegion ( criteria . getRegionName ( ) ) ; GeodePagination pagination = new GeodePagination ( ) ; TextPolicySearchStrategy geodeSearch = new TextPolicySearchStrategy ( cache ) ; // Collection < String > keys = ( Collection < String > ) checkCachedKeysByCriteria ( criteria , searchRequest , pagination , pagingRegion ) ;
geodeSearch . saveSearchResultsWithPageKeys ( criteria , criteria . getQuery ( ) , null , ( Region < String , Collection < Object > > ) pagingRegion ) ; // build results
Collection < Object > collection = pagination . readResultsByPageValues ( criteria . getId ( ) , criteria . getSortField ( ) , criteria . isSortDescending ( ) , criteria . getBeginIndex ( ) , ( Region < Object , Object > ) region , ( Region ) pagingRegion ) ; if ( collection == null ) { functionContext . getResultSender ( ) . lastResult ( null ) ; return ; } PagingCollection < Object > pageCollection = new PagingCollection < Object > ( collection , criteria ) ; functionContext . getResultSender ( ) . lastResult ( pageCollection ) ; } catch ( RuntimeException e ) { Logger logger = LogManager . getLogger ( LuceneSearchFunction . class ) ; logger . error ( Debugger . stackTrace ( e ) ) ; throw e ; }


signature: public class KeySetSnapshotFilter { @ Override public boolean accept ( Entry < Object , Object > entry ) { } }

implementation: return keys != null && keys . contains ( entry . getKey ( ) ) ;


signature:
public class StatsUtil { /** * Current supports get cache server name
 * Determine the logic name of app
 * @ param resources the resource used to determine namne
 * @ return the application name ( ex : datanode or locator name ) */
public static String getAppName ( ResourceInst [ ] resources ) { } }

implementation: if ( resources == null || resources . length == 0 ) return null ; ResourceType rt = null ; for ( ResourceInst resourceInst : resources ) { if ( resourceInst == null ) continue ; rt = resourceInst . getType ( ) ; if ( rt == null ) continue ; if ( ! "CacheServerStats" . equals ( rt . getName ( ) ) ) continue ; return resourceInst . getName ( ) ; } return null ;


signature:
public class GeodeClient { /** * Initialize security properties
 * @ param props the security properties
 * @ throws IOException */
protected static void constructSecurity ( Properties props ) throws IOException { } }

implementation:
props . setProperty ( "security-client-auth-init" , GeodeConfigAuthInitialize . class . getName ( ) + ".create" ) ; // write to file
File sslFile = saveEnvFile ( GeodeConfigConstants . SSL_KEYSTORE_CLASSPATH_FILE_PROP ) ; System . out . println ( "sslFile:" + sslFile ) ; File sslTrustStoreFile = saveEnvFile ( GeodeConfigConstants . SSL_TRUSTSTORE_CLASSPATH_FILE_PROP ) ; String sslTrustStoreFilePath = "" ; if ( sslTrustStoreFile != null ) sslTrustStoreFilePath = sslTrustStoreFile . getAbsolutePath ( ) ; props . setProperty ( "ssl-keystore" , ( sslFile != null ) ? sslFile . getAbsolutePath ( ) : "" ) ; props . setProperty ( "ssl-keystore-password" , Config . getPropertyEnv ( "ssl-keystore-password" , "" ) ) ; props . setProperty ( "ssl-truststore" , sslTrustStoreFilePath ) ; props . setProperty ( "ssl-protocols" , Config . getPropertyEnv ( "ssl-protocols" , "" ) ) ; props . setProperty ( "ssl-truststore-password" , Config . getPropertyEnv ( "ssl-truststore-password" , "" ) ) ; props . setProperty ( "ssl-keystore-type" , Config . getPropertyEnv ( "ssl-keystore-type" , "" ) ) ; props . setProperty ( "ssl-ciphers" , Config . getPropertyEnv ( "ssl-ciphers" , "" ) ) ; props . setProperty ( "ssl-require-authentication" , Config . getPropertyEnv ( "ssl-require-authentication" , "" ) ) ; props . setProperty ( "ssl-enabled-components" , Config . getPropertyEnv ( "ssl-enabled-components" , "" ) ) ;


signature: public class GeodeClient { static PdxSerializer createPdxSerializer ( String pdxSerializerClassNm , String ... classPatterns ) { } }

implementation: Object [ ] initArgs = { classPatterns } ; return ClassPath . newInstance ( pdxSerializerClassNm , initArgs ) ;


signature: public class GeodeClient { public < K , V > Map < K , V > readSearchResultsByPage ( TextPageCriteria criteria , int pageNumber ) { } }

implementation: GeodeLuceneSearch search = new GeodeLuceneSearch ( this . clientCache ) ; Region < String , Collection < ? > > pageRegion = this . getRegion ( criteria . getPageRegionName ( ) ) ; Region < K , V > region = this . getRegion ( criteria . getRegionName ( ) ) ; return search . readResultsByPage ( criteria , pageNumber , region , pageRegion ) ;


signature: public class GeodeClient { public Collection < String > clearSearchResultsByPage ( TextPageCriteria criteria ) { } }

implementation: GeodeLuceneSearch search = new GeodeLuceneSearch ( this . clientCache ) ; return search . clearSearchResultsByPage ( criteria , this . getRegion ( criteria . getPageRegionName ( ) ) ) ;


signature: public class GeodeClient { @ SuppressWarnings ( { } }

implementation:
"unchecked" , "rawtypes" } ) private < K , V > Region < K , V > createRegion ( String regionName ) { if ( regionName . startsWith ( "/" ) ) regionName = regionName . substring ( 1 ) ; // remove prefix
CacheListenerBridge < K , V > listener = ( CacheListenerBridge ) this . listenerMap . get ( regionName ) ; if ( listener != null ) { ClientRegionFactory < K , V > listenerRegionFactory = null ; if ( this . cachingProxy ) listenerRegionFactory = this . clientCache . createClientRegionFactory ( ClientRegionShortcut . CACHING_PROXY ) ; else listenerRegionFactory = this . clientCache . createClientRegionFactory ( ClientRegionShortcut . PROXY ) ; listenerRegionFactory . addCacheListener ( ( CacheListener ) listener ) ; Region < K , V > region = listenerRegionFactory . create ( regionName ) ; region . registerInterestRegex ( ".*" ) ; return region ; } if ( this . cachingProxy ) return ( Region < K , V > ) this . cachingRegionfactory . create ( regionName ) ; else return ( Region < K , V > ) this . proxyRegionfactory . create ( regionName ) ;


signature:
public class GeodeClient { /** * This is an example to get or create a region
 * @ param regionName the name
 * @ param < K > the key type
 * @ param < V > the value type
 * @ return the existing or created region ( using the ClientbRegionFactory ) */
@ SuppressWarnings ( "unchecked" ) public < K , V > Region < K , V > getRegion ( String regionName ) { } }

implementation:
if ( regionName == null || regionName . length ( ) == 0 ) return null ; Region < K , V > region = ( Region < K , V > ) clientCache . getRegion ( regionName ) ; if ( region != null ) return ( Region < K , V > ) region ; region = ( Region < K , V > ) this . createRegion ( regionName ) ; // Client side data policy is typically NORMAL or EMPTY
if ( cachingProxy ) { // NORMAL data policy are typically used for CACHING _ PROXY
// You should interest so updates for the server will be pushed to the clients
region . registerInterestRegex ( ".*" ) ; } return region ;


signature:
public class GeodeClient { /** * Create a proxy region
 * @ param < K > the region key
 * @ param < V > the region value
 * @ param clientCache the client cache
 * @ param regionName the region name
 * @ return the create region */
@ SuppressWarnings ( "unchecked" ) public static < K , V > Region < K , V > getRegion ( ClientCache clientCache , String regionName ) { } }

implementation: if ( regionName == null || regionName . length ( ) == 0 ) return null ; Region < K , V > region = ( Region < K , V > ) clientCache . getRegion ( regionName ) ; if ( region != null ) return ( Region < K , V > ) region ; region = ( Region < K , V > ) clientCache . createClientRegionFactory ( ClientRegionShortcut . PROXY ) . create ( regionName ) ; return region ;


signature: public class GeodeClient { public < T > BlockingQueue < T > registerCq ( String cqName , String oql ) { } }

implementation:
try { QueryService queryService = this . clientCache . getQueryService ( ) ; // Create CqAttribute using CqAttributeFactory
CqAttributesFactory cqf = new CqAttributesFactory ( ) ; // Create a listener and add it to the CQ attributes callback defined below
CqQueueListener < T > cqListener = new CqQueueListener < T > ( ) ; cqf . addCqListener ( cqListener ) ; CqAttributes cqa = cqf . create ( ) ; // Name of the CQ and its query
// Create the CqQuery
CqQuery cqQuery = queryService . newCq ( cqName , oql , cqa ) ; cqListener . setCqQuery ( cqQuery ) ; // Execute CQ , getting the optional initial result set
// Without the initial result set , the call is priceTracker . execute ( ) ;
cqQuery . execute ( ) ; return cqListener ; } catch ( CqException | CqClosedException | RegionNotFoundException | QueryInvalidException | CqExistsException e ) { throw new nyla . solutions . core . exception . SystemException ( "ERROR:" + e . getMessage ( ) + " cqName:" + cqName + " oql:" + oql , e ) ; }


signature:
public class GeodeClient { /** * Add the observer as a listener for put / create events
 * @ param < K > the region key
 * @ param < V > the region value
 * @ param regionName the region name
 * @ param consumer the observer */
@ SuppressWarnings ( { } }

implementation: "unchecked" , "rawtypes" } ) public < K , V > void registerAfterPut ( String regionName , Consumer < EntryEvent < K , V > > consumer ) { CacheListenerBridge < K , V > listener = ( CacheListenerBridge ) this . listenerMap . get ( regionName ) ; if ( listener == null ) { Region < K , V > region = ( Region < K , V > ) clientCache . getRegion ( regionName ) ; if ( region != null ) throw new IllegalStateException ( "Cannot register a listener when the region already created. Try registering the listener first. Then use GeodeClient.getRegion for regionName:" + regionName ) ; listener = CacheListenerBridge . forAfterPut ( consumer ) ; } else { listener . addAfterPutListener ( consumer ) ; } this . listenerMap . put ( regionName , listener ) ;


signature:
public class GeodeClient { /** * Add the observer as a listener for remove / invalidate events
 * @ param < K > the region key
 * @ param < V > the region value
 * @ param regionName the region name
 * @ param consumer the observer */
@ SuppressWarnings ( { } }

implementation: "unchecked" , "rawtypes" } ) public < K , V > void registerAfterDelete ( String regionName , Consumer < EntryEvent < K , V > > consumer ) { CacheListenerBridge < K , V > listener = ( CacheListenerBridge ) this . listenerMap . get ( regionName ) ; if ( listener == null ) { Region < K , V > region = ( Region < K , V > ) clientCache . getRegion ( regionName ) ; if ( region != null ) throw new IllegalStateException ( "Cannot register a listener when the region already created. Try registering the listener first. Then use GeodeClient.getRegion for regionName:" + regionName ) ; listener = CacheListenerBridge . forAfterDelete ( consumer ) ; } else { listener . addAfterDeleteListener ( consumer ) ; }


signature:
public class RegionDiffDirector { /** * Build the RegionSyncReport the given
 * @ param sourceChecksumMap the source map with the key and entry checksum
 * @ param targetMap the target map */
public void constructComparison ( Map < ? , BigInteger > sourceChecksumMap , Map < ? , BigInteger > targetMap ) { } }

implementation:
if ( sourceChecksumMap == null ) { if ( targetMap != null && ! targetMap . isEmpty ( ) ) { this . keysRemovedFromSource . addAll ( targetMap . keySet ( ) ) ; } return ; } if ( targetMap == null ) { this . keysMissingOnTarget . addAll ( sourceChecksumMap . keySet ( ) ) ; return ; } BigInteger targetBi = null ; BigInteger sourceBi = null ; for ( Map . Entry < ? , BigInteger > entrySource : sourceChecksumMap . entrySet ( ) ) { targetBi = targetMap . get ( entrySource . getKey ( ) ) ; sourceBi = sourceChecksumMap . get ( entrySource . getKey ( ) ) ; if ( targetBi == null ) { keysMissingOnTarget . add ( entrySource . getKey ( ) ) ; } else if ( ! targetBi . equals ( sourceBi ) ) { keysDifferentOnTarget . add ( entrySource . getKey ( ) ) ; } } // determine keysRemovedFromSource
Set < ? > sourceKeySet = sourceChecksumMap . keySet ( ) ; for ( Map . Entry < ? , ? > targetEntry : targetMap . entrySet ( ) ) { if ( ! sourceKeySet . contains ( targetEntry . getKey ( ) ) ) { keysRemovedFromSource . add ( targetEntry . getKey ( ) ) ; } }


signature:
public class ExportJsonFunction { /** * Export region data in JSON format
 * @ param fc the function context */
public void execute ( FunctionContext < Object > fc ) { } }

implementation: ResultSender < Object > rs = fc . getResultSender ( ) ; try { boolean didExport = false ; if ( fc instanceof RegionFunctionContext ) { didExport = exportOnRegion ( ( RegionFunctionContext ) fc ) ; } else { didExport = exportAllRegions ( fc ) ; } rs . lastResult ( didExport ) ; } catch ( Exception e ) { StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; e . printStackTrace ( pw ) ; LogManager . getLogger ( getClass ( ) ) . error ( sw . toString ( ) ) ; rs . sendException ( e ) ; }


signature: public class ExportJsonFunction { private boolean exportAllRegions ( FunctionContext < Object > fc ) { } }

implementation:
String [ ] args = ( String [ ] ) fc . getArguments ( ) ; if ( args == null || args . length == 0 ) { throw new FunctionException ( "Argument not provided" ) ; } // Get region name from arguments
String regionName = args [ 0 ] ; Cache cache = CacheFactory . getAnyInstance ( ) ; Region < Object , Object > region = cache . getRegion ( regionName ) ; return exportRegion ( region ) ;


signature: public class ExportJsonFunction { private boolean exportOnRegion ( RegionFunctionContext rfc ) { } }

implementation:
// get argument
// check if region is partitioned
Region < Object , Object > region = rfc . getDataSet ( ) ; return exportRegion ( region ) ;


signature: public class ExportJsonFunction { private boolean exportRegion ( Region < Object , Object > region ) { } }

implementation:
if ( PartitionRegionHelper . isPartitionedRegion ( region ) ) { region = PartitionRegionHelper . getLocalData ( region ) ; } // get first
ObjectMapper mapper = new ObjectMapper ( ) ; mapper . getSerializerProvider ( ) . setNullKeySerializer ( new DefaultNullKeySerializer ( ) ) ; mapper . getSerializerProvider ( ) . setDefaultKeySerializer ( new DefaultKeySerializer ( ) ) ; Set < Object > keySet = region . keySet ( ) ; if ( keySet == null || keySet . isEmpty ( ) ) { return false ; } String regionName = region . getName ( ) ; Collection < SerializationRegionWrapper > collection = new ArrayList < SerializationRegionWrapper > ( keySet . size ( ) ) ; SerializationRegionWrapper serializationWrapper = null ; try { String keyClassName = null ; Object value = null ; String valueClassName = null ; for ( Object key : keySet ) { keyClassName = key . getClass ( ) . getName ( ) ; value = region . get ( key ) ; valueClassName = value . getClass ( ) . getName ( ) ; serializationWrapper = new SerializationRegionWrapper ( key , keyClassName , value , valueClassName ) ; collection . add ( serializationWrapper ) ; } File resultFile = new File ( new StringBuilder ( this . directoryPath ) . append ( fileSeparator ) . append ( regionName ) . append ( suffix ) . toString ( ) ) ; // write data
mapper . writeValue ( resultFile , collection ) ; return true ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new FunctionException ( "Error exporting ERROR:" + e . getMessage ( ) + " serializationWrapper:" + serializationWrapper , e ) ; }


signature: public class GeodeConfigAuthInitialize { protected String getSecurityPassword ( ) { } }

implementation: String password = Config . getProperty ( PASSWORD , Config . getProperty ( "SECURITY_PASSWORD" , "" ) ) ; return password ;


signature: public class GeodeConfigAuthInitialize { protected String getSecurityUserName ( ) { } }

implementation: String username = Config . getProperty ( USER_NAME , Config . getProperty ( "SECURITY_USERNAME" , "" ) ) ; return username ;


signature:
public class ComboValue { /** * Return true if the current ts must be inserted instead of being mapped to
 * the tsAtInsertPoint */
private static boolean mustInsert ( int nextIdx , long [ ] valueTimeStamps , long tsAtInsertPoint ) { } }

implementation: return ( nextIdx < valueTimeStamps . length ) && ( valueTimeStamps [ nextIdx ] <= tsAtInsertPoint ) ;


signature:
public class ComboValue { /** * Returns true if the timeStamp at curIdx is the one that ts is the closest
 * to . We know that timeStamps [ curIdx - 1 ] , if it exists , was not the
 * closest . */
private static boolean isClosest ( long ts , long [ ] timeStamps , int curIdx ) { } }

implementation:
if ( curIdx >= ( timeStamps . length - 1 ) ) { // curIdx is the last one so it must be the closest
return true ; } if ( ts == timeStamps [ curIdx ] ) { return true ; } return closer ( ts , timeStamps [ curIdx ] , timeStamps [ curIdx + 1 ] ) ;


signature:
public class ResourceInst { /** * Returns the approximate amount of memory used to implement this object . */
protected int getMemoryUsed ( ) { } }

implementation: int result = 0 ; if ( values != null ) { for ( SimpleValue value : values ) { result += value . getMemoryUsed ( ) ; } } return result ;


signature:
public class ResourceInst { /** * Returns true if sample was added . */
protected boolean addValueSample ( int statOffset , long statDeltaBits ) { } }

implementation: if ( this . values != null && this . values [ statOffset ] != null ) { this . values [ statOffset ] . prepareNextBits ( statDeltaBits ) ; return true ; } else { return false ; }


signature:
public class ResourceInst { /** * Frees up any resources no longer needed after the archive file is closed .
 * Returns true if this guy is no longer needed . */
protected boolean close ( ) { } }

implementation: if ( isLoaded ( ) ) { for ( SimpleValue value : values ) { if ( value != null ) { value . shrink ( ) ; } } return false ; } else { return true ; }


signature:
public class ResourceInst { /** * Gets the value of the stat in the current instance given the stat name .
 * @ param name the name of the stat to find in the current instance
 * @ return the value that matches the name or null if the instance does not
 * have a stat of the given name */
public StatValue getStatValue ( String name ) { } }

implementation: StatValue result = null ; StatDescriptor desc = getType ( ) . getStat ( name ) ; if ( desc != null ) { result = values [ desc . getOffset ( ) ] ; } return result ;


signature:
public class GfStatsReader { /** * Checks to see if the archive has changed since the StatArchiverReader
 * instance was created or last updated . If the archive has additional
 * samples then those are read the resource instances maintained by the
 * reader are updated .
 * Once closed a reader can no longer be updated .
 * @ param doReset update flag
 * @ return true if update read some new data .
 * @ throws java . io . IOException
 * if < code > archiveName < / code > could not be opened read , or
 * closed . */
public boolean update ( boolean doReset ) throws IOException { } }

implementation: if ( this . closed ) { return false ; } if ( ! this . updateOK ) { throw new RuntimeException ( "Update of this type of file is not supported" ) ; } if ( doReset ) { this . dataIn . reset ( ) ; } int updateTokenCount = 0 ; while ( this . readToken ( ) ) { updateTokenCount ++ ; } return updateTokenCount != 0 ;


signature:
public class GfStatsReader { /** * Closes the archive .
 * @ throws IOException when an IO error occurs */
public void close ( ) throws IOException { } }

implementation:
if ( ! this . closed ) { this . closed = true ; this . is . close ( ) ; this . dataIn . close ( ) ; this . is = null ; this . dataIn = null ; int typeCount = 0 ; if ( this . resourceTypeTable != null ) { // fix for bug 32320
for ( int i = 0 ; i < this . resourceTypeTable . length ; i ++ ) { if ( this . resourceTypeTable [ i ] != null ) { if ( this . resourceTypeTable [ i ] . close ( ) ) { this . resourceTypeTable [ i ] = null ; } else { typeCount ++ ; } } } ResourceType [ ] newTypeTable = new ResourceType [ typeCount ] ; typeCount = 0 ; for ( ResourceType aResourceTypeTable : this . resourceTypeTable ) { if ( aResourceTypeTable != null ) { newTypeTable [ typeCount ] = aResourceTypeTable ; typeCount ++ ; } } this . resourceTypeTable = newTypeTable ; } if ( this . resourceInstTable != null ) { // fix for bug 32320
int instCount = 0 ; for ( int i = 0 ; i < this . resourceInstTable . length ; i ++ ) { if ( this . resourceInstTable [ i ] != null ) { if ( this . resourceInstTable [ i ] . close ( ) ) { this . resourceInstTable [ i ] = null ; } else { instCount ++ ; } } } ResourceInst [ ] newInstTable = new ResourceInst [ instCount ] ; instCount = 0 ; for ( ResourceInst aResourceInstTable : this . resourceInstTable ) { if ( aResourceInstTable != null ) { newInstTable [ instCount ] = aResourceInstTable ; instCount ++ ; } } this . resourceInstTable = newInstTable ; this . resourceInstSize = instCount ; } // optimize memory usage of timeSeries now that no more samples
this . timeSeries . shrink ( ) ; // filters are no longer needed since file will not be read from
this . filters = null ; }


signature:
public class GfStatsReader { /** * Finds and converts all statistics files in a given directory to CSV
 * @ param directory the top directory
 * @ throws IOException when an IO issues occurs */
public static void toCvsFiles ( File directory ) throws IOException { } }

implementation: Set < File > statsFiles = IO . listFileRecursive ( directory , "*.gfs" ) ; if ( statsFiles == null || statsFiles . isEmpty ( ) ) return ; for ( File archiveFile : statsFiles ) { GfStatsReader reader = new GfStatsReader ( archiveFile . getAbsolutePath ( ) ) ; reader . dumpCsvFiles ( ) ; }


signature:
public class GfStatsReader { /** * Main method to extract GF Stats to file
 * @ param args archiveFile csvFile [ statName ] * */
public static void main ( String [ ] args ) { } }

implementation:
File archiveFile , csvFile ; if ( args . length < 1 ) { System . err . println ( "Usage: java " + GfStatsReader . class . getName ( ) + " archiveFile [csvFile [statName ]*]" ) ; return ; } try { archiveFile = Paths . get ( args [ 0 ] ) . toFile ( ) ; if ( archiveFile . isDirectory ( ) ) { toCvsFiles ( archiveFile ) ; return ; } if ( args . length < 2 ) { GfStatsReader reader = new GfStatsReader ( archiveFile . getAbsolutePath ( ) ) ; reader . dumpCsvFiles ( ) ; return ; } String typeName = args [ 1 ] ; csvFile = Paths . get ( args [ 2 ] ) . toFile ( ) ; GenericCsvStatsVisitor visitor = null ; if ( args . length > 3 ) { String [ ] stateNames = Arrays . copyOfRange ( args , 2 , args . length - 1 ) ; visitor = new GenericCsvStatsVisitor ( csvFile , typeName , stateNames ) ; } else visitor = new GenericCsvStatsVisitor ( csvFile , typeName ) ; System . out . println ( "accepting" ) ; GfStatsReader reader = new GfStatsReader ( archiveFile . getAbsolutePath ( ) ) ; reader . accept ( visitor ) ; } catch ( IOException e ) { // TODO Auto - generated catch block
e . printStackTrace ( ) ; }


signature:
public class SingletonGemFireJmx { /** * Close and recreate the JMX connect
 * @ return the JMX connection */
public synchronized static JMX reconnect ( ) { } }

implementation: try { ClientCache cache = null ; cache = ClientCacheFactory . getAnyInstance ( ) ; if ( cache != null && ! cache . isClosed ( ) ) { cache . close ( ) ; } } catch ( Exception e ) { System . out . println ( "Cache was closed" ) ; } if ( jmx != null ) { jmx . dispose ( ) ; jmx = null ; } return getJmx ( ) ;


signature:
public class SingletonGemFireJmx { /** * Connect / Reconnect to a locator host / port
 * @ param locatorHost the locator host
 * @ param locatorPort the locator port
 * @ return the JMX connection */
public static synchronized JMX reconnectJMX ( String locatorHost , int locatorPort ) { } }

implementation: try { ClientCache cache = null ; cache = ClientCacheFactory . getAnyInstance ( ) ; if ( cache != null && ! cache . isClosed ( ) ) { cache . close ( ) ; } } catch ( Exception e ) { System . out . println ( "Cache was closed" ) ; } if ( jmx != null ) { jmx . dispose ( ) ; jmx = null ; } SingletonGemFireJmx . setLocatorJmxHost ( locatorHost ) ; SingletonGemFireJmx . setLocatorPort ( locatorPort ) ; return getJmx ( ) ;


signature: public class SingletonGemFireJmx { public synchronized static JMX getJmx ( ) { } }

implementation: if ( jmx == null ) jmx = JMX . connect ( locatorJmxHost , locatorJmxPort ) ; return jmx ;


signature:
public class GemFireMgmt { /** * Stops all cache servers followed by locators on a given server
 * @ param hostName the host name and or IP address
 * @ return the number of members */
public static int stopMembersOnHost ( String hostName ) { } }

implementation:
JMX jmx = SingletonGemFireJmx . getJmx ( ) ; String objectNamePattern = "GemFire:type=Member,member=*" ; QueryExp queryExp = null ; ValueExp [ ] values = null ; // Also get the IP
try { InetAddress [ ] addresses = InetAddress . getAllByName ( hostName ) ; InetAddress address = null ; if ( addresses != null ) { values = new ValueExp [ addresses . length ] ; for ( int i = 0 ; i < addresses . length ; i ++ ) { address = addresses [ i ] ; values [ i ] = Query . value ( address . getHostAddress ( ) ) ; } } } catch ( UnknownHostException e ) { Debugger . println ( e . getMessage ( ) ) ; } if ( values != null ) { queryExp = Query . or ( Query . eq ( Query . attr ( "Host" ) , Query . value ( hostName ) ) , Query . in ( Query . attr ( "Host" ) , values ) ) ; } else { queryExp = Query . eq ( Query . attr ( "Host" ) , Query . value ( hostName ) ) ; } /* * QueryExp query = Query . and ( Query . eq ( Query . attr ( " Enabled " ) , Query . value ( true ) ) ,
 Query . eq ( Query . attr ( " Owner " ) , Query . value ( " Duke " ) ) ) ; */
Set < ObjectName > memberObjectNames = jmx . searchObjectNames ( objectNamePattern , queryExp ) ; if ( memberObjectNames == null || memberObjectNames . isEmpty ( ) ) return 0 ; int memberCount = memberObjectNames . size ( ) ; MemberMXBean member = null ; Collection < String > locators = new ArrayList < String > ( ) ; for ( ObjectName objectName : memberObjectNames ) { member = GemFireJmxClient . getMember ( objectName . getKeyProperty ( "member" ) , SingletonGemFireJmx . getJmx ( ) ) ; if ( member . isLocator ( ) ) { locators . add ( member . getName ( ) ) ; } else { shutDownMember ( member . getName ( ) ) ; } } for ( String locatorName : locators ) { shutDownMember ( locatorName ) ; } return memberCount ;


signature:
public class GemFireMgmt { /** * Shut down a given member by its name
 * @ param name cache server name */
public static void shutDownMember ( String name ) { } }

implementation:
try { ObjectName serverName = new ObjectName ( "GemFire:type=Member,member=" + name ) ; JMX jmx = SingletonGemFireJmx . getJmx ( ) ; MemberMXBean bean = jmx . newBean ( MemberMXBean . class , serverName ) ; bean . shutDownMember ( ) ; // wait for member to shutdown
System . out . println ( "Waiting for member:" + name + "  to shutdown" ) ; while ( GemFireJmxClient . checkMemberStatus ( name , SingletonGemFireJmx . getJmx ( ) ) ) { Thread . sleep ( shutDownDelay ) ; } } catch ( MalformedObjectNameException e ) { throw new RuntimeException ( "Unable to shutdown member " + name + " ERROR:" + e . getMessage ( ) , e ) ; } catch ( Exception e ) { System . out . println ( e . getMessage ( ) ) ; }


signature: public class GemFireMgmt { public static void stopLocator ( JMX jmx , String locatorName ) { } }

implementation:
try { ObjectName objectName = new ObjectName ( "GemFire:type=Member,member=" + locatorName ) ; // DistributedSystemMXBean distributedSystemMXBean =
MemberMXBean bean = jmx . newBean ( MemberMXBean . class , objectName ) ; bean . shutDownMember ( ) ; } catch ( MalformedObjectNameException e ) { throw new RuntimeException ( "Cannot stop member:" + locatorName + " ERROR:" + e . getMessage ( ) , e ) ; }


signature:
public class GemFireMgmt { /** * Does not stop locators */
public static String [ ] shutDown ( JMX jmx ) { } }

implementation: try { DistributedSystemMXBean bean = toDistributeSystem ( jmx ) ; return bean . shutDownAllMembers ( ) ; } catch ( Exception e ) { throw new RuntimeException ( " ERROR:" + e . getMessage ( ) , e ) ; }


signature: public class GemFireMgmt { private static DistributedSystemMXBean toDistributeSystem ( JMX jmx ) throws MalformedObjectNameException { } }

implementation:
ObjectName objectName = new ObjectName ( "GemFire:service=System,type=Distributed" ) ; // DistributedSystemMXBean distributedSystemMXBean =
DistributedSystemMXBean bean = jmx . newBean ( DistributedSystemMXBean . class , objectName ) ; return bean ;


signature:
public class GemFireMgmt { /** * Shut down each member in a given RedundancyZone
 * @ param redundancyZone the Redundancy Zone to shutdown */
public static void shutDownRedundancyZone ( String redundancyZone ) { } }

implementation: if ( redundancyZone == null || redundancyZone . length ( ) == 0 ) throw new IllegalArgumentException ( "redundancyZone required" ) ; String objectNamePattern = "GemFire:type=Member,member=*" ; QueryExp exp = Query . eq ( Query . attr ( "RedundancyZone" ) , Query . value ( redundancyZone ) ) ; Collection < ObjectName > memberObjectNames = SingletonGemFireJmx . getJmx ( ) . searchObjectNames ( objectNamePattern , exp ) ; for ( ObjectName objectName : memberObjectNames ) { GemFireMgmt . shutDownMember ( objectName . getKeyProperty ( "member" ) ) ; }


signature:
public class GeodePagination { /** * Store the pagination search result details
 * @ param < K > the key class
 * @ param < V > the value class
 * @ param id the unique id
 * @ param pageSize the page size
 * @ param pageKeysRegion the region where pages keys are stors
 * @ param results the collection os results
 * @ return the list of keys in the page region */
@ SuppressWarnings ( { } }

implementation:
"unchecked" , "rawtypes" } ) public < K , V > List < String > storePaginationMap ( String id , int pageSize , Region < String , Collection < K > > pageKeysRegion , List < Map . Entry < K , V > > results ) { if ( results == null || results . isEmpty ( ) ) return null ; // add to pages
List < Collection < K > > pagesCollection = toKeyPages ( ( List ) results , pageSize ) ; int pageIndex = 1 ; String key = null ; ArrayList < String > keys = new ArrayList < String > ( pageSize ) ; for ( Collection < K > page : pagesCollection ) { // store in region
key = toPageKey ( id , pageIndex ++ ) ; pageKeysRegion . put ( key , page ) ; keys . add ( key ) ; } keys . trimToSize ( ) ; return keys ;


signature:
public class GeodePagination { /** * @ param id the ID
 * @ param pageNumber the page number
 * @ return the id - pageNumber */
public static String toPageKey ( String id , int pageNumber ) { } }

implementation: return new StringBuilder ( ) . append ( id ) . append ( "-" ) . append ( pageNumber ) . toString ( ) ;


signature: public class GeodePagination { public List < String > storePagination ( String sanId , int pageSize , Map < String , Collection < ? > > pageKeysRegion , Collection < String > keys ) { } }

implementation:
if ( keys == null || keys . isEmpty ( ) ) return null ; // add to pages
List < Collection < String > > pagesCollection = Organizer . toPages ( keys , pageSize ) ; String key = null ; int pageIndex = 1 ; ArrayList < String > pageKeys = new ArrayList < String > ( 10 ) ; for ( Collection < String > page : pagesCollection ) { // store in region
key = new StringBuilder ( ) . append ( sanId ) . append ( "-" ) . append ( pageIndex ++ ) . toString ( ) ; pageKeysRegion . put ( key , page ) ; pageKeys . add ( key ) ; } pageKeys . trimToSize ( ) ; return pageKeys ;


signature:
public class GeodePagination { /** * Read Results from region by keys in pageRegion
 * @ param < K > the key class
 * @ param < V > the value class
 * @ param criteria the text page criteria
 * @ param pageNumber the page number to retrieve
 * @ param region the region where data is retrieved
 * @ param pageRegion the page region with key contains the pageKey and value the keys to the region
 * @ return region . getAll ( pageKey ) */
public < K , V > Map < K , V > readResultsByPage ( TextPageCriteria criteria , int pageNumber , Region < K , V > region , Region < String , Collection < ? > > pageRegion ) { } }

implementation: if ( pageRegion == null ) return null ; Collection < ? > regionKeys = pageRegion . get ( criteria . toPageKey ( pageNumber ) ) ; if ( regionKeys == null || regionKeys . isEmpty ( ) ) return null ; return region . getAll ( regionKeys ) ;


signature: public class GfdImportFunction { public void execute ( FunctionContext < Object > fc ) { } }

implementation: ResultSender < Object > rs = fc . getResultSender ( ) ; try { boolean results = false ; if ( fc instanceof RegionFunctionContext ) { results = importOnRegion ( ( RegionFunctionContext ) fc ) ; } else { String [ ] args = ( String [ ] ) fc . getArguments ( ) ; if ( args == null || args . length == 0 ) throw new IllegalArgumentException ( "Arguments with region name required" ) ; String regionName = args [ 0 ] ; this . importRegion ( regionName ) ; } rs . lastResult ( results ) ; } catch ( Exception e ) { String stackTrace = Debugger . stackTrace ( e ) ; LogManager . getLogger ( getClass ( ) ) . error ( stackTrace ) ; rs . sendException ( e ) ; throw new FunctionException ( stackTrace ) ; }


signature: public class GfdImportFunction { private boolean importRegion ( String regionName ) throws Exception { } }

implementation: if ( regionName == null || regionName . length ( ) == 0 ) return false ; Cache cache = CacheFactory . getAnyInstance ( ) ; Region < Object , Object > region = cache . getRegion ( regionName ) ; return importRegion ( region ) ;


signature: public class GfdImportFunction { protected boolean importOnRegion ( RegionFunctionContext rfc ) throws Exception { } }

implementation:
// get argument
// check if region is partitioned
Region < Object , Object > region = rfc . getDataSet ( ) ; return importRegion ( region ) ;


signature:
public class GfdImportFunction { /** * Import exported data from a given
 * @ param region the region to be import
 * @ return true is the import was successful
 * @ throws Exception */
private boolean importRegion ( Region < Object , Object > region ) throws Exception { } }

implementation: File file = DataOpsSecretary . determineFile ( ExportFileType . gfd , region . getName ( ) ) ; if ( ! file . exists ( ) ) return false ; region . getSnapshotService ( ) . load ( file , SnapshotFormat . GEMFIRE ) ; return true ;


signature:
public class GemFireNetworking { /** * Parse the remote locators and locator and assert that they match
 * @ param remoteLocators the remote locator
 * @ param locators the local locator
 * @ return true if locators match */
public static boolean checkRemoteLocatorsAndLocatorsMatch ( String remoteLocators , String locators ) { } }

implementation:
if ( remoteLocators == null || remoteLocators . length ( ) == 0 ) return false ; if ( remoteLocators . equalsIgnoreCase ( locators ) ) return true ; String [ ] remoteLocatorsArray = remoteLocators . split ( "," ) ; if ( locators == null || locators . length ( ) == 0 ) return false ; String [ ] locatorsArray = locators . split ( "," ) ; String remoteLocatorHost , locatorHost ; int remoteLocatorPort , locatorPort ; for ( String remoteLocator : remoteLocatorsArray ) { if ( remoteLocator == null || remoteLocator . length ( ) == 0 ) continue ; // parse host
for ( String locator : locatorsArray ) { if ( locator == null || locator . length ( ) == 0 ) continue ; try { remoteLocatorHost = parseLocatorHost ( remoteLocator ) ; locatorHost = parseLocatorHost ( locator ) ; remoteLocatorPort = parseLocatorPort ( remoteLocator ) ; locatorPort = parseLocatorPort ( locator ) ; if ( Networking . hostEquals ( remoteLocatorHost , locatorHost ) && remoteLocatorPort == locatorPort ) { return true ; } else { // check if ip address match
} } catch ( NumberFormatException e ) { // port parse exception
return false ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( "remoteLocator:" + remoteLocator + " locator:" + locator + " ERROR:" + e . getMessage ( ) , e ) ; } } } return false ;


signature: public class GemFireNetworking { private static String parseLocatorHost ( String locator ) { } }

implementation: int i = locator . indexOf ( "[" ) ; if ( i > 0 ) return locator . substring ( 0 , i ) . trim ( ) ; else return locator . trim ( ) ;