static public boolean getCapture() {
        final Future<Boolean> task = ThreadPoolWorkQueue.submit(new Callable<Boolean>() {
            @Override public Boolean call() {
                return getCaptureSync();
            }
        });

        try {
            return task.get();
        }
        catch (Exception e) {
            return getCaptureSync();
        }
    }

static public boolean getCapture ( ) { final Future < Boolean > task = ThreadPoolWorkQueue . submit ( new Callable < Boolean > ( ) { @ Override public Boolean call ( ) { return getCaptureSync ( ) ; } } ) ; try { return task . get ( ) ; } catch ( Exception e ) { return getCaptureSync ( ) ; } }

Get the current value of the capture flag, indicating that the Logger is recording log calls persistently.

@return current value of capture flag

Get the current value of the capture flag indicating that the Logger is recording log calls persistently .


static public void setMaxLogStoreSize(final int bytes) {
        // 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();
        }
    }

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

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 .


protected static String prependMetadata (String message, JSONObject metadata) {
        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;
    }

protected
static
String
prependMetadata
(
String
message
,
JSONObject
metadata
)
{
try
{
if
(
!=
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
;
}

if we have callstack metadata, prepend it to the message

if we have callstack metadata prepend it to the message


protected static JSONObject appendStackMetadata(JSONObject additionalMetadata) {
        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;
    }

Get stack trace caused by Logger exceptions

@return Returns the JSONObject with stack metadata


private static JSONObject createJSONObject(final Logger.LEVEL level, final String pkg, final String message, long timestamp, final JSONObject jsonMetadata, final Throwable t) {
        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;

    }

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

Will create JSONObject with the passed parameters and other relevant information . See class - level documentation .


public static void logLocation(){
        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);

    }


private static void setUserIdentity(final String user, boolean isInitialCtx) {
        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);
    }

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)

Specify current application user . This value will be hashed to ensure privacy . If your application does not have user context then nothing will happen .


private byte[] getByteArrayFromFile (final String file) throws UnsupportedEncodingException {
        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");
    }

private
byte
[
]
getByteArrayFromFile
(
final
String
file
)
throws
UnsupportedEncodingException
{
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"
)
;
}


protected void startLocationUpdates() {

        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);

    }

//                                          int[] grantResults)


public void sizeRegion(Region<?,?> region, int numEntries) {
	    if (region == null) {
	      throw new IllegalArgumentException("Region is null.");
	    }

	    if (region instanceof PartitionedRegion) {
	      sizePartitionedRegion(region, numEntries);
	    } else {
	      sizeReplicatedOrLocalRegion(region, numEntries);
	    }
	  }

public
void
sizeRegion
(
Region
<
,
>
region
,
int
numEntries
)
{
if
(
region
==
)
{
throw
new
IllegalArgumentException
(
"Region is null."
)
;
}
if
(
region
instanceof
PartitionedRegion
)
{
sizePartitionedRegion
(
region
,
numEntries
)
;
}
else
{
sizeReplicatedOrLocalRegion
(
region
,
numEntries
)
;
}
}

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.

Calculates and logs the size of first numEntries in the region .


private void sizePartitionedRegion(Region<?,?> region, int numEntries) {
	    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();
	  }

private void sizePartitionedRegion ( Region < ? , ? > region , int numEntries ) { 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 ( ) ; }

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.

Sizes numEntries of a partitioned region or all the entries if numEntries is 0 .


private void sizeReplicatedOrLocalRegion(Region<?,?> region, int numEntries) {
	    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();
	  }

private void sizeReplicatedOrLocalRegion ( Region < ? , ? > region , int numEntries ) { 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 ( ) ; }

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.

Sizes numEntries of a replicated or local region or all the entries if numEntries is 0 .


public SnapshotRecord readSnapshotRecord() throws IOException, ClassNotFoundException {
      byte[] key = DataSerializer.readByteArray(dis);
      if (key == null) {
        return null;
      }

      byte[] value = DataSerializer.readByteArray(dis);
      return new SnapshotRecord(key, value);
    }

public SnapshotRecord readSnapshotRecord ( ) throws IOException , ClassNotFoundException { byte [ ] key = DataSerializer . readByteArray ( dis ) ; if ( key == null ) { return null ; } byte [ ] value = DataSerializer . readByteArray ( dis ) ; return new SnapshotRecord ( key , value ) ; }

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

Reads a snapshot entry . If the last entry has been read a null value will be returned .


void dump(PrintWriter stream) {
	      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("]");
	    }

void
dump
(
PrintWriter
stream
)
{
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
(
"]"
)
;
}


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

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

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.

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 .


public Chart convert(File file)
	{
		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);
		}
	}

public
Chart
convert
(
File
file
)
{
if
(
file
==
)
return
;
try
{
if
(
file
.
isDirectory
(
)
)
{
//Process for all files
Set
<
File
>
statsFiles
=
IO
.
listFileRecursive
(
file
,
"*.gfs"
)
;
if
(
statsFiles
==
||
statsFiles
.
isEmpty
(
)
)
return
;
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
)
;
}
}

Accepts a file or directory contain the statistics files
@param file the file or directory
@return the chart for files


public static synchronized Pool getPoolForServer(String serverName, JMX jmx)
	throws InstanceNotFoundException
	{
		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);
		}

	}

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 getPoolForLocator(JMX jmx)
	{
		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);
				}

			}

public
static
synchronized
Pool
getPoolForLocator
(
JMX
jmx
)
{
String
locatorsPoolName
=
jmx
.
getHost
(
)
+
"["
+
jmx
.
getPort
(
)
+
"]"
;
Pool
pool
=
PoolManager
.
find
(
locatorsPoolName
)
;
if
(
pool
!=
)
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
)
;
}
}

This methods create a pool for connecting to a locator
@param jmx the JMX connection
@return the pool instance


private static boolean isExistingRegionOnServer(String regionName,JMX jmx)
	{
		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();
	}

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


public static MemberMXBean getMember(String name,JMX jmx)
	{
		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);
		}

	}

public
static
MemberMXBean
getMember
(
String
name
,
JMX
jmx
)
{
try
{
String
pattern
=
"GemFire:type=Member,member="
+
name
;
Set
<
ObjectName
>
objectNames
=
jmx
.
searchObjectNames
(
pattern
)
;
if
(
objectNames
==
||
objectNames
.
isEmpty
(
)
)
return
;
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
)
;
}
}

