@Override
    @SuppressWarnings("PMD.PreserveStackTrace")
    public final void execute(final EnforcerRuleHelper helper) throws EnforcerRuleException {

        final MavenProject project;
        try {
            project = (MavenProject) helper.evaluate("${project}");
        } catch (final ExpressionEvaluationException e) {

            // Whoops.
            final String msg = "Could not acquire MavenProject. (Expression lookup failure for: "
                    + e.getLocalizedMessage() + ")";
            throw new EnforcerRuleException(msg, e);
        }

        // Delegate.
        try {
            performValidation(project, helper);
        } catch (RuleFailureException e) {

            // Create a somewhat verbose failure message.
            String message =
                    "\n"
                            + "\n#"
                            + "\n# Structure rule failure:"
                            + "\n# " + getShortRuleDescription()
                            + "\n# "
                            + "\n# Message: " + e.getLocalizedMessage()
                            + "\n# " + "\n# Offending project [" + project.getGroupId() + ":"
                            + project.getArtifactId() + ":" + project.getVersion() + "]" + "\n#";

            final Artifact art = e.getOffendingArtifact();
            if (art != null) {

                message += "\n# Offending artifact [" + art.getGroupId() + ":" + art.getArtifactId()
                        + ":" + art.getVersion() + "]"
                        + "\n#";
            }
            message += "\n";

            // Re-throw for pretty print
            throw new EnforcerRuleException(message);
        }
    }

This is the interface into the rule. This method should throw an exception
containing a reason message if the rule fails the check. The plugin will
then decide based on the fail flag if it should stop or just log the
message as a warning.

@param helper The helper provides access to the log, MavenSession and has
helpers to get common components. It is also able to lookup components
by class name.
@throws org.apache.maven.enforcer.rule.api.EnforcerRuleException the enforcer rule exception

This is the interface into the rule . This method should throw an exception containing a reason message if the rule fails the check . The plugin will then decide based on the fail flag if it should stop or just log the message as a warning .


protected static List<String> splice(final String toSplice) {

        final List<String> toReturn = new ArrayList<String>();

        final StringTokenizer tok = new StringTokenizer(toSplice, ",", false);
        while (tok.hasMoreTokens()) {
            toReturn.add(tok.nextToken());
        }

        return toReturn;
    }

protected static List < String > splice ( final String toSplice ) { final List < String > toReturn = new ArrayList < String > ( ) ; final StringTokenizer tok = new StringTokenizer ( toSplice , "," , false ) ; while ( tok . hasMoreTokens ( ) ) { toReturn . add ( tok . nextToken ( ) ) ; } return toReturn ; }

Helper method which splices the provided string into a List, separating on commas.

@param toSplice The string to splice
@return A list holding the elements of the spliced string.

Helper method which splices the provided string into a List separating on commas .


protected static List<Pattern> splice2Pattern(final String toSplice) throws PatternSyntaxException {

        final List<Pattern> toReturn = new ArrayList<Pattern>();

        for (final String current : splice(toSplice)) {
            toReturn.add(Pattern.compile(current));
        }

        return toReturn;
    }

protected static List < Pattern > splice2Pattern ( final String toSplice ) throws PatternSyntaxException { final List < Pattern > toReturn = new ArrayList < Pattern > ( ) ; for ( final String current : splice ( toSplice ) ) { toReturn . add ( Pattern . compile ( current ) ) ; } return toReturn ; }

Helper method which splices the provided String into a List of Pattern instances.

@param toSplice The string to splice
@return A List holding the elements of the spliced string, converted to Patterns
@throws PatternSyntaxException if the {@code Pattern.compile} method could not compile the provided string.

Helper method which splices the provided String into a List of Pattern instances .


protected static boolean containsPrefix(final List<String> source, final String toCheck) {

        if (source != null) {

            for (final String current : source) {
                if (toCheck.startsWith(current)) {
                    return true;
                }
            }
        }

        // The prefix was not found within the provided string toCheck.
        return false;
    }

Checks if any element within source startsWith the provided toCheck string.

@param source  The list of strings which could possibly contain toCheck.
@param toCheck The string to validate.
@return true if any element within source returns true to
toCheck.startsWith(element).

Checks if any element within source startsWith the provided toCheck string .


private static Class<?extends ObjectFactory> getFactoryClass(Class<?> factoryClass) {
        if(factoryPackages.size() == 0) throw new IllegalArgumentException("No package provide to look for factories.");

        if(factoryClasses == null) {
            factoryClasses = new HashMap<Class<?>, Class<? extends ObjectFactory>>();
            Set<Class<?extends ObjectFactory>> classes = ReflectionUtils.getSubclassesOf(ObjectFactory.class, factoryPackages);

            for(Class<?extends ObjectFactory> clazz : classes) {
                if(! Modifier.isAbstract(clazz.getModifiers())) {
                    try {
                        Constructor constructor = clazz.getConstructor();
                        ObjectFactory factory = (ObjectFactory)constructor.newInstance();
                        factoryClasses.put(factory.getFactoryClass(), factory.getClass());
                    } catch (Exception e) {
                        throw new RuntimeException(e); //should not happen, compiler forces factory classes to implement correct constructor.
                    }
                }
            }
        }

        return factoryClasses.get(factoryClass);
    }

Get the class of the Factory for the given factoryClass.
@param factoryClass
@return

Get the class of the Factory for the given factoryClass .


public void send(String subject, String content) throws MessagingException {
		MimeMessage message = compose(subject, content,
				propertiesHelper.getStringProperty("mail.to"));
		transport(message);
	}

public void send ( String subject , String content ) throws MessagingException { MimeMessage message = compose ( subject , content , propertiesHelper . getStringProperty ( "mail.to" ) ) ; transport ( message ) ; }

Sends email with subject and content to receivers specified in property file after key "mail.to"

@param subject - the subject
@param content - the content
@throws MessagingException

Sends email with subject and content to receivers specified in property file after key mail . to


public void send(String subject, String content, String to)
			throws MessagingException {
		MimeMessage message = compose(subject, content, to);
		transport(message);
	}

public void send ( String subject , String content , String to ) throws MessagingException { MimeMessage message = compose ( subject , content , to ) ; transport ( message ) ; }

Sends email with subject and content to receivers specified by argument "to"

@param subject - the subject
@param content - the content
@param to - the CSV list of receivers
@throws MessagingException

Sends email with subject and content to receivers specified by argument to


private int executeZeroFunction(Pool pool) throws FunctionException,
		InterruptedException {
		int result = -1;

		ResultCollector<?, ?> collector = FunctionService.onServer(pool)
			.execute(new ZeroFunction());

		List<?> functionResult = (List<?>) collector.getResult();
		if ((functionResult != null) && (functionResult.size() == 1)
			&& (functionResult.get(0) instanceof Integer)) {
			result = (Integer) functionResult.get(0);
		}

		return result;
	}

private int executeZeroFunction ( Pool pool ) throws FunctionException , InterruptedException { int result = - 1 ; ResultCollector < ? , ? > collector = FunctionService . onServer ( pool ) . execute ( new ZeroFunction ( ) ) ; List < ? > functionResult = ( List < ? > ) collector . getResult ( ) ; if ( ( functionResult != null ) && ( functionResult . size ( ) == 1 ) && ( functionResult . get ( 0 ) instanceof Integer ) ) { result = ( Integer ) functionResult . get ( 0 ) ; } return result ; }

Executes the "zero" function using pool for the concrete server.

@param pool
- the pool for the concrete server
@return 0 in case of function executed without problems, -1 otherwise
@throws FunctionException
@throws InterruptedException

Executes the zero function using pool for the concrete server .


@Override
    @SuppressWarnings({ "ThrowableInstanceNeverThrown", "unchecked" })
    public void execute(FunctionContext functionContext) {
	ResultSender<Serializable> resultSender = functionContext.getResultSender();

	RegionFunctionContext regionFunctionContext = (RegionFunctionContext) functionContext;

	if (functionContext.getArguments() == null) {
	    handleException(new FunctionException("You must specify function argument for query execution."),
		    resultSender, null);

	    return;
	}

	if (!(functionContext.getArguments() instanceof BucketOrientedQueryFunctionArgument)) {
	    handleException(new FunctionException("Function arguments must be of type "
		    + BucketOrientedQueryFunctionArgument.class.getName() + "."), resultSender, null);

	    return;
	}

	BucketOrientedQueryFunctionArgument argument = (BucketOrientedQueryFunctionArgument) functionContext
		.getArguments();

	LocalDataSet localData = (LocalDataSet) PartitionRegionHelper.getLocalDataForContext(regionFunctionContext);

	QueryService queryService = localData.getCache().getQueryService();

	String queryStr = argument.getQueryString();

	try {
	    Query query = queryService.newQuery(queryStr);

	    SelectResults<?> result = (SelectResults<?>) localData.executeQuery((DefaultQuery) query,
		    argument.getQueryParameters(), localData.getBucketSet());

	    resultSender.lastResult((Serializable) formatResults(result));
	} catch (Exception e) {
	    handleException(e, resultSender, queryStr);
	}
    }

Executes query using arguments query string and query parameters.

@param functionContext Function context.

Executes query using arguments query string and query parameters .


@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
    private void handleException(Throwable e, ResultSender<Serializable> resultSender, String queryString) {
	logger.error("Failed to execute bucket oriented query" + (queryString != null ? ": " + queryString : "."), e);

	resultSender.sendException(new FunctionException(e.getMessage()));
    }

Handles exceptions during query execution.

@param e Exception to handle.
@param resultSender of type ResultSender<Serializable>

Handles exceptions during query execution .


private List<Object> formatResults(SelectResults<?> selectResults) {
	List<Object> results = new ArrayList<Object>(selectResults.size() + 1);

	results.addAll(selectResults.asList());
	results.add(selectResults.getCollectionType().getElementType());

	return results;
    }

private List < Object > formatResults ( SelectResults < ? > selectResults ) { List < Object > results = new ArrayList < Object > ( selectResults . size ( ) + 1 ) ; results . addAll ( selectResults . asList ( ) ) ; results . add ( selectResults . getCollectionType ( ) . getElementType ( ) ) ; return results ; }

Formats results of query execution.

@param selectResults of type SelectResults
@return List<Object>


@Override
    public final void addErrorMessage(final String message) {
        if (message == null || "".equals(message)) {
            return;
        }

        // All done.
        errorMessages.add(message);
    }

@
Override
public
final
void
addErrorMessage
(
final
String
message
)
{
if
(
message
==
||
""
.
equals
(
message
)
)
{
return
;
}
// All done.
errorMessages
.
add
(
message
)
;
}

Adds the provided error message to this ErrorMessageContainer.

@param message The message to add, provided that the message is neither null nor empty.

Adds the provided error message to this ErrorMessageContainer .


@Override
    public String getMessage() {

        final StringBuilder builder = new StringBuilder();
        for (final String current : errorMessages) {
            builder.append(current).append("\n");
        }

        // All done.
        return builder.toString();
    }

@
Override
public
String
getMessage
(
)
{
final
StringBuilder
builder
=
new
StringBuilder
(
)
;
for
(
final
String
current
:
errorMessages
)
{
builder
.
append
(
current
)
.
append
(
"\n"
)
;
}
// All done.
return
builder
.
toString
(
)
;
}

Returns the detail message string of this throwable.

@return the detail message string of this <tt>Throwable</tt> instance (which may be <tt>null</tt>).

Returns the detail message string of this throwable .


public static boolean isSocketAlive(String host, int port) {
	boolean socketAlive = false;
	Socket socket = null;

	try {
	    socket = new Socket(host, port);

	    socketAlive = socket.isConnected();
	} catch (Throwable t) {
	    // do nothing
	} finally {
	    if (socket != null) {
		try {
		    socket.close();
		} catch (IOException e) {
		    // do nothing
		}
	    }
	}

	return socketAlive;
    }

