import java.lang
import java.util.regex
import jarray

# helper function to escape strings for the java regex
def escape(val):
	builder = java.lang.String(val);
	builder.replaceAll(".", "\\.");
	return builder;

# function to help locate a mbean(s) in the provided list
# that match a specific name
def findMBean(prefix, name):
	# get a listing of everything in the current directory
	mydirs = ls(returnMap='true');

	found = [];
		
	# we're going to use a regular expression for our test
	pattern = java.util.regex.Pattern.compile(str(escape(prefix)) + str('.*name=') + str(escape(name)) + str('.*$'));
		
	# loop through the listing
	for mydir in mydirs:
		x = java.lang.String(mydir);
		matcher = pattern.matcher(x);
		# if we find a match, add it to the found list
		while matcher.find():
			found.append(x);
		
	return found;
	
def purgeCache(cacheDirNames):
	if len(cacheDirNames) > 0:
		# for each match, let's purge it
		for cacheDirName in cacheDirNames:
			print 'Purging cache ' + str(cacheDirName);
			cd(cacheDirName);
			params = jarray.array([], java.lang.Object);
			sig = jarray.array([],java.lang.String);
			invoke('removeAll', params, sig);
			#important, must do before we move on to the next cache
			cd('..');
	else:
		print 'No cache found for ' + str(cache);

def main():
	# connect to our server
	connect('weblogic', 'welcome1', 't3://localhost:7001');
	
	# change to our custom tree
	custom();
	
	# navigate to the appropriate location in our custom tree
	cd('net.sf.ehcache');
	
	# find our mbean(s)
	mybean = findMBean('net.sf.ehcache:type=Cache,CacheManager', 'net.sf.ehcache:type=Cache,CacheManager');
	
	# purge our mbean
	purgeCache(mybean);
	
	# be nice and tidy up
	disconnect();
	
main();