Obtain a GemFire JMX client
@param name the JMX client name
@param jmx the JMX connection
@return JMX member object


public static Collection<String> listHosts(JMX jmx)
	{
		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;
	}

public static Collection < String > listHosts ( JMX jmx ) { 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 ; }

Determines the unique set of the host names for the distributed system
@param jmx the JMX connection
@return string of server host names


static synchronized String lookupNetworkHost(String host)
	{
		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;
		}
	}

static
synchronized
String
lookupNetworkHost
(
String
host
)
{
try
{
if
(
_bundle
==
)
{
URL
url
=
GemFireJmxClient
.
class
.
getResource
(
hostPropFileName
)
;
String
filePath
=
;
if
(
url
==
)
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
;
}
}

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)


public static boolean isErrorAndSendException(ResultSender<Object> resultSender, Object data)
	{
		if(data instanceof Throwable)
		{
			Throwable e = (Throwable)data;

			resultSender.sendException(e);
			return true;
		}

		return false;
	}

public static boolean isErrorAndSendException ( ResultSender < Object > resultSender , Object data ) { if ( data instanceof Throwable ) { Throwable e = ( Throwable ) data ; resultSender . sendException ( e ) ; return true ; } return false ; }

Determine if the data should be sent
@param resultSender the result sender implementation
@param data the data
@return true if data is an exception


@SuppressWarnings("unchecked")
	public  static <T> Collection<T> exeWithResults(Execution<?,?,?> execution, Function<?> function)
			throws Exception
	{
		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;

	}

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> void flatten(Collection<Object> input,
			Collection<Object> flattenOutput)
	throws Exception
	{
		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);

		}

	}

@ SuppressWarnings ( "unchecked" ) public static < T > void flatten ( Collection < Object > input , Collection < Object > flattenOutput ) throws Exception { 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 ) ; } }

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 <ReturnType> Collection<ReturnType> query(Query queryObj, RegionFunctionContext rfc, Object... params)
	throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException
	{
		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;
		}

	}

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


public static<K, V> CacheListenerBridge<K, V> forAfterPut(Consumer<EntryEvent<K, V>> consumer)
	{
		return new CacheListenerBridge<K, V>(consumer,null);
	}

public static < K , V > CacheListenerBridge < K , V > forAfterPut ( Consumer < EntryEvent < K , V > > consumer ) { return new CacheListenerBridge < K , V > ( consumer , null ) ; }

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> forAfterDelete(Consumer<EntryEvent<K, V>> consumer)
	{
		return new CacheListenerBridge<K, V>(null,consumer);
	}

public static < K , V > CacheListenerBridge < K , V > forAfterDelete ( Consumer < EntryEvent < K , V > > consumer ) { return new CacheListenerBridge < K , V > ( null , consumer ) ; }

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


@ExceptionHandler(Exception.class)
    private DataError  handleException(HttpServletRequest request, HttpServletResponse response,Exception e )
    {
        return faultAgent.handleException(request,response,e);
    }

@ ExceptionHandler ( Exception . class ) private DataError handleException ( HttpServletRequest request , HttpServletResponse response , Exception e ) { return faultAgent . handleException ( request , response , e ) ; }

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


public OnRegionFilterKeyFacts[] getOnRegionFilterKeyFacts()
	{
		if(onRegionFilterKeyFacts == null)
			return null;

		return Arrays.copyOf(onRegionFilterKeyFacts, onRegionFilterKeyFacts.length);
	}

public OnRegionFilterKeyFacts [ ] getOnRegionFilterKeyFacts ( ) { if ( onRegionFilterKeyFacts == null ) return null ; return Arrays . copyOf ( onRegionFilterKeyFacts , onRegionFilterKeyFacts . length ) ; }

On region filter facts determine how to parse the inputs typically for CICS to grid calls
@return the onRegionFilterKeyFacts


@Override
	public void execute(FunctionContext<Object> functionContext)
	{

		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);
		}

	}

This function will use the JsonExportFunction function
to export json data and read the results to be returned to callers


public static Set<String> listHosts(JMX jmx)
	{
		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;
	}

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

List the unique set of host name
@param jmx the JMX connection
@return set of host names


@SuppressWarnings({ "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;
		}
	}


public static String getAppName(ResourceInst[] resources)
	{
		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;
	}

public static String getAppName ( ResourceInst [ ] resources ) { 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 ; }

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)


protected static void constructSecurity(Properties props) throws IOException
	{
		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",""));

	}

protected
static
void
constructSecurity
(
Properties
props
)
throws
IOException
{
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
!=
)
sslTrustStoreFilePath
=
sslTrustStoreFile
.
getAbsolutePath
(
)
;
props
.
setProperty
(
"ssl-keystore"
,
(
sslFile
!=
)
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"
,
""
)
)
;
}

Initialize security properties
@param props the security properties
@throws IOException


@SuppressWarnings("unchecked")
	public <K,V> Region<K,V> getRegion(String regionName)
	{
		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;
	}

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 static <K,V> Region<K,V> getRegion(ClientCache clientCache, String regionName)
	{
		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;
	}

@ SuppressWarnings ( "unchecked" ) public static < K , V > Region < K , V > getRegion ( ClientCache clientCache , String regionName ) { 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 ; }

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


public void constructComparison(Map<?,BigInteger> sourceChecksumMap, Map<?,BigInteger> targetMap)
	{
		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());
			}
		}

	}

public
void
constructComparison
(
Map
<
,
BigInteger
>
sourceChecksumMap
,
Map
<
,
BigInteger
>
targetMap
)
{
if
(
sourceChecksumMap
==
)
{
if
(
targetMap
!=
&&
!
targetMap
.
isEmpty
(
)
)
{
this
.
keysRemovedFromSource
.
addAll
(
targetMap
.
keySet
(
)
)
;
}
return
;
}
if
(
targetMap
==
)
{
this
.
keysMissingOnTarget
.
addAll
(
sourceChecksumMap
.
keySet
(
)
)
;
return
;
}
BigInteger
targetBi
=
;
BigInteger
sourceBi
=
;
for
(
Map
.
Entry
<
,
BigInteger
>
entrySource
:
sourceChecksumMap
.
entrySet
(
)
)
{
targetBi
=
targetMap
.
get
(
entrySource
.
getKey
(
)
)
;
sourceBi
=
sourceChecksumMap
.
get
(
entrySource
.
getKey
(
)
)
;
if
(
targetBi
==
)
{
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
(
)
)
;
}
}
}