public
static
boolean
isSocketAlive
(
String
host
,
int
port
)
{
boolean
socketAlive
=
false
;
Socket
socket
=
;
try
{
socket
=
new
Socket
(
host
,
port
)
;
socketAlive
=
socket
.
isConnected
(
)
;
}
catch
(
Throwable
t
)
{
// do nothing
}
finally
{
if
(
socket
!=
)
{
try
{
socket
.
close
(
)
;
}
catch
(
IOException
e
)
{
// do nothing
}
}
}
return
socketAlive
;
}

Checks if the socket of specified host and port is alive.

@param host
- the host.
@param port
- the port.
@return - true if alive, false otherwise.

Checks if the socket of specified host and port is alive .


public static void execute(Thread thread, long timeout) {
	thread.start();

	try {
	    thread.join(timeout);
	} catch (InterruptedException e) {
	    // Should not be interrupted normally.
	}

	if (thread.isAlive()) {
	    thread.interrupt();
	}
    }

public
static
void
execute
(
Thread
thread
,
long
timeout
)
{
thread
.
start
(
)
;
try
{
thread
.
join
(
timeout
)
;
}
catch
(
InterruptedException
e
)
{
// Should not be interrupted normally.
}
if
(
thread
.
isAlive
(
)
)
{
thread
.
interrupt
(
)
;
}
}

Executes the thread with specified timeout.

@param thread
- the thread to execute.
@param timeout
- the timeout.

Executes the thread with specified timeout .


private boolean hasResources(List<Resource> resources) {
        for (Resource resource : resources) {
            if (new File(resource.getDirectory()).exists()) {
                return true;
            }
        }
        return false;
    }

private boolean hasResources ( List < Resource > resources ) { for ( Resource resource : resources ) { if ( new File ( resource . getDirectory ( ) ) . exists ( ) ) { return true ; } } return false ; }

Check if any of the resources exist.

@param resources The resources to check
@return true if the resource directory exist


private void mergeDeprecatedInfo()
            throws MavenReportException {
        if ("sun_checks.xml".equals(configLocation) && !"sun".equals(format)) {
            configLocation = FORMAT_TO_CONFIG_LOCATION.get(format);

            throw new MavenReportException("'format' parameter is deprecated: please replace with <configLocation>"
                    + configLocation + "</configLocation>.");
        }

        if (StringUtils.isEmpty(propertiesLocation)) {
            if (propertiesFile != null) {
                propertiesLocation = propertiesFile.getPath();

                throw new MavenReportException("'propertiesFile' parameter is deprecated: please replace with "
                        + "<propertiesLocation>" + propertiesLocation + "</propertiesLocation>.");
            } else if (propertiesURL != null) {
                propertiesLocation = propertiesURL.toExternalForm();

                throw new MavenReportException("'propertiesURL' parameter is deprecated: please replace with "
                        + "<propertiesLocation>" + propertiesLocation + "</propertiesLocation>.");
            }
        }

        if ("LICENSE.txt".equals(headerLocation)) {
            File defaultHeaderFile = new File(project.getBasedir(), "LICENSE.txt");
            if (!defaultHeaderFile.equals(headerFile)) {
                headerLocation = headerFile.getPath();
            }
        }

        if (StringUtils.isEmpty(suppressionsLocation)) {
            suppressionsLocation = suppressionsFile;

            if (StringUtils.isNotEmpty(suppressionsFile)) {
                throw new MavenReportException("'suppressionsFile' parameter is deprecated: please replace with "
                        + "<suppressionsLocation>" + suppressionsLocation + "</suppressionsLocation>.");
            }
        }

        if (StringUtils.isEmpty(packageNamesLocation)) {
            packageNamesLocation = packageNamesFile;

            if (StringUtils.isNotEmpty(packageNamesFile)) {
                throw new MavenReportException("'packageNamesFile' parameter is deprecated: please replace with "
                        + "<packageNamesFile>" + suppressionsLocation + "</packageNamesFile>.");
            }
        }
    }

Merge in the deprecated parameters to the new ones, unless the new
parameters have values.

@throws MavenReportException
@deprecated Remove when deprecated params are removed.

Merge in the deprecated parameters to the new ones unless the new parameters have values .


public static String addQueryLimit(String queryString, int queryLimit) {
		int limitIndex = queryString.lastIndexOf("limit");

		if (limitIndex == -1) {
			limitIndex = queryString.lastIndexOf("LIMIT");
		}

		if (limitIndex == -1) {
			return queryString + " LIMIT " + (queryLimit + 1);
		}

		int limitNumber = Integer.parseInt(queryString
				.substring(limitIndex + 5).trim());

		return (limitNumber > queryLimit) ? queryString
				.substring(0, limitIndex) + " LIMIT " + (queryLimit + 1)
				: queryString;
	}

public
static
String
addQueryLimit
(
String
queryString
,
int
queryLimit
)
{
int
limitIndex
=
queryString
.
lastIndexOf
(
"limit"
)
;
if
(
limitIndex
==
1
)
{
limitIndex
=
queryString
.
lastIndexOf
(
"LIMIT"
)
;
}
if
(
limitIndex
==
1
)
{
return
queryString
+
" LIMIT "
+
(
queryLimit
+
1
)
;
}
int
limitNumber
=
Integer
.
parseInt
(
queryString
.
substring
(
limitIndex
+
5
)
.
trim
(
)
)
;
return
(
limitNumber
>
queryLimit
)
queryString
.
substring
(
0
,
limitIndex
)
+
" LIMIT "
+
(
queryLimit
+
1
)
:
queryString
;
}

Limits query results.

@param queryString
Query string.
@return Query string with injected "LIMIT" clause.


public static String[] getFirstLocatorFromLocatorsString(
			String locatorsString) {
		if (locatorsString == null || locatorsString.length() == 0) {
			return new String[2];
		}

		String[] firstLocator = new String[2];

		firstLocator[0] = locatorsString.substring(0,
				locatorsString.indexOf('[')).trim();

		locatorsString = locatorsString
				.substring(locatorsString.indexOf('[') + 1);

		firstLocator[1] = locatorsString.substring(0,
				locatorsString.indexOf(']'));

		return firstLocator;
	}

public static String [ ] getFirstLocatorFromLocatorsString ( String locatorsString ) { if ( locatorsString == null || locatorsString . length ( ) == 0 ) { return new String [ 2 ] ; } String [ ] firstLocator = new String [ 2 ] ; firstLocator [ 0 ] = locatorsString . substring ( 0 , locatorsString . indexOf ( ' ' ) ) . trim ( ) ; locatorsString = locatorsString . substring ( locatorsString . indexOf ( ' ' ) + 1 ) ; firstLocator [ 1 ] = locatorsString . substring ( 0 , locatorsString . indexOf ( ' ' ) ) ; return firstLocator ; }

Returns first locator host and port from locators string.

@param locatorsString
of type String
@return String[0] - locator host String[1] - locator port

Returns first locator host and port from locators string .


public static int getRegionSize(Region<?, ?> region) {
		Function function = new RegionSizeFunction();

		FunctionService.registerFunction(function);

		ResultCollector<?, ?> rc = FunctionService.onRegion(region)
				.withCollector(new RegionSizeResultCollector())
				.execute(function);

		return (Integer) rc.getResult();
	}

public static int getRegionSize ( Region < ? , ? > region ) { Function function = new RegionSizeFunction ( ) ; FunctionService . registerFunction ( function ) ; ResultCollector < ? , ? > rc = FunctionService . onRegion ( region ) . withCollector ( new RegionSizeResultCollector ( ) ) . execute ( function ) ; return ( Integer ) rc . getResult ( ) ; }

Returns approximate number of entries in the region. As the function
counts number of entries on different nodes in parallel, per node values
may be captured on different moments. So the value may never be valid.

@param region
the region.
@returns approximate number of objects in the given region.

Returns approximate number of entries in the region . As the function counts number of entries on different nodes in parallel per node values may be captured on different moments . So the value may never be valid .


public static boolean isGemFireClient() {
		GemFireCacheImpl impl = (GemFireCacheImpl) CacheFactory
				.getAnyInstance();
		return impl != null && impl.isClient();
	}

public static boolean isGemFireClient ( ) { GemFireCacheImpl impl = ( GemFireCacheImpl ) CacheFactory . getAnyInstance ( ) ; return impl != null && impl . isClient ( ) ; }

Checks if the current GemFire is a client instance.

@return true if the cache instance is client.

Checks if the current GemFire is a client instance .


public static <K> void removeAll(Region<K, ?> region, Set<K> keys) {
		if (keys == null) {
			throw new NullPointerException();
		}
		if (keys.isEmpty()) {
			// Nothing to do
			return;
		}
		Function function = new RemoveAllFunction();

		FunctionService.registerFunction(function);

		ResultCollector<?, ?> rc = FunctionService.onRegion(region)
				.withFilter(keys).withArgs(region.getName()).execute(function);

		// Obtain result from the collector to return
		// only after everything is done.
		rc.getResult();
	}

Removes several entries from region in a single hop. On partitioned
region execution is done simultaneously on all partitions.

@param <K>
key type.
@param region
the region to remove entries.
@param keys
the keys of entries to remove.

Removes several entries from region in a single hop . On partitioned region execution is done simultaneously on all partitions .


public static <T> T retryWithExponentialBackoff(Retryable<T> runnable,
			int maxRetries) throws InterruptedException,
			OperationRetryFailedException {
		int retry = 0;

		while (retry < maxRetries) {
			retry++;

			try {
				return runnable.execute();
			} catch (OperationRequireRetryException e) {
				// No-op.
			} catch (InterruptedException e) {
				throw e;
			}

			if (retry > 1) {
				long delay = (long) ((BACKOFF_BASE << retry) * Math.random());

				log.debug("Operation requested retry. Sleep for {} millis",
						delay);

				Thread.sleep(delay);
			}
		}

		throw new OperationRetryFailedException(
				"Maximum number of operation retries reached");
	}

Retries passed operation with random exponential back off delay.

@param <T>
Type of returned value.
@param runnable
the operation.
@param maxRetries
the maximum number of retries.
@return the value returned by operation
@throws OperationRetryFailedException
@throws InterruptedException

Retries passed operation with random exponential back off delay .


protected void generateBufferedImage(TranscoderInput in, int w, int h) throws TranscoderException {
        BufferedImageTranscoder t = new BufferedImageTranscoder();
        if (w != 0 && h != 0) {
            t.setDimensions(w, h);
        }
        t.transcode(in, null);
        bufferedImage = t.getBufferedImage();
        width = bufferedImage.getWidth();
        height = bufferedImage.getHeight();
    }

protected void generateBufferedImage ( TranscoderInput in , int w , int h ) throws TranscoderException { BufferedImageTranscoder t = new BufferedImageTranscoder ( ) ; if ( w != 0 && h != 0 ) { t . setDimensions ( w , h ) ; } t . transcode ( in , null ) ; bufferedImage = t . getBufferedImage ( ) ; width = bufferedImage . getWidth ( ) ; height = bufferedImage . getHeight ( ) ; }


@Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        if (backgroundColour == null) g.drawImage(bufferedImage, x, y, null);
        else g.drawImage(bufferedImage, x, y, backgroundColour, null);
    }

@ Override public void paintIcon ( Component c , Graphics g , int x , int y ) { if ( backgroundColour == null ) g . drawImage ( bufferedImage , x , y , null ) ; else g . drawImage ( bufferedImage , x , y , backgroundColour , null ) ; }

Draw the icon at the specified location.

Draw the icon at the specified location .


private static BufferedReader getReader() {
        if (bufferedReader == null) {
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        }

        return bufferedReader;
    }

private static BufferedReader getReader ( ) { if ( bufferedReader == null ) { bufferedReader = new BufferedReader ( new InputStreamReader ( System . in ) ) ; } return bufferedReader ; }

Method getReader returns the reader of this ConsoleUtils object.

@return the reader (type BufferedReader) of this ConsoleUtils object.

Method getReader returns the reader of this ConsoleUtils object .


public static void waitForEnter(String message) {
        System.out.println(message);

        try {
            getReader().readLine();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

Waits for enter with specified message.

@param message of type String

Waits for enter with specified message .


public void execute(String[] args, boolean debugEnabled, boolean quiet) {
		try {
			this.debugEnabled = debugEnabled;

			debug("CheckReplicationTool#execute(String[]): args = "
				+ Arrays.asList(args));

			parseCommandLineArguments(args);

			System.out.println("Connecting...");

			debug("CheckReplicationTool#execute(String[]): Creating CheckReplicationTool.ProcessorTask with parameters: clustersProperties = "
				+ clustersProperties
				+ ", timeout = "
				+ timeout
				+ ", regionName = " + regionName);

			ProcessorTask task = new ProcessorTask(clustersProperties, timeout,
				regionName, debugEnabled, quiet);

			debug("CheckReplicationTool#execute(String[]): Starting CheckReplicationTool.ProcessorTask");

			Utils.execute(task, timeout + DELTA_TIMEOUT);

			int exitCode = task.getExitCode();

			debug("CheckReplicationTool#execute(String[]): CheckReplicationTool.ProcessorTask finished with exitCode = "
				+ exitCode);

			if (exitCode == 0) {
				Utils.exitWithSuccess();
			}

			Utils.exitWithFailure();
		} catch (Throwable t) {
			debug(
				"CheckReplicationTool#execute(String[]): Throwable caught with message = "
					+ t.getMessage(), t);

			Utils.exitWithFailure("Unexpected throwable", t);
		}
	}

Runs the tool. All the tools run in this way.

Runs the tool . All the tools run in this way .


protected void parseCommandLineArguments(String[] commandLineArguments) {
		Options options = constructGnuOptions();

		if (commandLineArguments.length < 1) {
			printHelp(options);
		}

		CommandLineParser parser = new GnuParser();
		try {
			CommandLine line = parser.parse(options, commandLineArguments);

			if (line.hasOption(HELP_OPTION)) {
				printHelp(options);
			}

			if (line.hasOption(REGION_OPTION)) {
				regionName = line.getOptionValue(REGION_OPTION);
			}

			if (line.hasOption(TIMEOUT_OPTION)) {
				String timeoutString = line.getOptionValue(TIMEOUT_OPTION);
				timeout = Long.parseLong(timeoutString);
			}

			if (line.hasOption(CLUSTER_OPTION)) {
				clustersProperties = line.getOptionProperties(CLUSTER_OPTION);

				if (clustersProperties.keySet().size() < 2) {
					Utils
						.exitWithFailure("At least two clusters should be defined");
				}
			} else {
				Utils.exitWithFailure("No clusters defined");
			}

		} catch (Throwable t) {
			Utils
				.exitWithFailure(
					"Throwable caught during the command-line arguments parsing",
					t);
		}
	}

Parses command-line arguments and sets the local variables

@param commandLineArguments
- the list of command-line arguments

Parses command - line arguments and sets the local variables


protected void printHelp(final Options options) {
		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp("check-replication [options]", options);

		Utils.exitWithFailure();
	}

protected
void
printHelp
(
final
Options
options
)
{
HelpFormatter
formatter
=
new
HelpFormatter
(
)
;
formatter
.
printHelp
(
"check-replication [options]"
,
options
)
;
Utils
.
exitWithFailure
(
)
;
}

Prints help if requested, or in case of any misconfiguration

@param options
- the GNU options

Prints help if requested or in case of any misconfiguration


protected Options constructGnuOptions() {
		final Options gnuOptions = new Options();

		gnuOptions
			.addOption("t", TIMEOUT_OPTION, true,
				"Timeout, ms. Default timeout is " + DEFAULT_TIMEOUT)
			.addOption(
				"r",
				REGION_OPTION,
				true,
				"The name of region for this test. Default name is \""
					+ DEFAULT_REGION_NAME + "\"")
			.addOption("h", HELP_OPTION, false, "Print usage information");

		@SuppressWarnings("static-access")
		Option locatorsOption = OptionBuilder
			.hasArgs()
			.withDescription(
				"Cluster name and list of its locators. "
					+ "There should be at least two clusters. "
					+ "Example: -c cluster1=host1[port1],host2[port2] -c cluster2=host3[port3]")
			.withValueSeparator().withArgName("cluster=locators")
			.withLongOpt(CLUSTER_OPTION).create("c");

		gnuOptions.addOption(locatorsOption);

		return gnuOptions;
	}

Constructs the set of GNU options

@return - the constructed options


private static void aggregateSingleClusterMemberData(List<ResultCollector> taskResults) {
        for (ResultCollector singleCluster : taskResults) {
            List membersResult = (List) singleCluster.getResult();
            for (Object resultFromNode : membersResult) {
                System.out.print(((HashMap) resultFromNode).get("ds") + ":");
            }
            System.out.println();
        }
    }

private static void aggregateSingleClusterMemberData ( List < ResultCollector > taskResults ) { for ( ResultCollector singleCluster : taskResults ) { List membersResult = ( List ) singleCluster . getResult ( ) ; for ( Object resultFromNode : membersResult ) { System . out . print ( ( ( HashMap ) resultFromNode ) . get ( "ds" ) + ":" ) ; } System . out . println ( ) ; } }


public ExpressionBuilder notNull(final Object property, final String name) {

        if (property == null) {
            messageContainer.addErrorMessage("Property '" + name + "' cannot be null");
        }

        return this;
    }

public
ExpressionBuilder
notNull
(
final
Object
property
,
final
String
name
)
{
if
(
property
==
)
{
messageContainer
.
addErrorMessage
(
"Property '"
+
name
+
"' cannot be null"
)
;
}
return
this
;
}

Adds a description for a null property.

@param property The property to check.
@param name     The property name.
@return This object.

Adds a description for a null property .


private static void parseCommandLineArguments(String[] commandLineArguments) {
	Options options = constructGnuOptions();

	CommandLineParser parser = new GnuParser();

	try {
	    CommandLine line = parser.parse(options, commandLineArguments);

	    if (line.hasOption(HELP_OPTION)) {
		printHelp(options);
	    }

	    if (line.hasOption(DEBUG_OPTION)) {
		debugEnabled = true;
	    }

	    if (!debugEnabled && line.hasOption(QUIET_OPTION)) {
		quiet = true;
	    }
	} catch (Throwable t) {
	    printHelp(options);
	}
    }

private static void parseCommandLineArguments ( String [ ] commandLineArguments ) { Options options = constructGnuOptions ( ) ; CommandLineParser parser = new GnuParser ( ) ; try { CommandLine line = parser . parse ( options , commandLineArguments ) ; if ( line . hasOption ( HELP_OPTION ) ) { printHelp ( options ) ; } if ( line . hasOption ( DEBUG_OPTION ) ) { debugEnabled = true ; } if ( ! debugEnabled && line . hasOption ( QUIET_OPTION ) ) { quiet = true ; } } catch ( Throwable t ) { printHelp ( options ) ; } }

Parses command line arguments.

@param commandLineArguments
- The arguments.


private static void printHelp(final Options options) {
	StringBuilder sb = new StringBuilder();

	sb.append("java -jar icegem-cache-utils-<version>.jar [options] <");

	Command[] commands = Command.values();

	for (int i = 0; i < commands.length; i++) {
	    sb.append(commands[i].getName());

	    if (i < (commands.length - 1)) {
		sb.append(" | ");
	    }
	}

	sb.append("> [command_specific_options]");

	HelpFormatter formatter = new HelpFormatter();

	formatter.printHelp(sb.toString(), options);

	Utils.exitWithFailure();
    }

Prints help if requested.

@param options
- The GNU options.


private static Options constructGnuOptions() {
	final Options gnuOptions = new Options();

	gnuOptions.addOption("d", DEBUG_OPTION, false, "Print debug information")
		.addOption("q", QUIET_OPTION, false, "Quiet output. Doesn't work if --" + DEBUG_OPTION + " specified.")
		.addOption("h", HELP_OPTION, false, "Print usage information");

	return gnuOptions;
    }

private
static
Options
constructGnuOptions
(
)
{
final
Options
gnuOptions
=
new
Options
(
)
;
gnuOptions
.
addOption
(
"d"
,
DEBUG_OPTION
,
false
,
"Print debug information"
)
.
addOption
(
"q"
,
QUIET_OPTION
,
false
,
"Quiet output. Doesn't work if --"
+
DEBUG_OPTION
+
" specified."
)
.
addOption
(
"h"
,
HELP_OPTION
,
false
,
"Print usage information"
)
;
return
gnuOptions
;
}

Constructs the set of GNU options.

@return - The constructed options.


private static int findCommandIndex(String[] args) {
	int commandIndex = -1;

	for (int i = 0; i < args.length; i++) {
	    for (Command command : Command.values()) {
		if (command.getName().equals(args[i].trim())) {
		    commandIndex = i;

		    break;
		}
	    }
	}

	return commandIndex;
    }

private static int findCommandIndex ( String [ ] args ) { int commandIndex = - 1 ; for ( int i = 0 ; i < args . length ; i ++ ) { for ( Command command : Command . values ( ) ) { if ( command . getName ( ) . equals ( args [ i ] . trim ( ) ) ) { commandIndex = i ; break ; } } } return commandIndex ; }

Looks for the index of command in the specified array.

@param args
- Arguments.
@return - Index of command, or -1 if command is not found in the array.

Looks for the index of command in the specified array .


private static String[] extractLauncherArgs(String[] args, int commandIndex) {
	String[] launcherArgs = new String[commandIndex];

	System.arraycopy(args, 0, launcherArgs, 0, commandIndex);

	return launcherArgs;
    }

private static String [ ] extractLauncherArgs ( String [ ] args , int commandIndex ) { String [ ] launcherArgs = new String [ commandIndex ] ; System . arraycopy ( args , 0 , launcherArgs , 0 , commandIndex ) ; return launcherArgs ; }

Extracts the launcher arguments from the all arguments array.

@param args
- All arguments.
@param commandIndex
- Index of the command.
@return - Launcher arguments.

Extracts the launcher arguments from the all arguments array .


private static String[] extractCommandArgs(String[] args, int commandIndex) {
	String[] commandArgs = new String[args.length - commandIndex - 1];

	System.arraycopy(args, commandIndex + 1, commandArgs, 0, args.length - commandIndex - 1);

	return commandArgs;
    }

private static String [ ] extractCommandArgs ( String [ ] args , int commandIndex ) { String [ ] commandArgs = new String [ args . length - commandIndex - 1 ] ; System . arraycopy ( args , commandIndex + 1 , commandArgs , 0 , args . length - commandIndex - 1 ) ; return commandArgs ; }

Extracts the command-specific arguments from the all arguments array.

@param args
- All arguments.
@param commandIndex
- Index of the command.
@return - Command-specific arguments.

Extracts the command - specific arguments from the all arguments array .


public static void main(String[] args) {
	try {
	    int commandIndex = findCommandIndex(args);

	    if (commandIndex < 0) {
		printHelp();
	    }

	    String[] launcherArgs = extractLauncherArgs(args, commandIndex);
	    String[] commandArgs = extractCommandArgs(args, commandIndex);

	    parseCommandLineArguments(launcherArgs);

	    debug("Launcher#main(): args = " + Arrays.asList(args));
	    debug("Launcher#main(): launcherArgs = " + Arrays.asList(launcherArgs));
	    debug("Launcher#main(): commandArgs = " + Arrays.asList(commandArgs));

	    String commandName = args[commandIndex];

	    Executable tool = Command.getUtil(commandName);

	    if (tool != null) {
		tool.execute(commandArgs, debugEnabled, quiet);
	    } else {
		debug("Launcher#main(): Command \"" + commandName + "\" not found");

		printHelp();
	    }
	} catch (Throwable t) {
	    debug("Launcher#main(): Throwable caught with message = " + t.getMessage(), t);

	    Utils.exitWithFailure("Unexpected throwable", t);
	}
    }

The entry point of the application.

@param args
- All arguments.
@throws Exception


private static void debug(String message, Throwable t) {
	if (debugEnabled) {
	    System.err.println("0 [Launcher] " + message);

	    if (t != null) {
		t.printStackTrace(System.err);
	    }
	}
    }

private
static
void
debug
(
String
message
,
Throwable
t
)
{
if
(
debugEnabled
)
{
System
.
err
.
println
(
"0 [Launcher] "
+
message
)
;
if
(
t
!=
)
{
t
.
printStackTrace
(
System
.
err
)
;
}
}
}

Prints debug information if debug is enabled.

@param message
- Debug message.
@param t
- Instance of Throwable.

Prints debug information if debug is enabled .


private void start() {
		try {
			timer.schedule(new IsAliveTimerTask(), 0, period);
		} catch (Throwable t) {
			Utils.exitWithFailure("Throwable caught during the startup", t);
		}
	}

private
void
start
(
)
{
try
{
timer
.
schedule
(
new
IsAliveTimerTask
(
)
,
0
,
period
)
;
}
catch
(
Throwable
t
)
{
Utils
.
exitWithFailure
(
"Throwable caught during the startup"
,
t
)
;
}
}


public Set<Region<?, ?>> createRegions(Map<String, String> regionNames) {
	Set<Region<?, ?>> regions = new HashSet<Region<?, ?>>();

	proxyRegionFactory = cache.createClientRegionFactory(ClientRegionShortcut.PROXY);

	for (String regionPath : regionNames.keySet()) {
	    Region region = createRegion(regionPath, regionNames.get(regionPath));

	    regions.add(region);
	}

	return regions;
    }

public Set < Region < ? , ? > > createRegions ( Map < String , String > regionNames ) { Set < Region < ? , ? > > regions = new HashSet < Region < ? , ? > > ( ) ; proxyRegionFactory = cache . createClientRegionFactory ( ClientRegionShortcut . PROXY ) ; for ( String regionPath : regionNames . keySet ( ) ) { Region region = createRegion ( regionPath , regionNames . get ( regionPath ) ) ; regions . add ( region ) ; } return regions ; }

Creates regions structure similar to server region structure.

@param regionNames names of the regions to reconstruct.
@return set of created regions.

Creates regions structure similar to server region structure .


public long process(Region<?, ?> region, ExpirationPolicy policy) {

		long destroyedEntriesNumber = 0;

		try {

			if (region == null) {
				throw new IllegalStateException("The Region cannot be null");
			}

			if (policy == null) {
				throw new IllegalArgumentException(
					"The ExpirationPolicy cannot be null");
			}

			logger
				.info("Running ExpirationController process with parameters region = "
					+ region
					+ ", policy = "
					+ policy
					+ ", packetSize = "
					+ packetSize + ", packetDelay = " + packetDelay);

			DestroyedEntriesCountCollector collector = (DestroyedEntriesCountCollector) FunctionService
				.onRegion(region)
				.withArgs(
					new ExpirationFunctionArguments(packetSize, packetDelay))
				.withCollector(new DestroyedEntriesCountCollector())
				.execute(new ExpirationFunction(policy));

			Object result = collector.getResult();
			if (result instanceof Long) {
				destroyedEntriesNumber = (Long) result;
			}

			logger
				.info("ExpirationController process with parameters region = "
					+ region + ", policy = " + policy + ", packetSize = "
					+ packetSize + ", packetDelay = " + packetDelay
					+ " has destroyed " + destroyedEntriesNumber + " entries");

		} catch (RuntimeException re) {
			logger.error("RuntimeException during processing", re);
			throw re;
		}

		return destroyedEntriesNumber;
	}

Applies the specified policy on the specified region and returns number
of destroyed entries.

@param region
- the region
@param policy
- the expiration policy
@return - the number of destroyed region entries

Applies the specified policy on the specified region and returns number of destroyed entries .


public final void setIndentationToken(final String indentationToken) {

        // Check sanity
        if (indentationToken == null || indentationToken.isEmpty()) {
            throw new IllegalArgumentException("Cannot handle null or empty 'indentationToken' argument.");
        }

        // Assign internal state
        this.indentationToken = indentationToken;
    }

Assigns the indentationToken of this RenderConfiguration.

@param indentationToken the indentationToken of this RenderConfiguration. Cannot be null or empty.

Assigns the indentationToken of this RenderConfiguration .


@Override
    public String getPackage(final File sourceFile) {

        String aLine = getPackage(sourceFile, PACKAGE_STATEMENT);
        if (aLine != null) return aLine;

        // No package statement found.
        // Return default package.
        return "";
    }

@
Override
public
String
getPackage
(
final
File
sourceFile
)
{
String
aLine
=
getPackage
(
sourceFile
,
PACKAGE_STATEMENT
)
;
if
(
aLine
!=
)
return
aLine
;
// No package statement found.
// Return default package.
return
""
;
}

Retrieves the package definition from the supplied sourceFile.

@param sourceFile The sourceFile from which the package definition should be extracted.
@return The package of the sourceFile.

Retrieves the package definition from the supplied sourceFile .


public static boolean start(final RootDoc root) {

        // Perform some reflective investigation of the RootDoc

        final boolean toReturn = Standard.start(root);
        eventSequence.add("start (root): " + toReturn);

        // We should emit the eventSequence here.
        for(int i = 0; i < eventSequence.size(); i++) {
            System.out.println(" event [" + i + " / " + eventSequence.size() + "]: " + eventSequence.get(i));
        }

        // All Done.
        return toReturn;
    }

Generate documentation here.
This method is required for all doclets.

@return true on success.

Generate documentation here . This method is required for all doclets .


private Set<Integer> extractPortsSet(SystemMember member)
		throws AdminException {
		Set<Integer> portsSet = new HashSet<Integer>();
		SystemMemberCache cache = member.getCache();
		if (cache != null) {
			SystemMemberCacheServer[] cacheServers = cache.getCacheServers();
			if (cacheServers != null) {
				for (SystemMemberCacheServer cacheServer : cacheServers) {
					portsSet.add(cacheServer.getPort());
				}
			}
		}

		return portsSet;
	}

private Set < Integer > extractPortsSet ( SystemMember member ) throws AdminException { Set < Integer > portsSet = new HashSet < Integer > ( ) ; SystemMemberCache cache = member . getCache ( ) ; if ( cache != null ) { SystemMemberCacheServer [ ] cacheServers = cache . getCacheServers ( ) ; if ( cacheServers != null ) { for ( SystemMemberCacheServer cacheServer : cacheServers ) { portsSet . add ( cacheServer . getPort ( ) ) ; } } } return portsSet ; }

Extracts port from the SystemMember object.

@param member
- the specified SystemMember
@return - port if its found, -1 otherwise
@throws AdminException

Extracts port from the SystemMember object .


private Pool findOrCreatePool(String host, int port) {
		String poolName = Utils.toKey(host, port);
		Pool pool = PoolManager.find(poolName);
		if (pool == null) {
			poolFactory.reset();
			poolFactory.addServer(host, port);
			pool = poolFactory.create(poolName);
		}

		return pool;
	}

private Pool findOrCreatePool ( String host , int port ) { String poolName = Utils . toKey ( host , port ) ; Pool pool = PoolManager . find ( poolName ) ; if ( pool == null ) { poolFactory . reset ( ) ; poolFactory . addServer ( host , port ) ; pool = poolFactory . create ( poolName ) ; } return pool ; }

Looks for the existing pool with name poolFactory. If there is no such
pool, creates new one.

@param host
- the concrete server's host
@param port
- the concrete server's port
@return found or new pool for the specified parameters

Looks for the existing pool with name poolFactory . If there is no such pool creates new one .


public static String getName(String eventSrcName) {
        if (eventSrcName == null) {
            return null;
        }

        if (eventSrcName.endsWith("Check")) {
            eventSrcName = eventSrcName.substring(0, eventSrcName.length() - 5);
        }

        return eventSrcName.substring(eventSrcName.lastIndexOf('.') + 1);
    }

public static String getName ( String eventSrcName ) { if ( eventSrcName == null ) { return null ; } if ( eventSrcName . endsWith ( "Check" ) ) { eventSrcName = eventSrcName . substring ( 0 , eventSrcName . length ( ) - 5 ) ; } return eventSrcName . substring ( eventSrcName . lastIndexOf ( ' ' ) + 1 ) ; }

Get the rule name from an audit event source name.

@param eventSrcName the audit event source name
@return the rule name, which is the class name without package and removed eventual "Check" suffix

Get the rule name from an audit event source name .


public static String getCategory(String eventSrcName) {
        if (eventSrcName == null) {
            return null;
        }

        int end = eventSrcName.lastIndexOf('.');
        eventSrcName = eventSrcName.substring(0, end);

        if (CHECKSTYLE_PACKAGE.equals(eventSrcName)) {
            return "misc";
        } else if (!eventSrcName.startsWith(CHECKSTYLE_PACKAGE)) {
            return "extension";
        }

        return eventSrcName.substring(eventSrcName.lastIndexOf('.') + 1);
    }

public static String getCategory ( String eventSrcName ) { if ( eventSrcName == null ) { return null ; } int end = eventSrcName . lastIndexOf ( ' ' ) ; eventSrcName = eventSrcName . substring ( 0 , end ) ; if ( CHECKSTYLE_PACKAGE . equals ( eventSrcName ) ) { return "misc" ; } else if ( ! eventSrcName . startsWith ( CHECKSTYLE_PACKAGE ) ) { return "extension" ; } return eventSrcName . substring ( eventSrcName . lastIndexOf ( ' ' ) + 1 ) ; }

Get the rule category from an audit event source name.

@param eventSrcName the audit event source name
@return the rule category, which is the last package name or "misc" or "extension"

Get the rule category from an audit event source name .


public static void enterFrame(String className) {
        int counter = local.get().incrementAndGet();
        classNames.get().add(className);
        if (counter == MAX_STACK_DEPTH) {
            throw new RuntimeException(STACK_OVERFLOW_MSG + getClassNames());
        }
    }

public static void enterFrame ( String className ) { int counter = local . get ( ) . incrementAndGet ( ) ; classNames . get ( ) . add ( className ) ; if ( counter == MAX_STACK_DEPTH ) { throw new RuntimeException ( STACK_OVERFLOW_MSG + getClassNames ( ) ) ; } }

Increment the counter.
@param className name of class to enter.


public static void exitFrame(String className) {
        int counter = local.get().decrementAndGet();
        if (counter < 0) {
            String errorMessage = "Method frame counter is less then 0. Some programming error: count(exitFrame) > count(enterFrame)."
                    + getClassNames();
            clearCounter();
            throw new RuntimeException(errorMessage);
        }
        String frameToExit = classNames.get().remove(classNames.get().size() - 1);
        if (!className.equals(frameToExit)) {
            throw new RuntimeException("Method frame counter try to exit from the class '" + className
                    + "' but must exit from the class '" + frameToExit + "' first." + getClassNames());
        }
    }

Decrement the counter and remove class name from the list.
@param className name of class to exit from.

Decrement the counter and remove class name from the list .


private static String getClassNames() {
        StringBuilder result = new StringBuilder("\nMethod frame counter enter to the following classes:\n");
        for (String className : classNames.get()) {
            result.append(className).append("\n");
        }
        return result.toString();
    }

Creates string with all classes that have been entered by method frame counter.
@return String

Creates string with all classes that have been entered by method frame counter .


public final void setPackageExtractors(final String packageExtractorImplementations)
            throws IllegalArgumentException {

        // Check sanity
        if(packageExtractorImplementations == null) {
            throw new NullPointerException("Cannot handle empty packageExtractorImplementations argument.");
        }

        // Instantiate the PackageExtractor instances.
        List<PackageExtractor> extractors = new ArrayList<PackageExtractor>();
        for (String current : splice(packageExtractorImplementations)) {
            try {

                // Load the current PackageExtractor implementation class
                final Class<?> aClass = getClass().getClassLoader().loadClass(current);

                // The PackageExtractor implementation must have a default constructor.
                // Fire, and handle any exceptions.
                extractors.add((PackageExtractor) aClass.newInstance());
            } catch (Exception e) {
                throw new IllegalArgumentException("Could not instantiate PackageExtractor from class ["
                        + current + "]. Validate that implementation has a default constructor, and implements the"
                        + PackageExtractor.class.getSimpleName() + " interface.");
            }
        }

        // Assign if non-null.
        if (extractors.size() > 0) {
            this.packageExtractors = extractors;
        }
    }

Splices the supplied packageExtractorImplementations argument, which is assumed to be a comma-separated
string holding fully qualified class names of the PackageExtractor implementations which should be used
by this CorrectPackagingRule.

@param packageExtractorImplementations a comma-separated string holding fully qualified class names of the
PackageExtractor implementations. Each such class must have a default
(i.e. no-argument) constructor.
@throws IllegalArgumentException if the supplied packageExtractorImplementations argument could not yield an
instantiated PackageExtractor instance.

Splices the supplied packageExtractorImplementations argument which is assumed to be a comma - separated string holding fully qualified class names of the PackageExtractor implementations which should be used by this CorrectPackagingRule .


private void addPackages(final File fileOrDirectory,
                             final SortedMap<String, SortedSet<String>> package2FileNamesMap) {

        for (PackageExtractor current : packageExtractors) {

            final FileFilter sourceFileDefinitionFilter = current.getSourceFileFilter();

            if (fileOrDirectory.isFile() && sourceFileDefinitionFilter.accept(fileOrDirectory)) {

                // Single source file to add.
                final String thePackage = current.getPackage(fileOrDirectory);

                SortedSet<String> sourceFileNames = package2FileNamesMap.get(thePackage);
                if (sourceFileNames == null) {
                    sourceFileNames = new TreeSet<String>();
                    package2FileNamesMap.put(thePackage, sourceFileNames);
                }

                // Done.
                sourceFileNames.add(fileOrDirectory.getName());

            } else if (fileOrDirectory.isDirectory()) {

                // Add the immediate source files
                for (File currentChild : fileOrDirectory.listFiles(sourceFileDefinitionFilter)) {
                    addPackages(currentChild, package2FileNamesMap);
                }

                // Recurse into subdirectories
                for (File currentSubdirectory : fileOrDirectory.listFiles(DIRECTORY_FILTER)) {
                    addPackages(currentSubdirectory, package2FileNamesMap);
                }
            }
        }
    }

private
void
addPackages
(
final
File
fileOrDirectory
,
final
SortedMap
<
String
,
SortedSet
<
String
>
>
package2FileNamesMap
)
{
for
(
PackageExtractor
current
:
packageExtractors
)
{
final
FileFilter
sourceFileDefinitionFilter
=
current
.
getSourceFileFilter
(
)
;
if
(
fileOrDirectory
.
isFile
(
)
&&
sourceFileDefinitionFilter
.
accept
(
fileOrDirectory
)
)
{
// Single source file to add.
final
String
thePackage
=
current
.
getPackage
(
fileOrDirectory
)
;
SortedSet
<
String
>
sourceFileNames
=
package2FileNamesMap
.
get
(
thePackage
)
;
if
(
sourceFileNames
==
)
{
sourceFileNames
=
new
TreeSet
<
String
>
(
)
;
package2FileNamesMap
.
put
(
thePackage
,
sourceFileNames
)
;
}
// Done.
sourceFileNames
.
add
(
fileOrDirectory
.
getName
(
)
)
;
}
else
if
(
fileOrDirectory
.
isDirectory
(
)
)
{
// Add the immediate source files
for
(
File
currentChild
:
fileOrDirectory
.
listFiles
(
sourceFileDefinitionFilter
)
)
{
addPackages
(
currentChild
,
package2FileNamesMap
)
;
}
// Recurse into subdirectories
for
(
File
currentSubdirectory
:
fileOrDirectory
.
listFiles
(
DIRECTORY_FILTER
)
)
{
addPackages
(
currentSubdirectory
,
package2FileNamesMap
)
;
}
}
}
}

Adds all source file found by recursive search under sourceRoot to the
toPopulate List, using a width-first approach.

@param fileOrDirectory      The file or directory to search for packages and [if a directory] recursively
search for further source files.
@param package2FileNamesMap A Map relating package names extracted by the PackageExtractors.

Adds all source file found by recursive search under sourceRoot to the toPopulate List using a width - first approach .


@PrePersist
    @PreUpdate
    private void updateImageData() throws CustomConstraintViolationException {
        thumbnail = createImage(true);
        imageFile.validate();
        if (imageData != null) {
            imageContentHash = HashUtilities.generateSHA256(imageData).toCharArray();
        }
    }

@ PrePersist @ PreUpdate private void updateImageData ( ) throws CustomConstraintViolationException { thumbnail = createImage ( true ) ; imageFile . validate ( ) ; if ( imageData != null ) { imageContentHash = HashUtilities . generateSHA256 ( imageData ) . toCharArray ( ) ; } }

Create the thumbnails, and make sure the parent imagefile is valid.

@throws CustomConstraintViolationException

Create the thumbnails and make sure the parent imagefile is valid .


public void setUiOriginalFileName(final String uiOriginalFileName) {
        this.uiOriginalFileName = uiOriginalFileName;
        if (this.uiOriginalFileName != null && !this.uiOriginalFileName.isEmpty()) originalFileName = this.uiOriginalFileName;
    }

public void setUiOriginalFileName ( final String uiOriginalFileName ) { this . uiOriginalFileName = uiOriginalFileName ; if ( this . uiOriginalFileName != null && ! this . uiOriginalFileName . isEmpty ( ) ) originalFileName = this . uiOriginalFileName ; }

The UI will attempt to assign an empty value if the file upload box does not have a file selected. This method is used to
ignore any empty values, while passing through any legitimate file uploads. This means that the absence of a file in the
upload box does not indicate that no file should be assigned to the entity.

@param uiOriginalFileName The image file name uploaded through the UI

The UI will attempt to assign an empty value if the file upload box does not have a file selected . This method is used to ignore any empty values while passing through any legitimate file uploads . This means that the absence of a file in the upload box does not indicate that no file should be assigned to the entity .


private static int extractLimit(String queryString) {
	int limitIndex = queryString.lastIndexOf("limit");

	if (limitIndex == -1) {
	    limitIndex = queryString.lastIndexOf("LIMIT");
	}

	if (limitIndex == -1) {
	    return limitIndex;
	}

	String limitValue = queryString.substring(limitIndex + 5);

	return Integer.parseInt(limitValue.trim());
    }

private static int extractLimit ( String queryString ) { int limitIndex = queryString . lastIndexOf ( "limit" ) ; if ( limitIndex == - 1 ) { limitIndex = queryString . lastIndexOf ( "LIMIT" ) ; } if ( limitIndex == - 1 ) { return limitIndex ; } String limitValue = queryString . substring ( limitIndex + 5 ) ; return Integer . parseInt ( limitValue . trim ( ) ) ; }

Extracts limit value from query string.

@param queryString OQL query string.
@return Value of 'limit' clause.

Extracts limit value from query string .


@SuppressWarnings({ "unchecked" })
    private static SelectResults<Object> formatSelectResults(List<List<Object>> queryResults, int limit) {
	List<Object> list = new ArrayList<Object>();

	ObjectType baseElementType = null;

	for (List<Object> queryResult : queryResults) {
	    ObjectType elementType = (ObjectType) queryResult.remove(queryResult.size() - 1);

	    if (baseElementType == null) {
		baseElementType = elementType;
	    } else if (!baseElementType.equals(elementType)) {
		throw new IllegalStateException("Collection types for query result are different.");
	    }

	    list.addAll(queryResult);

	    if (limit != -1 && list.size() >= limit) {
		break;
	    }
	}

	return limit == -1 ? new ResultsCollectionWrapper(baseElementType, list) : new ResultsCollectionWrapper(
		baseElementType, list, limit);
    }

Collects and formats query results into SelectResults. Limits query results based on limit value.

@param queryResults Query results from several nodes.
@param limit Query results limit.
@return Aggregated query results represented by instance of {@link SelectResults}.

Collects and formats query results into SelectResults . Limits query results based on limit value .


private static void checkAllowedInRealTime0(Object obj, int depth) throws InvalidClassException {
        if (depth >= MethodFrameCounter.MAX_STACK_DEPTH) { //todo: correct >? or >=?
            throw new RuntimeException();
        }
        Class<?> clazz = obj.getClass();

        if (clazz.getName().startsWith("java.") || clazz.getName().startsWith("javax.")) {
            checkAllowedInCompileTimeJdkType(clazz);
        } else {
            checkAllowedInCompileTimeCustomType(clazz);
        }

        // array
        if (clazz.isArray()) {
            final int length = Array.getLength(obj);
            for (int k = 0; k < length; k++) {
                Object elem = Array.get(obj, k);
                checkAllowedInRealTime0(elem, depth + 1);
            }
        }
        // Collection
        if (Collection.class.isAssignableFrom(clazz)) {
            for (Object elem : ((Collection) obj)) {
                checkAllowedInRealTime0(elem, depth + 1);
            }
        }
        // Map
        if (Map.class.isAssignableFrom(clazz)) {
            for (Map.Entry<Object, Object> elem : ((Map<Object, Object>) obj).entrySet()) {
                checkAllowedInRealTime0(elem.getKey(), depth + 1);
                checkAllowedInRealTime0(elem.getValue(), depth + 1);
            }
        }
    }

private
static
void
checkAllowedInRealTime0
(
Object
obj
,
int
depth
)
throws
InvalidClassException
{
if
(
depth
>=
MethodFrameCounter
.
MAX_STACK_DEPTH
)
{
//todo: correct >? or >=?
throw
new
RuntimeException
(
)
;
}
Class
<
>
clazz
=
obj
.
getClass
(
)
;
if
(
clazz
.
getName
(
)
.
startsWith
(
"java."
)
||
clazz
.
getName
(
)
.
startsWith
(
"javax."
)
)
{
checkAllowedInCompileTimeJdkType
(
clazz
)
;
}
else
{
checkAllowedInCompileTimeCustomType
(
clazz
)
;
}
// array
if
(
clazz
.
isArray
(
)
)
{
final
int
length
=
Array
.
getLength
(
obj
)
;
for
(
int
k
=
0
;
k
<
length
;
k
++
)
{
Object
elem
=
Array
.
get
(
obj
,
k
)
;
checkAllowedInRealTime0
(
elem
,
depth
+
1
)
;
}
}
// Collection
if
(
Collection
.
class
.
isAssignableFrom
(
clazz
)
)
{
for
(
Object
elem
:
(
(
Collection
)
obj
)
)
{
checkAllowedInRealTime0
(
elem
,
depth
+
1
)
;
}
}
// Map
if
(
Map
.
class
.
isAssignableFrom
(
clazz
)
)
{
for
(
Map
.
Entry
<
Object
,
Object
>
elem
:
(
(
Map
<
Object
,
Object
>
)
obj
)
.
entrySet
(
)
)
{
checkAllowedInRealTime0
(
elem
.
getKey
(
)
,
depth
+
1
)
;
checkAllowedInRealTime0
(
elem
.
getValue
(
)
,
depth
+
1
)
;
}
}
}

With stack counter

@param obj
@param depth of
@throws InvalidClassException


public Process runWithConfirmation(String id, Class<?> klass,
			String[] javaArguments, String[] processArguments)
			throws IOException, InterruptedException {
		Process process = startProcess(id, klass, javaArguments, processArguments,
				true);

		waitConfirmation(klass.getSimpleName(), process);

		new StreamRedirector(process.getInputStream(), klass.getSimpleName()
				+ PROCESS_STDOUT_STREAM_PREFIX,
				redirectProcessInputStreamToParentProcessStdOut).start();

		return process;
	}

Runs process based on a specified class in a separate VM using array of
arguments. To confirm that process completes startup it should write a
startup completed string into it's standard output.

@param id
the process identifier.
@param klass
of type Class.
@param javaArguments
arguments for java.
@param processArguments
arguments for process.

@return Process the started process.
@throws IOException
when
@throws InterruptedException
when

Runs process based on a specified class in a separate VM using array of arguments . To confirm that process completes startup it should write a startup completed string into it s standard output .


public Process runWithStartupDelay(Class<?> klass, String[] javaArguments,
			String[] processArguments) throws IOException,
			InterruptedException, TimeoutException {
		return runWithStartupDelay(klass, javaArguments, processArguments,
				DEFAULT_PROCESS_STARTUP_SHUTDOWN_TIME);
	}

public Process runWithStartupDelay ( Class < ? > klass , String [ ] javaArguments , String [ ] processArguments ) throws IOException , InterruptedException , TimeoutException { return runWithStartupDelay ( klass , javaArguments , processArguments , DEFAULT_PROCESS_STARTUP_SHUTDOWN_TIME ) ; }

Runs process with arguments based on a specified class in a separate VM.
Waits DEFAULT_PROCESS_STARTUP_TIME before returns the created process to
a caller.

@param klass
of type Class
@param javaArguments
arguments for java
@param processArguments
arguments for process
@return Process
@throws IOException
when
@throws InterruptedException
when
@throws TimeoutException
when

Runs process with arguments based on a specified class in a separate VM . Waits DEFAULT_PROCESS_STARTUP_TIME before returns the created process to a caller .


public Process runWithStartupDelay(Class<?> klass, String[] javaArguments,
			String[] processArguments, long processStartupTime)
			throws IOException, InterruptedException, TimeoutException {
		Process process = runWithConfirmation("", klass, javaArguments,
				processArguments);

		if (processStartupTime > 0) {
			Thread.sleep(processStartupTime);
		}

		return process;
	}

public Process runWithStartupDelay ( Class < ? > klass , String [ ] javaArguments , String [ ] processArguments , long processStartupTime ) throws IOException , InterruptedException , TimeoutException { Process process = runWithConfirmation ( "" , klass , javaArguments , processArguments ) ; if ( processStartupTime > 0 ) { Thread . sleep ( processStartupTime ) ; } return process ; }

Runs process with arguments based on a specified class in a separate VM.
Waits processStartupTime before returns the created process to a caller.

@param klass
of type Class
@param processStartupTime
time in milliseconds that launcher spend on waiting process
after it's start.
@param javaArguments
arguments for java
@param processArguments
arguments for process
@return Process
@throws IOException
when
@throws InterruptedException
when
@throws TimeoutException
if process startup is not completed in time.

Runs process with arguments based on a specified class in a separate VM . Waits processStartupTime before returns the created process to a caller .


public void stopBySendingNewLineIntoProcess(Process process)
			throws IOException, InterruptedException {
		if (process != null) {
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
					process.getOutputStream()));

			writer.newLine();

			writer.flush();

			process.waitFor();
		}
	}