Build the  RegionSyncReport the given
@param sourceChecksumMap the source map with the key and entry checksum
@param targetMap the target map


private static boolean mustInsert(int nextIdx, long[] valueTimeStamps,
	        long tsAtInsertPoint) {
	      return (nextIdx < valueTimeStamps.length)
	          && (valueTimeStamps[nextIdx] <= tsAtInsertPoint);
	    }

private static boolean mustInsert ( int nextIdx , long [ ] valueTimeStamps , long tsAtInsertPoint ) { return ( nextIdx < valueTimeStamps . length ) && ( valueTimeStamps [ nextIdx ] <= tsAtInsertPoint ) ; }

Return true if the current ts must be inserted instead of being mapped to
the tsAtInsertPoint


public void close() throws IOException
	{
		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;
		}
	}

Closes the archive.
@throws IOException when an IO error occurs


public static void toCvsFiles(File directory)
	throws IOException
	{

		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();
		}

	}

public static void toCvsFiles ( File directory ) throws IOException { 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 ( ) ; } }

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 main(String[] args)
	{
		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();
		}
	}

public
static
void
main
(
String
[
]
args
)
{
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
=
;
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
(
)
;
}
}

Main method to extract GF Stats to file
@param args archiveFile csvFile [statName ]*


public synchronized static JMX reconnect()
	{
		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();
	}

public
synchronized
static
JMX
reconnect
(
)
{
try
{
ClientCache
cache
=
;
cache
=
ClientCacheFactory
.
getAnyInstance
(
)
;
if
(
cache
!=
&&
!
cache
.
isClosed
(
)
)
{
cache
.
close
(
)
;
}
}
catch
(
Exception
e
)
{
System
.
out
.
println
(
"Cache was closed"
)
;
}
if
(
jmx
!=
)
{
jmx
.
dispose
(
)
;
jmx
=
;
}
return
getJmx
(
)
;
}

Close and recreate the JMX connect
@return the JMX connection


public static int stopMembersOnHost(String hostName)
	{

		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;
	}

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 void shutDownMember(String name)
	{
		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());
		}
	}

public
static
void
shutDownMember
(
String
name
)
{
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
(
)
)
;
}
}

Shut down a given member by its name
@param name cache server name


public static String [] shutDown(JMX jmx)
	{
		try
		{

			DistributedSystemMXBean bean = toDistributeSystem(jmx);

			return bean.shutDownAllMembers();

		}
		catch (Exception e)
		{
			throw new RuntimeException(" ERROR:"+e.getMessage(),e);
		}

	}

public
static
String
[
]
shutDown
(
JMX
jmx
)
{
try
{
DistributedSystemMXBean
bean
=
toDistributeSystem
(
jmx
)
;
return
bean
.
shutDownAllMembers
(
)
;
}
catch
(
Exception
e
)
{
throw
new
RuntimeException
(
" ERROR:"
+
e
.
getMessage
(
)
,
e
)
;
}
}


public static void shutDownRedundancyZone(String redundancyZone)
   {
	   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"));
	   }
   }

public
static
void
shutDownRedundancyZone
(
String
redundancyZone
)
{
if
(
redundancyZone
==
||
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"
)
)
;
}
}

Shut down each member in a given RedundancyZone
@param redundancyZone the Redundancy Zone to shutdown


@SuppressWarnings({ "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;
	}

@
SuppressWarnings
(
{
"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
==
||
results
.
isEmpty
(
)
)
return
;
//add to pages
List
<
Collection
<
K
>
>
pagesCollection
=
toKeyPages
(
(
List
)
results
,
pageSize
)
;
int
pageIndex
=
1
;
String
key
=
;
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
;
}

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


public <K,V> Map<K,V> readResultsByPage(TextPageCriteria criteria, int pageNumber, Region<K,V> region, Region<String,Collection<?>> pageRegion)
	{
		if(pageRegion == null )
			return null;

		Collection<?> regionKeys = pageRegion.get(criteria.toPageKey(pageNumber));

		if(regionKeys == null|| regionKeys.isEmpty())
			return null;

		return region.getAll(regionKeys);
	}

public < K , V > Map < K , V > readResultsByPage ( TextPageCriteria criteria , int pageNumber , Region < K , V > region , Region < String , Collection < ? > > pageRegion ) { if ( pageRegion == null ) return null ; Collection < ? > regionKeys = pageRegion . get ( criteria . toPageKey ( pageNumber ) ) ; if ( regionKeys == null || regionKeys . isEmpty ( ) ) return null ; return region . getAll ( regionKeys ) ; }

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)


private boolean importRegion(Region<Object, Object> region)
			throws Exception
	{
		File file = DataOpsSecretary.determineFile(ExportFileType.gfd, region.getName());

		if(!file.exists())
			return false;

		region.getSnapshotService().load(file, SnapshotFormat.GEMFIRE);

		return true;
	}

private boolean importRegion ( Region < Object , Object > region ) throws Exception { File file = DataOpsSecretary . determineFile ( ExportFileType . gfd , region . getName ( ) ) ; if ( ! file . exists ( ) ) return false ; region . getSnapshotService ( ) . load ( file , SnapshotFormat . GEMFIRE ) ; return true ; }

Import exported data from a given
@param region the region to be import
@return true is the import was successful
@throws Exception


public static boolean checkRemoteLocatorsAndLocatorsMatch(String remoteLocators, String locators)
	{

		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;

	}