public void stopBySendingNewLineIntoProcess ( Process process ) throws IOException , InterruptedException { if ( process != null ) { BufferedWriter writer = new BufferedWriter ( new OutputStreamWriter ( process . getOutputStream ( ) ) ) ; writer . newLine ( ) ; writer . flush ( ) ; process . waitFor ( ) ; } }

Stops process by sending new line to it's output stream.

The process can be stopped by calling destroy() method.

@param process
of type Process
@throws IOException
when
@throws InterruptedException

Stops process by sending new line to it s output stream .


private Process startProcess(String id, Class<?> klass, String[] javaArguments,
			String[] processArguments, boolean withConfirmation)
			throws IOException, InterruptedException {
		List<String> arguments = createCommandLineForProcess(klass,
				javaArguments, processArguments);

		Process process = new ProcessBuilder(arguments).start();

		redirectProcessStreams(id, klass, process, !withConfirmation);

		return process;
	}

private Process startProcess ( String id , Class < ? > klass , String [ ] javaArguments , String [ ] processArguments , boolean withConfirmation ) throws IOException , InterruptedException { List < String > arguments = createCommandLineForProcess ( klass , javaArguments , processArguments ) ; Process process = new ProcessBuilder ( arguments ) . start ( ) ; redirectProcessStreams ( id , klass , process , ! withConfirmation ) ; return process ; }

Starts process based on specified class using command line arguments.
This process inherits a classpath from parent VM that starts it.

@param klass
of type Class
@param javaArguments
of type String[]
@param processArguments
of type String[]
@param withConfirmation
of type boolean
@return Process
@throws IOException
when
@throws InterruptedException
when

Starts process based on specified class using command line arguments . This process inherits a classpath from parent VM that starts it .


private void redirectProcessStreams(String id, Class<?> klass, Process process,
			boolean redirectProcessStdOut) {

		String errorStreamType = (printType ? klass.getSimpleName() + id
				+ PROCESS_ERROR_STREAM_PREFIX : "");

		new StreamRedirector(process.getErrorStream(), errorStreamType,
				redirectProcessErrorStreamToParentProcessStdOut, System.err)
				.start();

		if (redirectProcessStdOut) {
			String outputStreamType = (printType ? klass.getSimpleName() + id
					+ PROCESS_STDOUT_STREAM_PREFIX : "");

			new StreamRedirector(process.getInputStream(), outputStreamType,
					redirectProcessInputStreamToParentProcessStdOut, System.out)
					.start();
		}
	}

Redirects process standard output and error streams into parent process
standard output.

@param klass
of type Class
@param process
of type Process
@param redirectProcessStdOut
of type boolean

Redirects process standard output and error streams into parent process standard output .