public
static
boolean
checkRemoteLocatorsAndLocatorsMatch
(
String
remoteLocators
,
String
locators
)
{
if
(
remoteLocators
==
||
remoteLocators
.
length
(
)
==
0
)
return
false
;
if
(
remoteLocators
.
equalsIgnoreCase
(
locators
)
)
return
true
;
String
[
]
remoteLocatorsArray
=
remoteLocators
.
split
(
","
)
;
if
(
locators
==
||
locators
.
length
(
)
==
0
)
return
false
;
String
[
]
locatorsArray
=
locators
.
split
(
","
)
;
String
remoteLocatorHost
,
locatorHost
;
int
remoteLocatorPort
,
locatorPort
;
for
(
String
remoteLocator
:
remoteLocatorsArray
)
{
if
(
remoteLocator
==
||
remoteLocator
.
length
(
)
==
0
)
continue
;
//parse host
for
(
String
locator
:
locatorsArray
)
{
if
(
locator
==
||
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
;
}

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


@Override
	public void execute(FunctionContext<Object> functionContext)
	{
		try
		{
			String[] args = (String[])functionContext.getArguments();
			if(args == null || args.length == 0)
				throw new IllegalArgumentException("region argument required");

			String regionName = args[0];

			if(regionName == null || regionName.length() == 0)
				throw new IllegalArgumentException("region name argument required");

			Region<Serializable,Object> region = CacheFactory.getAnyInstance().getRegion(regionName);

			if(region == null)
				throw new IllegalArgumentException("region:"+regionName+" not found");

			functionContext.getResultSender().lastResult(buildCheckSumMap(region));
		}
		catch (Exception e)
		{
			String stack = Debugger.stackTrace(e);
			LogManager.getLogger(getClass()).error(stack);
			throw new FunctionException(stack);
		}
	}

@
Override
public
void
execute
(
FunctionContext
<
Object
>
functionContext
)
{
try
{
String
[
]
args
=
(
String
[
]
)
functionContext
.
getArguments
(
)
;
if
(
args
==
||
args
.
length
==
0
)
throw
new
IllegalArgumentException
(
"region argument required"
)
;
String
regionName
=
args
[
0
]
;
if
(
regionName
==
||
regionName
.
length
(
)
==
0
)
throw
new
IllegalArgumentException
(
"region name argument required"
)
;
Region
<
Serializable
,
Object
>
region
=
CacheFactory
.
getAnyInstance
(
)
.
getRegion
(
regionName
)
;
if
(
region
==
)
throw
new
IllegalArgumentException
(
"region:"
+
regionName
+
" not found"
)
;
functionContext
.
getResultSender
(
)
.
lastResult
(
buildCheckSumMap
(
region
)
)
;
}
catch
(
Exception
e
)
{
String
stack
=
Debugger
.
stackTrace
(
e
)
;
LogManager
.
getLogger
(
getClass
(
)
)
.
error
(
stack
)
;
throw
new
FunctionException
(
stack
)
;
}
}

This function gets HashMap key=Serializable value=BigInteger

@param functionContext contains an argument String[] where the first contains the regionName

This function gets HashMap key = Serializable value = BigInteger


HashMap<Serializable,BigInteger> buildCheckSumMap(Region<Serializable,Object> region)
	{

		if(region.getAttributes().getDataPolicy().withPartitioning())
		{
			region = PartitionRegionHelper.getLocalData(region);
		}

		Set<Serializable> keySet = region.keySet();

		if(keySet == null || keySet.isEmpty())
			return null;

		HashMap<Serializable,BigInteger> regionCheckSumMap = new HashMap<Serializable,BigInteger>(keySet.size());
		Object object = null;

		Object tmp = null;
		for (Map.Entry<Serializable,Object> entry :region.entrySet())
		{
			object = entry.getValue();

			if(PdxInstance.class.isAssignableFrom(object.getClass()))
			{
				tmp = ((PdxInstance)object).getObject();

				if(Serializable.class.isAssignableFrom(tmp.getClass()))
				{
					object = tmp;
				}
				//else use PdxInstance.hashCode
			}

			if(!(PdxInstance.class.isAssignableFrom(object.getClass())))
			{
				regionCheckSumMap.put(entry.getKey(), MD.checksum(object));
			}
			else
			{
				regionCheckSumMap.put(entry.getKey(),  BigInteger.valueOf(object.hashCode()));
			}
		}

		return regionCheckSumMap;
	}

HashMap
<
Serializable
,
BigInteger
>
buildCheckSumMap
(
Region
<
Serializable
,
Object
>
region
)
{
if
(
region
.
getAttributes
(
)
.
getDataPolicy
(
)
.
withPartitioning
(
)
)
{
region
=
PartitionRegionHelper
.
getLocalData
(
region
)
;
}
Set
<
Serializable
>
keySet
=
region
.
keySet
(
)
;
if
(
keySet
==
||
keySet
.
isEmpty
(
)
)
return
;
HashMap
<
Serializable
,
BigInteger
>
regionCheckSumMap
=
new
HashMap
<
Serializable
,
BigInteger
>
(
keySet
.
size
(
)
)
;
Object
object
=
;
Object
tmp
=
;
for
(
Map
.
Entry
<
Serializable
,
Object
>
entry
:
region
.
entrySet
(
)
)
{
object
=
entry
.
getValue
(
)
;
if
(
PdxInstance
.
class
.
isAssignableFrom
(
object
.
getClass
(
)
)
)
{
tmp
=
(
(
PdxInstance
)
object
)
.
getObject
(
)
;
if
(
Serializable
.
class
.
isAssignableFrom
(
tmp
.
getClass
(
)
)
)
{
object
=
tmp
;
}
//else use PdxInstance.hashCode
}
if
(
!
(
PdxInstance
.
class
.
isAssignableFrom
(
object
.
getClass
(
)
)
)
)
{
regionCheckSumMap
.
put
(
entry
.
getKey
(
)
,
MD
.
checksum
(
object
)
)
;
}
else
{
regionCheckSumMap
.
put
(
entry
.
getKey
(
)
,
BigInteger
.
valueOf
(
object
.
hashCode
(
)
)
)
;
}
}
return
regionCheckSumMap
;
}

Build check sum map
@param region the region to build the information
@return the map of the keys/checksums


private Object valueOf(String columnName, Object value) {
    java.lang.reflect.Field field;
    try {
      field = tableObject.getDeclaredField(columnName);
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(
          String.format("%s isEqualTo not a field found in %s", columnName, tableObject));
    }
    return field.getType() == String.class ? String.format("\'%s\'", value) : value;
  }

private
Object
valueOf
(
String
columnName
,
Object
value
)
{
java
.
lang
.
reflect
.
Field
field
;
try
{
field
=
tableObject
.
getDeclaredField
(
columnName
)
;
}
catch
(
NoSuchFieldException
e
)
{
throw
new
RuntimeException
(
String
.
format
(
"%s isEqualTo not a field found in %s"
,
columnName
,
tableObject
)
)
;
}
return
field
.
getType
(
)
==
String
.
class
String
.
format
(
"\'%s\'"
,
value
)
:
value
;
}

Forces the value to be wrapped with ' if it isEqualTo for a string field.

Forces the value to be wrapped with if it isEqualTo for a string field .


boolean isTypeOf(TypeMirror typeMirror) {
    if (integerKinds.contains(typeMirror.getKind())) {
      return true;
    }

    if (integerObjects.contains(typeMirror.toString())) {
      return true;
    }

    return false;
  }

boolean isTypeOf ( TypeMirror typeMirror ) { if ( integerKinds . contains ( typeMirror . getKind ( ) ) ) { return true ; } if ( integerObjects . contains ( typeMirror . toString ( ) ) ) { return true ; } return false ; }

Checks if a TypeMirror is mapped to Sqlite Integer Type

@param typeMirror The TypeMirror to check if it's an Sqlite Integer Type
@return true if it maps to Sqlite Integer false otherwise


public static <T> byte[] serialize(T object) {
    try {
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
      objectOutputStream.writeObject(object);
      return byteArrayOutputStream.toByteArray();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

public static < T > byte [ ] serialize ( T object ) { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; ObjectOutputStream objectOutputStream = new ObjectOutputStream ( byteArrayOutputStream ) ; objectOutputStream . writeObject ( object ) ; return byteArrayOutputStream . toByteArray ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }

Takes an object and serializes it to a byte array. Don't enforce that it extends serializable
to allow for lists and maps to be passed in.

@param object The object to serialize. Must implement {@link java.io.Serializable}
@return The object as a byte array.

Takes an object and serializes it to a byte array . Don t enforce that it extends serializable to allow for lists and maps to be passed in .


public static <K> K deserialize(byte[] bytes) {
    try {
      ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
      ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
      @SuppressWarnings("unchecked") final K k = (K) objectInputStream.readObject();
      return k;
    } catch (IOException e) {
      throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }

public static < K > K deserialize ( byte [ ] bytes ) { try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream ( bytes ) ; ObjectInputStream objectInputStream = new ObjectInputStream ( byteArrayInputStream ) ; @ SuppressWarnings ( "unchecked" ) final K k = ( K ) objectInputStream . readObject ( ) ; return k ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } }

De-serialize a byte array back to it's original object.

@param bytes The bytes that where serialized from an object.
@param <K> The type the bytes should be serialised back too.
@return The de-serialized object.

De - serialize a byte array back to it s original object .


@SuppressWarnings("unchecked")
  public static <T> T createInstance(Class<T> clazz) {
    if (clazz.isInterface()) {
      if (clazz == List.class) {
        return (T) new ArrayList();
      } else if (clazz == Map.class) {
        return (T) new HashMap();
      }

      throw new UnsupportedOperationException("Interface types can not be instantiated.");
    }

    ObjectInstantiator instantiator = OBJENESIS.getInstantiatorOf(clazz);
    return (T) instantiator.newInstance();
  }

Takes a class type and constructs it. If the class does not have an empty constructor this
will
find the parametrized constructor and use nulls and default values to construct the class.

@param clazz The class to construct.
@param <T> The type of the class to construct.
@return The constructed object.

Takes a class type and constructs it . If the class does not have an empty constructor this will find the parametrized constructor and use nulls and default values to construct the class .


private void checkForTableId(TableObject tableObject, Element element) {
    // Check if user wants to use an id other than _id
    Id idAnnotation = element.getAnnotation(Id.class);
    if (idAnnotation != null) {
      if (element.asType().getKind() != TypeKind.LONG && !("java.lang.Long".equals(
          element.asType().toString()))) {
        logger.e("@Id must be on a long");
      }

      // Id attribute set and continue
      String columnName = Strings.isBlank(idAnnotation.name()) //
          ? element.getSimpleName().toString() //
          : idAnnotation.name();

      final TableColumn idColumn = new TableColumn(columnName, element.getSimpleName().toString(),
          element.asType().toString(), SqliteType.INTEGER);

      tableObject.setIdColumn(idColumn);
    }
  }

Check if the element has the @Id annotation if it does use that for it's id


private void checkForFields(TableObject tableObject, Element columnElement) {
    Column columnAnnotation = columnElement.getAnnotation(Column.class);
    if (columnAnnotation == null) return;

    // Convert the element from a field to a type
    final Element typeElement = typeUtils.asElement(columnElement.asType());
    final String type = typeElement == null ? columnElement.asType().toString()
        : elementUtils.getBinaryName((TypeElement) typeElement).toString();

    TableColumn tableColumn = new TableColumn(columnElement, type, columnAnnotation.name());
    if (tableColumn.isBlob() && !tableColumn.isByteArray()) {
      String columnType = columnElement.asType().toString();
      logger.d("Column Element Type: " + columnType);
      if (!checkForSuperType(columnElement, Serializable.class)
          && !columnType.equals("java.lang.Byte[]")
          && !columnType.startsWith("java.util.Map")
          && !columnType.startsWith("java.util.List")) {
        logger.e(String.format(
            "%s in %s is not Serializable and will not be able to be converted to a byte array",
            columnElement.toString(), tableObject.getTableName()));
      }
    } else if (tableColumn.isOneToMany()) {
      // List<T> should only have one generic type. Get that type and make sure
      // it has @Table annotation
      TypeMirror typeMirror = ((DeclaredType) columnElement.asType()).getTypeArguments().get(0);
      if (typeUtils.asElement(typeMirror).getAnnotation(Table.class) == null) {
        logger.e("One to many relationship in class %s where %s is not annotated with @Table",
            tableObject.getTableName(), tableColumn.getColumnName());
      }
      oneToManyCache.put(typeMirror.toString(), tableObject);
      TypeElement childColumnElement = elementUtils.getTypeElement(typeMirror.toString());
      tableColumn.setType(getClassName(childColumnElement, getPackageName(childColumnElement)));
    } else if (tableColumn.getSqlType() == SqliteType.UNKNOWN) {
      @SuppressWarnings("ConstantConditions") Table annotation =
          typeElement.getAnnotation(Table.class);
      if (annotation == null) {
        logger.e(String.format(
            "%s in %s needs to be marked as a blob or should be " + "annotated with @Table",
            columnElement.toString(), tableObject.getTableName()));
      }
      tableColumn.setOneToOne(true);
    }
    tableObject.addColumn(tableColumn);
  }

Check if the element has a @Field annotation if it does parse it and
add it to the table object


private boolean checkForSuperType(Element element, Class type) {
    List<? extends TypeMirror> superTypes = typeUtils.directSupertypes(element.asType());
    for (TypeMirror superType : superTypes) {
      if (superType.toString().equals(type.getName())) {
        return true;
      }
    }
    return false;
  }

private boolean checkForSuperType ( Element element , Class type ) { List < ? extends TypeMirror > superTypes = typeUtils . directSupertypes ( element . asType ( ) ) ; for ( TypeMirror superType : superTypes ) { if ( superType . toString ( ) . equals ( type . getName ( ) ) ) { return true ; } } return false ; }

Checks for a supertype returns true if element has a supertype


private String getSchema() {
    StringBuilder sb = new StringBuilder();
    Iterator<TableColumn> iterator = columns.iterator();
    while (iterator.hasNext()) {
      TableColumn column = iterator.next();
      if (column.isOneToMany()) {
        if (!iterator.hasNext()) {
          // remove the extra ", " after one to many
          int length = sb.length();
          sb.replace(length - 2, length, "");
        }
        continue;
      }
      sb.append(column);
      if (iterator.hasNext()) {
        sb.append(", ");
      }
    }

    // writes out id_missing for logging, the actual idMissing check happens
    // by the annotation processor.
    String idCol = idColumn == null ? "id_missing" : idColumn.getColumnName();
    return String.format(CREATE_TABLE_DEFAULT, getTableName(), idCol, sb.toString());
  }


void brewJava(Writer writer) throws IOException {
    logger.d("brewJava");
    JavaWriter javaWriter = new JavaWriter(writer);
    javaWriter.setCompressingTypes(false);

    javaWriter.emitSingleLineComment("Generated code from Shillelagh. Do not modify!") //
        .emitPackage(classPackage) //
        /* Knows nothing of android types, must use strings. */ //
        .emitImports("android.content.ContentValues", "android.database.Cursor", //
            "android.database.DatabaseUtils", "android.database.sqlite.SQLiteDatabase") //
        .emitImports(ShillelaghUtil.class, ByteArrayInputStream.class, ByteArrayOutputStream.class,
            IOException.class, ObjectInputStream.class, ObjectOutputStream.class, LinkedList.class,
            Date.class, List.class) //
        .beginType(className, "class", EnumSet.of(PUBLIC, FINAL));

    if (this.isChildTable) {
      emitParentInsert(javaWriter);
      emitSelectAll(javaWriter);
    }
    emitInsert(javaWriter);
    emitOneToOneInsert(javaWriter);
    emitGetId(javaWriter);
    emitCreateTable(javaWriter);
    emitDropTable(javaWriter);
    emitUpdate(javaWriter);
    emitUpdateColumnId(javaWriter);
    emitDeleteWithId(javaWriter);
    emitDeleteWithObject(javaWriter);
    emitMapCursorToObject(javaWriter);
    emitSingleMap(javaWriter);
    emitSelectById(javaWriter);
    javaWriter.endType();
  }

Create the java functions required for the internal class


private void emitGetId(JavaWriter javaWriter) throws IOException {
    logger.d("emitGetId");
    javaWriter.beginMethod("long", GET_ID_FUNCTION, EnumSet.of(PUBLIC, STATIC), getTargetClass(),
        "value").emitStatement("return value.%s", idColumn.getMemberName()).endMethod();
  }

private
void
emitGetId
(
JavaWriter
javaWriter
)
throws
IOException
{
logger
.
d
(
"emitGetId"
)
;
javaWriter
.
beginMethod
(
"long"
,
GET_ID_FUNCTION
,
EnumSet
.
of
(
PUBLIC
,
STATIC
)
,
getTargetClass
(
)
,
"value"
)
.
emitStatement
(
"return value.%s"
,
idColumn
.
getMemberName
(
)
)
.
endMethod
(
)
;
}

Create a way to get an id for foreign keys


public final Observable<T> toObservable() {
    if (!HAS_RX_JAVA) {
      throw new RuntimeException(
          "RxJava not available! Add RxJava to your build to use this feature");
    }

    return shillelagh.getObservable(tableObject, new CursorLoader() {
      @Override public Cursor getCursor() {
        return shillelagh.rawQuery(query.toString());
      }
    });
  }

Executes a query and returns the results wrapped in an observable


final void checkColumnName(String columnName) {
    try {
      tableObject.getDeclaredField(columnName);
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(
          String.format("%s isEqualTo not a field found in %s", columnName, tableObject));
    }
  }

final
void
checkColumnName
(
String
columnName
)
{
try
{
tableObject
.
getDeclaredField
(
columnName
)
;
}
catch
(
NoSuchFieldException
e
)
{
throw
new
RuntimeException
(
String
.
format
(
"%s isEqualTo not a field found in %s"
,
columnName
,
tableObject
)
)
;
}
}

Check to ensure that the column name provided is valid


static String valueOrDefault(String string, String defaultString) {
    return isBlank(string) ? defaultString : string;
  }

static String valueOrDefault ( String string , String defaultString ) { return isBlank ( string ) ? defaultString : string ; }

Checks if a string there, if not returns the default string

Checks if a string there if not returns the default string


static String capitalize(String string) {
    if (isBlank(string)) {
      return "";
    }
    char first = string.charAt(0);
    if (Character.isUpperCase(first)) {
      return string;
    } else {
      return Character.toUpperCase(first) + string.substring(1);
    }
  }

static String capitalize ( String string ) { if ( isBlank ( string ) ) { return "" ; } char first = string . charAt ( 0 ) ; if ( Character . isUpperCase ( first ) ) { return string ; } else { return Character . toUpperCase ( first ) + string . substring ( 1 ) ; } }

Capitalizes the first letter of the string passed in


boolean isTypeOf(TypeMirror typeMirror) {
    if (realKinds.contains(typeMirror.getKind())) {
      return true;
    }

    if (realObjects.contains(typeMirror.toString())) {
      return true;
    }

    return false;
  }

boolean isTypeOf ( TypeMirror typeMirror ) { if ( realKinds . contains ( typeMirror . getKind ( ) ) ) { return true ; } if ( realObjects . contains ( typeMirror . toString ( ) ) ) { return true ; } return false ; }

Checks if a TypeMirror is mapped to Sqlite Type

@param typeMirror The TypeMirror to check if it's an Sqlite Type
@return true if it maps to the Sqlite Object false otherwise


public Builder<T> descending() {
    this.query.append(" DESC");
    return new Builder<T>(shillelagh, tableObject, query);
  }

public
Builder
<
T
>
descending
(
)
{
this
.
query
.
append
(
" DESC"
)
;
return
new
Builder
<
T
>
(
shillelagh
,
tableObject
,
query
)
;
}


public float readTemperature() throws IOException {

      byte[] encoded = Files.readAllBytes(new File(deviceFile, "w1_slave").toPath());

      String tmp = new String(encoded);
      int tmpIndex = tmp.indexOf("t=");

      if (tmpIndex < 0) {
         throw new IOException("Could not read temperature!");
      }

      return Integer.parseInt(tmp.substring(tmpIndex + 2).trim()) / 1000f;
   }

public
float
readTemperature
(
)
throws
IOException
{
byte
[
]
encoded
=
Files
.
readAllBytes
(
new
File
(
deviceFile
,
"w1_slave"
)
.
toPath
(
)
)
;
String
tmp
=
new
String
(
encoded
)
;
int
tmpIndex
=
tmp
.
indexOf
(
"t="
)
;
if
(
tmpIndex
<
0
)
{
throw
new
IOException
(
"Could not read temperature!"
)
;
}
return
Integer
.
parseInt
(
tmp
.
substring
(
tmpIndex
+
2
)
.
trim
(
)
)
/
1000f
;
}

Read temperature from the sensors.
@return temperature
@throws IOException
@see {@link TemperatureSensor#readTemperature()}


public static String get(String type) {
    final String returnValue = SUPPORTED_CURSOR_METHODS.get(type);
    return returnValue != null ? returnValue : SUPPORTED_CURSOR_METHODS.get(BLOB);
  }

public static String get ( String type ) { final String returnValue = SUPPORTED_CURSOR_METHODS . get ( type ) ; return returnValue != null ? returnValue : SUPPORTED_CURSOR_METHODS . get ( BLOB ) ; }

Maps a type to the corresponding Cursor get function. For mapping objects between the database
and java. If a type is not found getBlob is returned

Maps a type to the corresponding Cursor get function . For mapping objects between the database and java . If a type is not found getBlob is returned


void n(String message, Object... args) {
    messenger.printMessage(NOTE, formatString(message, args));
  }

void n ( String message , Object ... args ) { messenger . printMessage ( NOTE , formatString ( message , args ) ) ; }


void e(String message, Object... args) {
    messenger.printMessage(ERROR, formatString(message, args));
  }

void e ( String message , Object ... args ) { messenger . printMessage ( ERROR , formatString ( message , args ) ) ; }

Print out errors, this will stop the build from succeeding

Print out errors this will stop the build from succeeding


public static List<IconFont> getIconFonts() {
        List<IconFont> list = new ArrayList<>();
        list.add(GoogleMaterialDesignIcons.getIconFont());
        list.add(Elusive.getIconFont());
        list.add(Entypo.getIconFont());
        list.add(FontAwesome.getIconFont());
        list.add(Iconic.getIconFont());
        list.add(Typicons.getIconFont());
        return list;
    }

public static List < IconFont > getIconFonts ( ) { List < IconFont > list = new ArrayList <> ( ) ; list . add ( GoogleMaterialDesignIcons . getIconFont ( ) ) ; list . add ( Elusive . getIconFont ( ) ) ; list . add ( Entypo . getIconFont ( ) ) ; list . add ( FontAwesome . getIconFont ( ) ) ; list . add ( Iconic . getIconFont ( ) ) ; list . add ( Typicons . getIconFont ( ) ) ; return list ; }

Returns all icon fonts from bundle.

@return List with the fonts.


public static List<IconCode> getIcons() {
        List<IconCode> list = new ArrayList<>();

        for (IconCode icon : GoogleMaterialDesignIcons.values()) {
            list.add(icon);
        }
        for (IconCode icon : Elusive.values()) {
            list.add(icon);
        }
        for (IconCode icon : Entypo.values()) {
            list.add(icon);
        }
        for (IconCode icon : FontAwesome.values()) {
            list.add(icon);
        }
        for (IconCode icon : Iconic.values()) {
            list.add(icon);
        }
        for (IconCode icon : Typicons.values()) {
            list.add(icon);
        }

        return list;
    }

public static List < IconCode > getIcons ( ) { List < IconCode > list = new ArrayList <> ( ) ; for ( IconCode icon : GoogleMaterialDesignIcons . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Elusive . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Entypo . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : FontAwesome . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Iconic . values ( ) ) { list . add ( icon ) ; } for ( IconCode icon : Typicons . values ( ) ) { list . add ( icon ) ; } return list ; }

Returns all icons from bundle.

@return List with the icons.


public VLayout createSldEditorLayout() {

		final VLayout vLayout = new VLayout();

		toolStrip = new ToolStrip();
		toolStrip.setWidth100();

		codeMirrorPanel = new CodeMirrorPanel();
		WidgetCanvas canvas = new WidgetCanvas(codeMirrorPanel);
		canvas.setWidth100();
		canvas.setHeight100();

		vLayout.addMember(toolStrip);
		vLayout.addMember(canvas);

		ToolStripButton saveButton = new ToolStripButton();
		saveButton.setIcon("[ISOMORPHIC]/" + "icons/silk/disk.png");
		saveButton.setTitle(msg.saveButtonTitle());
		saveButton.setTooltip(msg.saveButtonTooltip());
		saveButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent clickEvent) {
				presenter.onSaveButton();
			}
		});

		ToolStripButton cancelButton = new ToolStripButton();
		cancelButton.setIcon("[ISOMORPHIC]/" + "icons/silk/cancel.png");
		cancelButton.setTitle(msg.cancelButtonTitle());
		cancelButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent clickEvent) {
				presenter.onCancelButton();
			}
		});

		ToolStripButton validateButton = new ToolStripButton();
		validateButton.setIcon("[ISOMORPHIC]/" + "icons/silk/tick.png");
		validateButton.setTitle(msg.validateButtonTitle());
		validateButton.setTooltip(msg.validateButtonTooltip());
		validateButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent clickEvent) {
				presenter.onValidateButton();
			}
		});

		ToolStripButton formatBtn = new ToolStripButton();
		formatBtn.setIcon("[ISOMORPHIC]/" + "icons/silk/text_align_left.png");
		formatBtn.setTitle(msg.formatButtonTitle());
		formatBtn.setTooltip(msg.formatButtonTooltip());
		formatBtn.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {
				presenter.onFormatButton();
			}
		});

		selectTemplate = new SelectItem();
		selectTemplate.setTitle(msg.templateSelectTitle());
		selectTemplate.setTooltip(msg.templateSelectTooltip());
		selectTemplate.setWidth(200);
		selectTemplate.addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent changeEvent) {
				presenter.onTemplateSelect((String) changeEvent.getValue());
			}
		});

		toolStrip.addFormItem(selectTemplate);
		toolStrip.addButton(saveButton);
		toolStrip.addButton(validateButton);
		toolStrip.addButton(formatBtn);
		/*
		 * toolStrip.addSeparator(); toolStrip.addButton(saveButton);
		 */
		toolStrip.addFill();
		toolStrip.addButton(cancelButton);

		return vLayout;

	}

Create the Sld Editor layout and attach handlers to the actions.

@return the Sld Editor layout

Create the Sld Editor layout and attach handlers to the actions .


private HTMLFlow getBackgroundDecoration() {

		// Show some background content in the tab.
		HTMLFlow htmlFlow = new HTMLFlow();
		htmlFlow.setWidth100();
		htmlFlow.setHeight100();
		String contents =
			"
GEOMAJAS
"
			+ "
SLD-Editor
"
			+ "
EXPERT-mode
";
		htmlFlow.setContents(contents);

		return htmlFlow;

	}

Create background content decoration for the widget tab.

@return HTMLFlow background content.

Create background content decoration for the widget tab .


public static double raise (final double px, final int pexponent)
  {
    double x = px;
    int exponent = pexponent;
    if (exponent < 0)
      return 1 / raise (x, -exponent);

    double power = 1;

    // Loop to compute x^exponent.
    while (exponent > 0)
    {

      // Is the rightmost exponent bit a 1?
      if ((exponent & 1) == 1)
        power *= x;

      // Square x and shift the exponent 1 bit to the right.
      x *= x;
      exponent >>= 1;
    }

    return power;
  }

Compute and return x^power.

@param px
@param pexponent
the integer power
@return x^power


protected void set (final float values[])
  {
    this.m_nRows = values.length;
    this.m_nCols = 1;
    this.m_aValues = new float [m_nRows] [1];

    for (int r = 0; r < m_nRows; ++r)
    {
      this.m_aValues[r][0] = values[r];
    }
  }