private void waitConfirmation(String className, Process process)
			throws IOException, InterruptedException {
		System.out
				.println("Waiting startup complete confirmation for a process ("
						+ className + ")...");

		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(process.getInputStream()));

		String line;

		while ((line = bufferedReader.readLine()) != null) {
			if (line.equals(PROCESS_STARTUP_COMPLETED)) {
				System.out.println("The process (" + className
						+ ") has been started successfully");

				return;
			} else if (redirectProcessInputStreamToParentProcessStdOut) {
				System.out.println(className + PROCESS_STDOUT_STREAM_PREFIX
						+ line);
			}
		}

		throw new InterruptedException(
				"Process ("
						+ className
						+ ") "
						+ "has been already finished without startup complete confirmation");
	}

Waits startup complete confirmation from process.

@param className
of type String
@param process
of type Process
@throws IOException
when
@throws InterruptedException
when

Waits startup complete confirmation from process .


public void generate( String outputFilename, String template, Context context )
        throws VelocityException, MojoExecutionException, IOException
    {
        Writer writer = null;

        try
        {
            File f = new File( outputFilename );

            if ( !f.getParentFile().exists() )
            {
                f.getParentFile().mkdirs();
            }

            writer = new FileWriter( f );

            getVelocity().getEngine().mergeTemplate( templateDirectory + "/" + template, context, writer );
        }
        catch ( ResourceNotFoundException e )
        {
            throw new ResourceNotFoundException( "Template not found: " + templateDirectory + "/" + template, e );
        }
        catch ( VelocityException | IOException e )
        {
            throw e; // to get past generic catch for Exception.
        }
        catch ( Exception e )
        {
            throw new MojoExecutionException( e.getMessage(), e );
        }
        finally
        {
            if ( writer != null )
            {
                writer.flush();
                writer.close();

                getLog().debug( "File " + outputFilename + " created..." );
            }
        }
    }

Using a specified Velocity Template and provided context, create the outputFilename.

@param outputFilename the file to be generated.
@param template       the velocity template to use.
@param context        the velocity context map.
@throws VelocityException if the template was not found or any other Velocity exception.
@throws MojoExecutionException
@throws IOException

Using a specified Velocity Template and provided context create the outputFilename .


public int process() throws IOException, InterruptedException {
		debug("ReplicationProcessor#process(): Processing start");

		Properties gemfireProperties = PropertiesHelper.filterProperties(
			System.getProperties(), "gemfire.");
		String[] vmOptions = PropertiesHelper
			.propertiesToVMOptions(gemfireProperties);

		debug("ReplicationProcessor#process(): vmOptions = "
			+ Arrays.asList(vmOptions));

		List<Process> processesList = new ArrayList<Process>();
		for (Object keyObject : clustersProperties.keySet()) {
			String cluster = (String) keyObject;
			String clustersPropertiesString = PropertiesHelper
				.propertiesToString(clustersProperties);

			debug("ReplicationProcessor#process(): Starting GuestNode with parameters: cluster = "
				+ cluster
				+ ", clustersPropertiesString = "
				+ clustersPropertiesString
				+ ", timeout = "
				+ timeout
				+ ", regionName = " + regionName);

			Process process = javaProcessLauncher.runWithoutConfirmation(
				"",
				GuestNode.class,
				vmOptions, new String[] { cluster, clustersPropertiesString,
					String.valueOf(timeout), regionName,
					String.valueOf(debugEnabled), String.valueOf(quiet),
					String.valueOf(processingStartedAt) });

			debug("ReplicationProcessor#process(): Adding GuestNode to processList");

			processesList.add(process);
		}

		debug("ReplicationProcessor#process(): Waiting for processes finish");
		int mainExitCode = 0;
		int processNumber = 0;
		for (Process process : processesList) {
			debug("ReplicationProcessor#process(): Waiting for process #"
				+ processNumber);

			int exitCode = process.waitFor();

			if (exitCode != 0) {
				mainExitCode = 1;
			}
			debug("ReplicationProcessor#process(): Process #" + processNumber
				+ " finished with exitCode = " + exitCode);

			processNumber++;
		}

		debug("ReplicationProcessor#process(): Processing finished with mainExitCode = "
			+ mainExitCode);

		return mainExitCode;
	}

Creates, configures and runs the guest nodes and collects information
form them

@return - 0 in case of success, 1 otherwise

@throws IOException
@throws InterruptedException

Creates configures and runs the guest nodes and collects information form them


public static boolean isA(Class clazz, ParameterizedType pType) {
        return clazz.isAssignableFrom((Class) pType.getRawType());
    }

public static boolean isA ( Class clazz , ParameterizedType pType ) { return clazz . isAssignableFrom ( ( Class ) pType . getRawType ( ) ) ; }