protected void set ( final float values [ ] ) { this . m_nRows = values . length ; this . m_nCols = 1 ; this . m_aValues = new float [ m_nRows ] [ 1 ] ; for ( int r = 0 ; r < m_nRows ; ++ r ) { this . m_aValues [ r ] [ 0 ] = values [ r ] ; } }

Set this column vector from an array of values.

@param values
the array of values

Set this column vector from an array of values .


public static BigDecimal intPower (@Nonnull final BigDecimal px, final long pexponent, final int scale)
  {
    BigDecimal x = px;
    long exponent = pexponent;

    // If the exponent is negative, compute 1/(x^-exponent).
    if (exponent < 0)
    {
      return BigDecimal.ONE.divide (intPower (x, -exponent, scale), scale, RoundingMode.HALF_EVEN);
    }

    BigDecimal power = BigDecimal.ONE;

    // Loop to compute value^exponent.
    while (exponent > 0)
    {

      // Is the rightmost bit a 1?
      if ((exponent & 1) == 1)
      {
        power = power.multiply (x).setScale (scale, RoundingMode.HALF_EVEN);
      }

      // Square x and shift exponent 1 bit to the right.
      x = x.multiply (x).setScale (scale, RoundingMode.HALF_EVEN);
      exponent >>= 1;

      Thread.yield ();
    }

    return power;
  }