public static boolean isCompatible(Method method, Method intfMethod) {
        if (method == intfMethod)
            return true;

        if (!method.getName().equals(intfMethod.getName()))
            return false;
        if (method.getParameterTypes().length != intfMethod.getParameterTypes().length)
            return false;

        for (int i = 0; i < method.getParameterTypes().length; i++) {
            Class rootParam = method.getParameterTypes()[i];
            Class intfParam = intfMethod.getParameterTypes()[i];
            if (!intfParam.isAssignableFrom(rootParam))
                return false;
        }
        return true;
    }

public static boolean isCompatible ( Method method , Method intfMethod ) { if ( method == intfMethod ) return true ; if ( ! method . getName ( ) . equals ( intfMethod . getName ( ) ) ) return false ; if ( method . getParameterTypes ( ) . length != intfMethod . getParameterTypes ( ) . length ) return false ; for ( int i = 0 ; i < method . getParameterTypes ( ) . length ; i ++ ) { Class rootParam = method . getParameterTypes ( ) [ i ] ; Class intfParam = intfMethod . getParameterTypes ( ) [ i ] ; if ( ! intfParam . isAssignableFrom ( rootParam ) ) return false ; } return true ; }

See if the two methods are compatible, that is they have the same
relative signature

@param method
@param intfMethod
@return

See if the two methods are compatible that is they have the same relative signature


public static Method getImplementingMethod(Class clazz, Method intfMethod) {
        Class<?> declaringClass = intfMethod.getDeclaringClass();
        if (declaringClass.equals(clazz))
            return intfMethod;

        Class[] paramTypes = intfMethod.getParameterTypes();

        if (declaringClass.getTypeParameters().length > 0 && paramTypes.length > 0) {
            Type[] intfTypes = findParameterizedTypes(clazz, declaringClass);
            Map<String, Type> typeVarMap = new HashMap<String, Type>();
            TypeVariable<? extends Class<?>>[] vars = declaringClass.getTypeParameters();
            for (int i = 0; i < vars.length; i++) {
                if (intfTypes != null && i < intfTypes.length) {
                    typeVarMap.put(vars[i].getName(), intfTypes[i]);
                } else {
                    // Interface type parameters may not have been filled out
                    typeVarMap.put(vars[i].getName(), vars[i].getGenericDeclaration());
                }
            }
            Type[] paramGenericTypes = intfMethod.getGenericParameterTypes();
            paramTypes = new Class[paramTypes.length];

            for (int i = 0; i < paramTypes.length; i++) {
                if (paramGenericTypes[i] instanceof TypeVariable) {
                    TypeVariable tv = (TypeVariable) paramGenericTypes[i];
                    Type t = typeVarMap.get(tv.getName());
                    if (t == null) {
                        throw new RuntimeException("Unable to resolve type variable");
                    }
                    paramTypes[i] = getRawType(t);
                } else {
                    paramTypes[i] = getRawType(paramGenericTypes[i]);
                }
            }

        }

        try {
            return clazz.getMethod(intfMethod.getName(), paramTypes);
        } catch (NoSuchMethodException e) {
        }

        try {
            Method tmp = clazz.getMethod(intfMethod.getName(), intfMethod.getParameterTypes());
            return tmp;
        } catch (NoSuchMethodException e) {

        }
        return intfMethod;
    }

Given a method and a root class, find the actual method declared in the
root that implements the method.

@param clazz
@param intfMethod
@return

Given a method and a root class find the actual method declared in the root that implements the method .


public static Class<?> getTypeArgument(Type genericType) {
        if (!(genericType instanceof ParameterizedType))
            return null;
        ParameterizedType parameterizedType = (ParameterizedType) genericType;
        Class<?> typeArg = (Class<?>) parameterizedType.getActualTypeArguments()[0];
        return typeArg;
    }

public static Class < ? > getTypeArgument ( Type genericType ) { if ( ! ( genericType instanceof ParameterizedType ) ) return null ; ParameterizedType parameterizedType = ( ParameterizedType ) genericType ; Class < ? > typeArg = ( Class < ? > ) parameterizedType . getActualTypeArguments ( ) [ 0 ] ; return typeArg ; }

Returns the type argument from a parameterized type

@param genericType
@return null if there is no type parameter


public static Type resolveTypeVariable(Class<?> root, TypeVariable<?> typeVariable) {
        if (typeVariable.getGenericDeclaration() instanceof Class<?>) {
            Class<?> classDeclaringTypeVariable = (Class<?>) typeVariable.getGenericDeclaration();
            Type[] types = findParameterizedTypes(root, classDeclaringTypeVariable);
            if (types == null)
                return null;
            for (int i = 0; i < types.length; i++) {
                TypeVariable<?> tv = classDeclaringTypeVariable.getTypeParameters()[i];
                if (tv.equals(typeVariable)) {
                    return types[i];
                }
            }
        }
        return null;
    }

public static Type resolveTypeVariable ( Class < ? > root , TypeVariable < ? > typeVariable ) { if ( typeVariable . getGenericDeclaration ( ) instanceof Class < ? > ) { Class < ? > classDeclaringTypeVariable = ( Class < ? > ) typeVariable . getGenericDeclaration ( ) ; Type [ ] types = findParameterizedTypes ( root , classDeclaringTypeVariable ) ; if ( types == null ) return null ; for ( int i = 0 ; i < types . length ; i ++ ) { TypeVariable < ? > tv = classDeclaringTypeVariable . getTypeParameters ( ) [ i ] ; if ( tv . equals ( typeVariable ) ) { return types [ i ] ; } } } return null ; }

Finds an actual value of a type variable. The method looks in a class
hierarchy for a class defining the variable and returns the value if
present.

@param root
@param typeVariable
@return actual type of the type variable

Finds an actual value of a type variable . The method looks in a class hierarchy for a class defining the variable and returns the value if present .


public static Type[] getActualTypeArgumentsOfAnInterface(Class<?> classToSearch, Class<?> interfaceToFind) {
        Type[] types = findParameterizedTypes(classToSearch, interfaceToFind);
        if (types == null)
            throw new RuntimeException("Unable to find type arguments of " + interfaceToFind);
        return types;
    }

public
static
Type
[
]
getActualTypeArgumentsOfAnInterface
(
Class
<
>
classToSearch
,
Class
<
>
interfaceToFind
)
{
Type
[
]
types
=
findParameterizedTypes
(
classToSearch
,
interfaceToFind
)
;
if
(
types
==
)
throw
new
RuntimeException
(
"Unable to find type arguments of "
+
interfaceToFind
)
;
return
types
;
}

Given a class and an interfaces, go through the class hierarchy to find
the interface and return its type arguments.

@param classToSearch
@param interfaceToFind
@return type arguments of the interface

Given a class and an interfaces go through the class hierarchy to find the interface and return its type arguments .


private void populate() throws Exception {
        List<T> initializer = new ArrayList<T>(this.getMinIdle());

        for (int idx = 0; idx < this.getMinIdle() && (this.getMaxIdle() == DISABLED || idx < this.getMaxIdle()) && (this.getMaxActive() == DISABLED || idx < this.getMaxActive()); idx++) {
            initializer.add(this.borrowObject());
        }
        for (int idx = 0; idx < this.getMinIdle() && (this.getMaxIdle() == DISABLED || idx < this.getMaxIdle()) && (this.getMaxActive() == DISABLED || idx < this.getMaxActive()); idx++) {
            this.returnObject(initializer.get(idx));
        }
    }

private void populate ( ) throws Exception { List < T > initializer = new ArrayList < T > ( this . getMinIdle ( ) ) ; for ( int idx = 0 ; idx < this . getMinIdle ( ) && ( this . getMaxIdle ( ) == DISABLED || idx < this . getMaxIdle ( ) ) && ( this . getMaxActive ( ) == DISABLED || idx < this . getMaxActive ( ) ) ; idx ++ ) { initializer . add ( this . borrowObject ( ) ) ; } for ( int idx = 0 ; idx < this . getMinIdle ( ) && ( this . getMaxIdle ( ) == DISABLED || idx < this . getMaxIdle ( ) ) && ( this . getMaxActive ( ) == DISABLED || idx < this . getMaxActive ( ) ) ; idx ++ ) { this . returnObject ( initializer . get ( idx ) ) ; } }

Populate the pool up to minIdle instances. Is limited to maxIdle and maxActive.

@throws Exception when could not borrow or return objects to the pool

Populate the pool up to minIdle instances . Is limited to maxIdle and maxActive .


private void addReturnOptionDescription(Method method, Return.ReturnBuilder returnBuilder) {
        DocReturn returnAnno = getNonExceptionDocReturn(method);
        String returnOptionDesc = (returnAnno == null) ? null : returnAnno.description();
        returnBuilder.description(StringUtils.isEmpty(returnOptionDesc) ? null : returnAnno.description());
    }

private void addReturnOptionDescription ( Method method , Return . ReturnBuilder returnBuilder ) { DocReturn returnAnno = getNonExceptionDocReturn ( method ) ; String returnOptionDesc = ( returnAnno == null ) ? null : returnAnno . description ( ) ; returnBuilder . description ( StringUtils . isEmpty ( returnOptionDesc ) ? null : returnAnno . description ( ) ) ; }

Used for non exception return option

@param method
@param returnBuilder


private void returnObject(ObjectPool<Classifier> pool, Classifier object) {
        try {
            pool.returnObject(object);
        } catch (Exception e) {
            logger.error("Could not return object to pool", e);
        }
    }

private
void
returnObject
(
ObjectPool
<
Classifier
>
pool
,
Classifier
object
)
{
try
{
pool
.
returnObject
(
object
)
;
}
catch
(
Exception
e
)
{
logger
.
error
(
"Could not return object to pool"
,
e
)
;
}
}

Returns the given object to the pool.

@param pool   The pool to where return the object to.
@param object The object to be returned to the pool.


private Destination getDestination(final String destinationName) {
        if (!destinations.containsKey(destinationName)) {
            Destination destination = destinationSupplier.apply(destinationName);
            destinations.put(destinationName, destination);
        }
        return destinations.get(destinationName);
    }

private Destination getDestination ( final String destinationName ) { if ( ! destinations . containsKey ( destinationName ) ) { Destination destination = destinationSupplier . apply ( destinationName ) ; destinations . put ( destinationName , destination ) ; } return destinations . get ( destinationName ) ; }

Get the destination.

@param destinationName destinationName
@return JMS destination which is a queue or topic.


private MessageConsumer getConsumer(final String destinationName) {
        if (!consumers.containsKey(destinationName)) {
            Session session = getSession();

            Destination destination = getDestination(destinationName);
            try {
                MessageConsumer consumer = session.createConsumer(destination);
                consumers.put(destinationName, consumer);
            } catch (JMSException e) {
                throw new JmsException("Unable to create consumer for destination "
                        + destinationName, e);
            }
        }
        return consumers.get(destinationName);
    }

Get the `MessageConsumer`.

@param destinationName destinationName
@return JMS `MessageConsumer`.


private MessageProducer getProducer(final String destinationName) {

        if (!producers.containsKey(destinationName)) {

            Session session = getSession();
            Destination destination = getDestination(destinationName);
            MessageProducer producer;
            try {
                producer = session.createProducer(destination);
            } catch (JMSException e) {
                throw new JmsException("Unable to create producer for destination "
                        + destinationName, e);
            }
            producers.put(destinationName, producer);

        }
        return producers.get(destinationName);
    }

Get the `MessageProducer` or create one from the JMS session.

@param destinationName destinationName
@return JMS `MessageProducer`.

Get the MessageProducer or create one from the JMS session .