Compute x^exponent to a given scale. Uses the same algorithm as class
numbercruncher.mathutils.IntPower.

@param px
the value x
@param pexponent
the exponent value
@param scale
the desired scale of the result
@return the result value

Compute x^exponent to a given scale . Uses the same algorithm as class numbercruncher . mathutils . IntPower .


public static BigDecimal intRoot (@Nonnull final BigDecimal px, final long index, final int scale)
  {
    BigDecimal x = px;

    // Check that x >= 0.
    if (x.signum () < 0)
    {
      throw new IllegalArgumentException ("x < 0: " + x);
    }

    final int sp1 = scale + 1;
    final BigDecimal n = x;
    final BigDecimal i = BigDecimal.valueOf (index);
    final BigDecimal im1 = BigDecimal.valueOf (index - 1);
    final BigDecimal tolerance = BigDecimal.valueOf (5).movePointLeft (sp1);
    BigDecimal xPrev;

    // The initial approximation is x/index.
    x = x.divide (i, scale, RoundingMode.HALF_EVEN);

    // Loop until the approximations converge
    // (two successive approximations are equal after rounding).
    do
    {
      // x^(index-1)
      final BigDecimal xToIm1 = intPower (x, index - 1, sp1);

      // x^index
      final BigDecimal xToI = x.multiply (xToIm1).setScale (sp1, RoundingMode.HALF_EVEN);

      // n + (index-1)*(x^index)
      final BigDecimal numerator = n.add (im1.multiply (xToI)).setScale (sp1, RoundingMode.HALF_EVEN);

      // (index*(x^(index-1))
      final BigDecimal denominator = i.multiply (xToIm1).setScale (sp1, RoundingMode.HALF_EVEN);

      // x = (n + (index-1)*(x^index)) / (index*(x^(index-1)))
      xPrev = x;
      x = numerator.divide (denominator, sp1, RoundingMode.DOWN);

      Thread.yield ();
    } while (x.subtract (xPrev).abs ().compareTo (tolerance) > 0);

    return x;
  }

Compute the integral root of x to a given scale, x ≥ 0. Use Newton's
algorithm.

@param px
the value of x
@param index
the integral root value
@param scale
the desired scale of the result
@return the result value

Compute the integral root of x to a given scale x &ge ; 0 . Use Newton s algorithm .