private Session getSession() {

        if (!sessionOption.isPresent()) {
            try {
                sessionOption = Optional.of(getConnection().createSession(transacted, acknowledgeMode));
            } catch (JMSException e) {
                throw new JmsException("Unable to get JMS session", e);
            }
        }
        return sessionOption.get();
    }

private
Session
getSession
(
)
{
if
(
!
sessionOption
.
isPresent
(
)
)
{
try
{
sessionOption
=
Optional
.
of
(
getConnection
(
)
.
createSession
(
transacted
,
acknowledgeMode
)
)
;
}
catch
(
JMSException
e
)
{
throw
new
JmsException
(
"Unable to get JMS session"
,
e
)
;
}
}
return
sessionOption
.
get
(
)
;
}

Get the current session or create one from the JMS connection.

@return JMS Session

Get the current session or create one from the JMS connection .


private Connection getConnection() {

        if (!connectionOption.isPresent()) {
            final Connection connection = connectionSupplier.get();

            if (connection instanceof ActiveMQConnection) {
                ((ActiveMQConnection) connection).addTransportListener(new TransportListener() {
                    @Override
                    public void onCommand(Object command) {

                    }

                    @Override
                    public void onException(IOException error) {
                    }

                    @Override
                    public void transportInterupted() {
                        connected.set(false);
                    }

                    @Override
                    public void transportResumed() {
                        connected.set(true);
                    }
                });
            }

            connected.set(true);

            if (startConnection) {
                try {
                    connection.start();
                } catch (JMSException e) {
                    throw new JmsException("Unable to start JMS connection", e);
                }
            }
            connectionOption = Optional.of(connection);
        }
        return connectionOption.get();
    }

private
Connection
getConnection
(
)
{
if
(
!
connectionOption
.
isPresent
(
)
)
{
final
Connection
connection
=
connectionSupplier
.
get
(
)
;
if
(
connection
instanceof
ActiveMQConnection
)
{
(
(
ActiveMQConnection
)
connection
)
.
addTransportListener
(
new
TransportListener
(
)
{
@
Override
public
void
onCommand
(
Object
command
)
{
}
@
Override
public
void
onException
(
IOException
error
)
{
}
@
Override
public
void
transportInterupted
(
)
{
connected
.
set
(
false
)
;
}
@
Override
public
void
transportResumed
(
)
{
connected
.
set
(
true
)
;
}
}
)
;
}
connected
.
set
(
true
)
;
if
(
startConnection
)
{
try
{
connection
.
start
(
)
;
}
catch
(
JMSException
e
)
{
throw
new
JmsException
(
"Unable to start JMS connection"
,
e
)
;
}
}
connectionOption
=
Optional
.
of
(
connection
)
;
}
return
connectionOption
.
get
(
)
;
}

Get the current connection or create one using the connectionSupplier.

@return JMS Connection

Get the current connection or create one using the connectionSupplier .


public void sendTextMessageWithDestination(final String destinationName, final String messageContent) {

        if (!this.isConnected()) {
            throw new JmsNotConnectedException("JMS connection is down " + destinationName);
        }

        final Session session = getSession();
        final MessageProducer producer = getProducer(destinationName);
        try {
            TextMessage message = session.createTextMessage(messageContent);
            producer.send(message);
        } catch (JMSException e) {
            throw new JmsException("Unable to send message to " + destinationName, e);
        }
    }

public
void
sendTextMessageWithDestination
(
final
String
destinationName
,
final
String
messageContent
)
{
if
(
!
this
.
isConnected
(
)
)
{
throw
new
JmsNotConnectedException
(
"JMS connection is down "
+
destinationName
)
;
}
final
Session
session
=
getSession
(
)
;
final
MessageProducer
producer
=
getProducer
(
destinationName
)
;
try
{
TextMessage
message
=
session
.
createTextMessage
(
messageContent
)
;
producer
.
send
(
message
)
;
}
catch
(
JMSException
e
)
{
throw
new
JmsException
(
"Unable to send message to "
+
destinationName
,
e
)
;
}
}

Send a text message given a queue or topic name and a text message.

@param destinationName destinationName
@param messageContent  messageContent

Send a text message given a queue or topic name and a text message .


public void listenTextMessagesWithDestination(final String destinationName,
                                                  final Consumer<String> messageListener) {
        final MessageConsumer consumer = getConsumer(destinationName);
        try {
            consumer.setMessageListener(message -> {
                try {
                    messageListener.accept(
                            ((TextMessage) message).getText()
                    );

                    if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
                        message.acknowledge();
                    }

                } catch (JMSException e) {

                    throw new JmsException("Unable to register get text from message in listener " + destinationName, e);
                } catch (Exception ex) {

                    throw new IllegalStateException("Unable handle JMS Consumer  " + destinationName, ex);
                }
            });
        } catch (JMSException e) {

            throw new JmsException("Unable to register message listener " + destinationName, e);
        }
    }

Listen to a message from JMS from a given destination by name.

@param destinationName destinationName
@param messageListener messageListener

Listen to a message from JMS from a given destination by name .


public String receiveTextMessageFromDestinationWithTimeout(final String destinationName, final int timeout) {

        if (!this.isConnected()) {
            throw new JmsNotConnectedException("Not connected");
        }
        MessageConsumer consumer = getConsumer(destinationName);
        TextMessage message;
        try {
            if (timeout == 0) {
                message = (TextMessage) consumer.receiveNoWait();
            } else {
                message = (TextMessage) consumer.receive(timeout);
            }
            if (message != null) {

                if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
                    message.acknowledge();
                }
                return message.getText();
            } else {
                return null;
            }
        } catch (JMSException e) {
            throw new JmsException("Unable to receive message from " + destinationName, e);
        }
    }

Receive a message from  destination with timeout.

@param destinationName destinationName
@param timeout         timeout
@return message

Receive a message from destination with timeout .


@Override
    public void stop() {
        if (connectionOption.isPresent()) {
            try {
                if (startConnection)
                    connectionOption.get().close();
            } catch (JMSException e) {

                throw new JmsException("Unable to stop ", e);
            }
            connectionOption = Optional.empty();
            sessionOption = Optional.empty();
            producers.clear();
            consumers.clear();
            destinations.clear();
        }
    }

@
Override
public
void
stop
(
)
{
if
(
connectionOption
.
isPresent
(
)
)
{
try
{
if
(
startConnection
)
connectionOption
.
get
(
)
.
close
(
)
;
}
catch
(
JMSException
e
)
{
throw
new
JmsException
(
"Unable to stop "
,
e
)
;
}
connectionOption
=
Optional
.
empty
(
)
;
sessionOption
=
Optional
.
empty
(
)
;
producers
.
clear
(
)
;
consumers
.
clear
(
)
;
destinations
.
clear
(
)
;
}
}


private void handleLoadFromUserDataService(final User loadedUser,
                                               final Callback<List<Recommendation>> recommendationsCallback) {

        /** Add a runnable to the callbacks list. */
        callbacks.add(() -> {
            List<Recommendation> recommendations = runRulesEngineAgainstUser(loadedUser);
            recommendationsCallback.accept(recommendations);
        });

//        callbacks.add(new Runnable() {
//            @Override
//            public void run() {
//                List<Recommendation> recommendations = runRulesEngineAgainstUser(loadedUser);
//                recommendationsCallback.accept(recommendations);
//            }
//        });
    }

//        callbacks.add(new Runnable() {

Handle defered recommendations based on user loads.

Handle defered recommendations based on user loads .


@NotNull
    public Map<Object, Object> getPoolConfiguration() {
        return ConfigurationConverter.getMap(configuration.subset(GenericObjectPoolConfig.class.getName()));
    }

@ NotNull public Map < Object , Object > getPoolConfiguration ( ) { return ConfigurationConverter . getMap ( configuration . subset ( GenericObjectPoolConfig . class . getName ( ) ) ) ; }

Returns the pool configuration of the scorer.

@return a map from configuration key to configuration value

Returns the pool configuration of the scorer .


public void setId(UUID id) {
        this.dirty = true;
        this.id = id;

        this.modelConfig.setProperty(ID, id.toString());
    }

public void setId ( UUID id ) { this . dirty = true ; this . id = id ; this . modelConfig . setProperty ( ID , id . toString ( ) ) ; }

Sets the ID of the model.

@param id the ID


public void setModel(File model) {
        this.dirty = true;
        this.model = model;

        this.modelConfig.setProperty(MODEL_FILE, model.getAbsolutePath());
    }

public void setModel ( File model ) { this . dirty = true ; this . model = model ; this . modelConfig . setProperty ( MODEL_FILE , model . getAbsolutePath ( ) ) ; }

Sets the model file of the serialized classifier.

@param model the model file

Sets the model file of the serialized classifier .


public void addOrUpdate(WekaModelConfig wekaModelConfig) throws FOSException {
        checkNotNull(wekaModelConfig, "Model config cannot be null");

        WekaThreadSafeScorer newWekaThreadSafeScorer = new WekaThreadSafeScorerPool(wekaModelConfig, wekaManagerConfig);
        WekaThreadSafeScorer oldWekaThreadSafeScorer = quickSwitch(wekaModelConfig.getId(), newWekaThreadSafeScorer);

        WekaUtils.closeSilently(oldWekaThreadSafeScorer);
    }

public
void
addOrUpdate
(
WekaModelConfig
wekaModelConfig
)
throws
FOSException
{
checkNotNull
(
wekaModelConfig
,
"Model config cannot be null"
)
;
WekaThreadSafeScorer
newWekaThreadSafeScorer
=
new
WekaThreadSafeScorerPool
(
wekaModelConfig
,
wekaManagerConfig
)
;
WekaThreadSafeScorer
oldWekaThreadSafeScorer
=
quickSwitch
(
wekaModelConfig
.
getId
(
)
,
newWekaThreadSafeScorer
)
;
WekaUtils
.
closeSilently
(
oldWekaThreadSafeScorer
)
;
}

Adds the given model to the managed models.

<p> If the provided model id already exists, then the older model is removed and the new one is instantiated.

@param wekaModelConfig the configuration of the new model
@throws FOSException when the new model could not be instantiated

Adds the given model to the managed models .


public void removeModel(UUID modelId) {
        WekaThreadSafeScorer newWekaThreadSafeScorer = null;
        WekaThreadSafeScorer oldWekaThreadSafeScorer = quickSwitch(modelId, newWekaThreadSafeScorer);

        WekaUtils.closeSilently(oldWekaThreadSafeScorer);
    }

public void removeModel ( UUID modelId ) { WekaThreadSafeScorer newWekaThreadSafeScorer = null ; WekaThreadSafeScorer oldWekaThreadSafeScorer = quickSwitch ( modelId , newWekaThreadSafeScorer ) ; WekaUtils . closeSilently ( oldWekaThreadSafeScorer ) ; }

Removes the given model from the managed models.

<p> If the model does not exist no exception will be thrown.

@param modelId the id of the model to remove.

Removes the given model from the managed models .


@Bean
    public ServiceQueue clusteredEventManagerServiceQueue(final @Qualifier("eventBusCluster")
                                                          EventBusCluster eventBusCluster) {

        if (eventBusCluster == null) {
            return null;
        }
        return eventBusCluster.eventServiceQueue();
    }

@ Bean public ServiceQueue clusteredEventManagerServiceQueue ( final @ Qualifier ( "eventBusCluster" ) EventBusCluster eventBusCluster ) { if ( eventBusCluster == null ) { return null ; } return eventBusCluster . eventServiceQueue ( ) ; }

The actual service queue for the clustered event bus.
All events are sent to this queue first.

@param eventBusCluster actual event manager impl no proxy
@return the service queue

The actual service queue for the clustered event bus . All events are sent to this queue first .