public Committees getCommitteesByTypeState(String typeId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Committee.getCommitteesByTypeState", new ArgMap("typeId", typeId), Committees.class );
	}

public Committees getCommitteesByTypeState ( String typeId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Committee.getCommitteesByTypeState" , new ArgMap ( "typeId" , typeId ) , Committees . class ) ; }

Returns the list of committees that fit the criteria.

@param typeId
@return {@link Committees}:

Returns the list of committees that fit the criteria .


public Committee getCommittee(String committeeId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Committee.getCommittee", new ArgMap("committeeId", committeeId), Committee.class );
	}

public Committee getCommittee ( String committeeId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Committee.getCommittee" , new ArgMap ( "committeeId" , committeeId ) , Committee . class ) ; }

Returns detailed committee data.

@param committeeId
@return {@link Committee}:


public CommitteeMembers getCommitteeMembers(String committeeId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Committee.getCommitteeMembers", new ArgMap("committeeId", committeeId), CommitteeMembers.class );
	}

public CommitteeMembers getCommitteeMembers ( String committeeId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Committee.getCommitteeMembers" , new ArgMap ( "committeeId" , committeeId ) , CommitteeMembers . class ) ; }

Returns members of the committee.

@param committeeId
@return {@link CommitteeMembers}:


public Leadership getPositions(String stateId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Leadership.getPositions", new ArgMap("stateId", stateId), Leadership.class );
	}

public Leadership getPositions ( String stateId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Leadership.getPositions" , new ArgMap ( "stateId" , stateId ) , Leadership . class ) ; }

Gets leadership positions by state and office.

@param stateId
@return {@link Leadership}:

Gets leadership positions by state and office .


public Leaders getOfficials(String leadershipId) throws VoteSmartException, VoteSmartErrorException {
		return api.query("Leadership.getOfficials", new ArgMap("leadershipId", leadershipId), Leaders.class );
	}

public Leaders getOfficials ( String leadershipId ) throws VoteSmartException , VoteSmartErrorException { return api . query ( "Leadership.getOfficials" , new ArgMap ( "leadershipId" , leadershipId ) , Leaders . class ) ; }

Gets officials that hold the leadership role in certain states.

@param leadershipId
@return {@link Leaders}:

Gets officials that hold the leadership role in certain states .


public static void sleep(int ms) {
      long deadline = System.currentTimeMillis() + ms;
      while (System.currentTimeMillis() < deadline) {
         try {
            Thread.sleep(Math.max(1, (deadline - System.currentTimeMillis()) / 2));
         } catch (InterruptedException ignore) {}
      }
   }

public static void sleep ( int ms ) { long deadline = System . currentTimeMillis ( ) + ms ; while ( System . currentTimeMillis ( ) < deadline ) { try { Thread . sleep ( Math . max ( 1 , ( deadline - System . currentTimeMillis ( ) ) / 2 ) ) ; } catch ( InterruptedException ignore ) { } } }

Sleeps for the provided amount of milliseconds, ignoring thread
interrupts.

@param ms
how many milliseconds to sleep

Sleeps for the provided amount of milliseconds ignoring thread interrupts .


public void start() {
      if (timer != null)
         throw new IllegalStateException("already running");

      if (interval < BUSY_WAITING_THRESHOLD)
         timer = new MyBusyTimer();
      else if (interval < MILLISECOND_THRESHOLD)
         timer = new MyWaitingTimer();
      else
         timer = new MyMillisecondTimer();

      Thread thread = new Thread(timer, "timer");
      thread.setDaemon(true);
      thread.start();
   }

public
void
start
(
)
{
if
(
timer
!=
)
throw
new
IllegalStateException
(
"already running"
)
;
if
(
interval
<
BUSY_WAITING_THRESHOLD
)
timer
=
new
MyBusyTimer
(
)
;
else
if
(
interval
<
MILLISECOND_THRESHOLD
)
timer
=
new
MyWaitingTimer
(
)
;
else
timer
=
new
MyMillisecondTimer
(
)
;
Thread
thread
=
new
Thread
(
timer
,
"timer"
)
;
thread
.
setDaemon
(
true
)
;
thread
.
start
(
)
;
}

Starts generating tick events, starting from 0. This method must not be
called when the tick source is already running.

Starts generating tick events starting from 0 . This method must not be called when the tick source is already running .


public void waitFor() throws Throwable {
      while (!finished) {
         try {
            synchronized (this) {
               this.wait(100);
            }
         } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
         }
      }

      if (t != null)
         throw t;
   }

public void waitFor ( ) throws Throwable { while ( ! finished ) { try { synchronized ( this ) { this . wait ( 100 ) ; } } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } } if ( t != null ) throw t ; }

Waits until the gobbler finished. If the gobbler encountered any
exception, it is thrown from this method.

@throws Throwable
if the gobbler has thrown an exception

Waits until the gobbler finished . If the gobbler encountered any exception it is thrown from this method .


public void close() {
      cancel = true;
      try {
         thread.interrupt();
         waitFor();
      } catch (Throwable ignore) {}

      try {
         is.close();
      } catch (Exception ignore) {}

      try {
         os.close();
      } catch (Exception ignore) {}
   }

public void close ( ) { cancel = true ; try { thread . interrupt ( ) ; waitFor ( ) ; } catch ( Throwable ignore ) { } try { is . close ( ) ; } catch ( Exception ignore ) { } try { os . close ( ) ; } catch ( Exception ignore ) { } }

Interrupts the gobbler and closes its streams.

Interrupts the gobbler and closes its streams .


public static <K, V, M extends Map<K, V>> M merge(Stream<? extends Map<K, V>> stream,
	                                                  BinaryOperator<V> mergeFunction,
	                                                  Supplier<M> mapSupplier) {

		Assert.notNull(stream, "Missing map merge function!");
		Assert.notNull(mergeFunction, "Missing map merge function!");
		Assert.notNull(mapSupplier, "Missing map supplier!");

		return stream.collect(mapSupplier,
		                      (a, b) -> b.forEach((k, v) -> a.merge(k, v, mergeFunction)),
		                      Map::putAll);
	}

public
static
<
K
,
V
,
M
extends
Map
<
K
,
V
>
>
M
merge
(
Stream
<
extends
Map
<
K
,
V
>
>
stream
,
BinaryOperator
<
V
>
mergeFunction
,
Supplier
<
M
>
mapSupplier
)
{
Assert
.
notNull
(
stream
,
"Missing map merge function!"
)
;
Assert
.
notNull
(
mergeFunction
,
"Missing map merge function!"
)
;
Assert
.
notNull
(
mapSupplier
,
"Missing map supplier!"
)
;
return
stream
.
collect
(
mapSupplier
,
(
a
,
b
)
->
b
.
forEach
(
(
k
,
v
)
->
a
.
merge
(
k
,
v
,
mergeFunction
)
)
,
Map
::
putAll
)
;
}

Merging single level aggregation maps

@param stream        source to merge
@param mergeFunction operation
@param mapSupplier   new map supplier
@param <K>           type of key
@param <V>           type of value
@param <M>           type of map supplier
@return new merged map


public static <K, V> List<Map<K, V>> split(Map<K, V> map, int limit) {

		Assert.notNull(map, "Missing map!");
		Assert.isTrue(limit > 0, "Map limit must be > 0!");

		if (map.size() <= limit) {
			return Collections.singletonList(map); // nothing to do
		}

		return map.entrySet().parallelStream().collect(mapSizer(limit));
	}

public
static
<
K
,
V
>
List
<
Map
<
K
,
V
>
>
split
(
Map
<
K
,
V
>
map
,
int
limit
)
{
Assert
.
notNull
(
map
,
"Missing map!"
)
;
Assert
.
isTrue
(
limit
>
0
,
"Map limit must be > 0!"
)
;
if
(
map
.
size
(
)
<=
limit
)
{
return
Collections
.
singletonList
(
map
)
;
// nothing to do
}
return
map
.
entrySet
(
)
.
parallelStream
(
)
.
collect
(
mapSizer
(
limit
)
)
;
}

Splits map to list of maps
@param map to be split
@param limit max number of items in splitted map
@param <K> key type
@param <V> value type
@return list of maps


private static <K, V> Collector<Map.Entry<K, V>, ?, List<Map<K, V>>> mapSizer(int limit) {
		return Collector.of(ArrayList::new,
		                    (l, e) -> {
			                    if (l.isEmpty() || l.get(l.size() - 1).size() == limit) {
				                    l.add(new HashMap<>());
			                    }
			                    l.get(l.size() - 1).put(e.getKey(), e.getValue());
		                    },
		                    (l1, l2) -> {
			                    if (l1.isEmpty()) {
				                    return l2;
			                    }
			                    if (l2.isEmpty()) {
				                    return l1;
			                    }
			                    if (l1.get(l1.size() - 1).size() < limit) {
				                    Map<K, V> map = l1.get(l1.size() - 1);
				                    ListIterator<Map<K, V>> mapsIte = l2.listIterator(l2.size());
				                    while (mapsIte.hasPrevious() && map.size() < limit) {
					                    Iterator<Map.Entry<K, V>> ite = mapsIte.previous().entrySet().iterator();
					                    while (ite.hasNext() && map.size() < limit) {
						                    Map.Entry<K, V> entry = ite.next();
						                    map.put(entry.getKey(), entry.getValue());
						                    ite.remove();
					                    }
					                    if (!ite.hasNext()) {
						                    mapsIte.remove();
					                    }
				                    }
			                    }
			                    l1.addAll(l2);
			                    return l1;
		                    }
		);
	}

private static < K , V > Collector < Map . Entry < K , V > , ? , List < Map < K , V > > > mapSizer ( int limit ) { return Collector . of ( ArrayList :: new , ( l , e ) -> { if ( l . isEmpty ( ) || l . get ( l . size ( ) - 1 ) . size ( ) == limit ) { l . add ( new HashMap <> ( ) ) ; } l . get ( l . size ( ) - 1 ) . put ( e . getKey ( ) , e . getValue ( ) ) ; } , ( l1 , l2 ) -> { if ( l1 . isEmpty ( ) ) { return l2 ; } if ( l2 . isEmpty ( ) ) { return l1 ; } if ( l1 . get ( l1 . size ( ) - 1 ) . size ( ) < limit ) { Map < K , V > map = l1 . get ( l1 . size ( ) - 1 ) ; ListIterator < Map < K , V > > mapsIte = l2 . listIterator ( l2 . size ( ) ) ; while ( mapsIte . hasPrevious ( ) && map . size ( ) < limit ) { Iterator < Map . Entry < K , V > > ite = mapsIte . previous ( ) . entrySet ( ) . iterator ( ) ; while ( ite . hasNext ( ) && map . size ( ) < limit ) { Map . Entry < K , V > entry = ite . next ( ) ; map . put ( entry . getKey ( ) , entry . getValue ( ) ) ; ite . remove ( ) ; } if ( ! ite . hasNext ( ) ) { mapsIte . remove ( ) ; } } } l1 . addAll ( l2 ) ; return l1 ; } ) ; }

Collector splitting map into seperate maps
@param limit max number of items in slitted map
@param <K> key type
@param <V> value type
@return collected map with size less or equal to limit


public static <K, V> Map<K, V> sort(Map<K, V> map, Comparator<Map.Entry<K, V>> comparator) {

		Assert.notNull(map, "Missing map!");
		Assert.notNull(comparator, "Missing comparator!");

		List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
		Collections.sort(list, comparator);

		Map<K, V> result = new LinkedHashMap<>();
		for (Map.Entry<K, V> entry : list) {
			result.put(entry.getKey(), entry.getValue());
		}
		return result;
	}

public
static
<
K
,
V
>
Map
<
K
,
V
>
sort
(
Map
<
K
,
V
>
map
,
Comparator
<
Map
.
Entry
<
K
,
V
>
>
comparator
)
{
Assert
.
notNull
(
map
,
"Missing map!"
)
;
Assert
.
notNull
(
comparator
,
"Missing comparator!"
)
;
List
<
Map
.
Entry
<
K
,
V
>
>
list
=
new
LinkedList
<>
(
map
.
entrySet
(
)
)
;
Collections
.
sort
(
list
,
comparator
)
;
Map
<
K
,
V
>
result
=
new
LinkedHashMap
<>
(
)
;
for
(
Map
.
Entry
<
K
,
V
>
entry
:
list
)
{
result
.
put
(
entry
.
getKey
(
)
,
entry
.
getValue
(
)
)
;
}
return
result
;
}

Sorts map with comparator

@param map        to be sorted
@param comparator to apply
@param <K>        type of key
@param <V>        type of value
@return sorted map (LinkedHashMap)


public static <T> T firstValue(Map<String, T> map) {

		if (map == null || map.size() == 0) {
			return null;
		}

		String firstKey = map.keySet().iterator().next();
		return map.get(firstKey);
	}

public static < T > T firstValue ( Map < String , T > map ) { if ( map == null || map . size ( ) == 0 ) { return null ; } String firstKey = map . keySet ( ) . iterator ( ) . next ( ) ; return map . get ( firstKey ) ; }

Returns first value in map as given by the iterator or null if empty

@param map to get first value out
@param <T> object type of result
@return first value in map or null if null or empty


public static <T> void isNull(T test, String message) {

		isTrue(test == null, message);
	}

public static < T > void isNull ( T test , String message ) { isTrue ( test == null , message ) ; }

Tests if object is null

@param test    must be null
@param message to return in exception
@param <T>     object type
@throws IllegalArgumentException if object != null


public static <T> void notNull(T test, String message) {

		isFalse(test == null, message);
	}

public static < T > void notNull ( T test , String message ) { isFalse ( test == null , message ) ; }

Tests if object is != null

@param test    must not be null
@param message to return in exception
@param <T>     object type
@throws IllegalArgumentException if object == null


public static void notNullOrEmptyTrimmed(String value, String message) {

		isFalse(StringUtils.isNullOrEmptyTrimmed(value), message);
	}

public static void notNullOrEmptyTrimmed ( String value , String message ) { isFalse ( StringUtils . isNullOrEmptyTrimmed ( value ) , message ) ; }

Tests if String is null or empty when trimmed

@param value   must be non empty string
@param message to return in exception
@throws IllegalArgumentException if value == null, value == "" or value.trim() == ""


public static <T> void isNullOrEmpty(Set<T> set, String message) {

		isTrue(set == null || set.size() == 0, message);
	}

public static < T > void isNullOrEmpty ( Set < T > set , String message ) { isTrue ( set == null || set . size ( ) == 0 , message ) ; }

Tests if set is null or empty

@param set     must be null or empty
@param message to return in exception
@param <T>     object type
@throws IllegalArgumentException if list != null or list.size() greater than 0


public static <T> void isNullOrEmpty(T[] array, String message) {

		isTrue(array == null || array.length == 0, message);
	}

public static < T > void isNullOrEmpty ( T [ ] array , String message ) { isTrue ( array == null || array . length == 0 , message ) ; }

Tests if array is null or empty

@param array   must be null or empty
@param message to return in exception
@param <T>     object type
@throws IllegalArgumentException if list != null or list.size() greater than 0


@Deprecated
	public static String getResourceAsString(String resourceFile, Class clazz) {

		Assert.notNullOrEmptyTrimmed(resourceFile, "Missing resource file!");

		Scanner scanner = null;

		try {
			InputStream resource = clazz.getResourceAsStream(resourceFile);
			scanner = new Scanner(resource, UTF_8);
			return scanner.useDelimiter("\\A").next();
		}
		catch (Exception e) {
			return null;
		}
		finally {
			if (scanner != null) {
				scanner.close();
			}
		}
	}

@
Deprecated
public
static
String
getResourceAsString
(
String
resourceFile
,
Class
clazz
)
{
Assert
.
notNullOrEmptyTrimmed
(
resourceFile
,
"Missing resource file!"
)
;
Scanner
scanner
=
;
try
{
InputStream
resource
=
clazz
.
getResourceAsStream
(
resourceFile
)
;
scanner
=
new
Scanner
(
resource
,
UTF_8
)
;
return
scanner
.
useDelimiter
(
"\\A"
)
.
next
(
)
;
}
catch
(
Exception
e
)
{
return
;
}
finally
{
if
(
scanner
!=
)
{
scanner
.
close
(
)
;
}
}
}

Loads class resource to String

@param resourceFile to read
@param clazz        to use for resource access
@return String representing the resource or null if resource could not be read


public static Set<String> getResourceWords(String resourceFile, Class clazz) {

		Assert.notNullOrEmptyTrimmed(resourceFile, "Missing resource file!");

		Scanner scanner = null;

		try {
			InputStream resource = clazz.getResourceAsStream(resourceFile);
			scanner = new Scanner(resource, UTF_8);

			Set<String> list = new LinkedHashSet<>();
			while (scanner.hasNext()) {
				String next = scanner.next();
				if (next != null && next.trim().length() > 0) {
					list.add(next);
				}
			}

			return list;
		}
		catch (Exception e) {
			return null;
		}
		finally {
			if (scanner != null) {
				scanner.close();
			}
		}
	}

public
static
Set
<
String
>
getResourceWords
(
String
resourceFile
,
Class
clazz
)
{
Assert
.
notNullOrEmptyTrimmed
(
resourceFile
,
"Missing resource file!"
)
;
Scanner
scanner
=
;
try
{
InputStream
resource
=
clazz
.
getResourceAsStream
(
resourceFile
)
;
scanner
=
new
Scanner
(
resource
,
UTF_8
)
;
Set
<
String
>
list
=
new
LinkedHashSet
<>
(
)
;
while
(
scanner
.
hasNext
(
)
)
{
String
next
=
scanner
.
next
(
)
;
if
(
next
!=
&&
next
.
trim
(
)
.
length
(
)
>
0
)
{
list
.
add
(
next
)
;
}
}
return
list
;
}
catch
(
Exception
e
)
{
return
;
}
finally
{
if
(
scanner
!=
)
{
scanner
.
close
(
)
;
}
}
}

Loads resource as a set of Strings, where each word is added to the set

@param resourceFile to read
@param clazz        to use for resource access
@return set of strings (lines) or null if resource could not be read

Loads resource as a set of Strings where each word is added to the set


@Deprecated
	public static Long getLastModifiedTime(String resourceFile, Class clazz) {

		Assert.notNullOrEmptyTrimmed(resourceFile, "Missing resource file!");

		try {
			URL url = clazz.getResource(resourceFile);
			return url.openConnection().getLastModified(); // get last modified date of resource
		}
		catch (IOException e) {
			return null;
		}
	}

@
Deprecated
public
static
Long
getLastModifiedTime
(
String
resourceFile
,
Class
clazz
)
{
Assert
.
notNullOrEmptyTrimmed
(
resourceFile
,
"Missing resource file!"
)
;
try
{
URL
url
=
clazz
.
getResource
(
resourceFile
)
;
return
url
.
openConnection
(
)
.
getLastModified
(
)
;
// get last modified date of resource
}
catch
(
IOException
e
)
{
return
;
}
}

Get resource last modified date

@param resourceFile to read
@param clazz        to use for resource access
@return last modified date or null if resource could not be read


public static String getString(final InputStream is, String encoding) {

		if (is == null) {
			return null;
		}

		if (StringUtils.isNullOrEmptyTrimmed(encoding)) {
			encoding = UTF_8;
		}

		final char[] buffer = new char[BUFFER_SIZE];
		final StringBuilder out = new StringBuilder();
		try {
			try (Reader in = new InputStreamReader(is, encoding)) {
				for (; ; ) {
					int rsz = in.read(buffer, 0, buffer.length);
					if (rsz < 0) {
						break;
					}
					out.append(buffer, 0, rsz);
				}
			}
		}
		catch (IOException ioe) {
			throw new RuntimeException(ioe);
		}
		return out.toString();
	}

public static String getString ( final InputStream is , String encoding ) { if ( is == null ) { return null ; } if ( StringUtils . isNullOrEmptyTrimmed ( encoding ) ) { encoding = UTF_8 ; } final char [ ] buffer = new char [ BUFFER_SIZE ] ; final StringBuilder out = new StringBuilder ( ) ; try { try ( Reader in = new InputStreamReader ( is , encoding ) ) { for ( ; ; ) { int rsz = in . read ( buffer , 0 , buffer . length ) ; if ( rsz < 0 ) { break ; } out . append ( buffer , 0 , rsz ) ; } } } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } return out . toString ( ) ; }

Load input stream into string

@param is       stream
@param encoding to use when reading input stream
@return String representation of given input


public static byte[] getBytes(InputStream is) {

		if (is == null) {
			return null;
		}

		ByteArrayOutputStream buffer = new ByteArrayOutputStream();

		int nRead;
		byte[] data = new byte[BUFFER_SIZE];
		try {

			while ((nRead = is.read(data, 0, data.length)) != -1) {
				buffer.write(data, 0, nRead);
			}

			buffer.flush();
		}
		catch (IOException ignored) {
		}

		return buffer.toByteArray();
	}

public static byte [ ] getBytes ( InputStream is ) { if ( is == null ) { return null ; } ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int nRead ; byte [ ] data = new byte [ BUFFER_SIZE ] ; try { while ( ( nRead = is . read ( data , 0 , data . length ) ) != - 1 ) { buffer . write ( data , 0 , nRead ) ; } buffer . flush ( ) ; } catch ( IOException ignored ) { } return buffer . toByteArray ( ) ; }

Load input stream into byte array

@param is stream
@return byte representation of given input


public static String readFileToString(File file) throws IOException {

		Assert.isTrue(file.exists(), "File '" + file + "' does not exist");
		Assert.isFalse(file.isDirectory(), "File '" + file + "' is a directory");
		Assert.isTrue(file.canRead(), "File '" + file + "' cannot be read");

		FileInputStream stream = new FileInputStream(file);
		return getString(stream);
	}

public
static
String
readFileToString
(
File
file
)
throws
IOException
{
Assert
.
isTrue
(
file
.
exists
(
)
,
"File '"
+
file
+
"' does not exist"
)
;
Assert
.
isFalse
(
file
.
isDirectory
(
)
,
"File '"
+
file
+
"' is a directory"
)
;
Assert
.
isTrue
(
file
.
canRead
(
)
,
"File '"
+
file
+
"' cannot be read"
)
;
FileInputStream
stream
=
new
FileInputStream
(
file
)
;
return
getString
(
stream
)
;
}

Reads file into String

@param file to be read
@return file content
@throws IOException in case file does't exist or is not a file


@Deprecated
	public static String getResourceAbsolutePath(String resource, Class clazz) {

		Assert.notNullOrEmptyTrimmed(resource, "Missing resource name!");

		URL file = clazz.getResource(resource);
		Assert.notNull(file, "Resource: '" + resource + "', not found!");

		return file.getFile();
	}

@
Deprecated
public
static
String
getResourceAbsolutePath
(
String
resource
,
Class
clazz
)
{
Assert
.
notNullOrEmptyTrimmed
(
resource
,
"Missing resource name!"
)
;
URL
file
=
clazz
.
getResource
(
resource
)
;
Assert
.
notNull
(
file
,
"Resource: '"
+
resource
+
"', not found!"
)
;
return
file
.
getFile
(
)
;
}

Gets absolute file path of resource

@param resource to get absolute file path for
@param clazz    namespace holding resource
@return file path if found
@throws IllegalArgumentException if resource can not be found


public static String generateString(int length) {

		if (length <= 0 || length > 100) {
			throw new IllegalArgumentException("Can't generate random id with length: " + length);
		}

		SecureRandom random = new SecureRandom();
		StringBuilder sb = new StringBuilder(length);
		for (int i = 0; i < length; i++) {
			sb.append(ELEMENTS.charAt(random.nextInt(ELEMENTS.length())));
		}

		return sb.toString();
	}

Generates random string from ELEMENTS set of chars and numbers

@param length desired length of key greater than 0
@return random string of desired length (min 1, max 100 characters long)


public static long generateLong(int length) {

		if (length <= 0 || length > 19) {
			throw new IllegalArgumentException("Can't generate random id with length: " + length);
		}

		SecureRandom random = new SecureRandom();
		StringBuilder sb = new StringBuilder(length);

		// 1st digit should  not be a 0 or 9 if desired length is 19 (as max long is: 9223372036854775807)
		if (length == 19) {
			sb.append(NUMBERS_NO_NINE_AND_ZERO.charAt(random.nextInt(NUMBERS_NO_NINE_AND_ZERO.length())));
		}
		else {
			sb.append(NUMBERS_NO_ZERO.charAt(random.nextInt(NUMBERS_NO_ZERO.length())));
		}

		// all other digits can contain a 0
		for (int i = 1; i < length; i++) {
			sb.append(NUMBERS.charAt(random.nextInt(NUMBERS.length())));
		}

		return Long.parseLong(sb.toString());
	}

Generates non negative long key of maximum length 18

@param length desired length of key grater than 0 (must consider max possible length of a long value)
@return long key (min 1, max 19 digits long)


@SafeVarargs
	public static <T> T[] join(final T[] array1, final T... array2) {

		if (isEmpty(array1) && isEmpty(array2)) {
			return null;
		}

		if (isEmpty(array1)) {
			return array2;
		}

		if (isEmpty(array2)) {
			return array1;
		}

		final Class<?> type1 = array1.getClass().getComponentType();

		@SuppressWarnings("unchecked") // OK, because array is of type T
		final T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);

		int index = 0;
		for (T item : array1) {
			joinedArray[index++] = item;
		}

		for (T item : array2) {
			joinedArray[index++] = item;
		}

		return joinedArray;
	}

@
SafeVarargs
public
static
<
T
>
T
[
]
join
(
final
T
[
]
array1
,
final
T
...
array2
)
{
if
(
isEmpty
(
array1
)
&&
isEmpty
(
array2
)
)
{
return
;
}
if
(
isEmpty
(
array1
)
)
{
return
array2
;
}
if
(
isEmpty
(
array2
)
)
{
return
array1
;
}
final
Class
<
>
type1
=
array1
.
getClass
(
)
.
getComponentType
(
)
;
@
SuppressWarnings
(
"unchecked"
)
// OK, because array is of type T
final
T
[
]
joinedArray
=
(
T
[
]
)
Array
.
newInstance
(
type1
,
array1
.
length
+
array2
.
length
)
;
int
index
=
0
;
for
(
T
item
:
array1
)
{
joinedArray
[
index
++
]
=
item
;
}
for
(
T
item
:
array2
)
{
joinedArray
[
index
++
]
=
item
;
}
return
joinedArray
;
}

joins two arrays and preserves array order
array1 items are followed by array2 items as given
@param array1 first array
@param array2 second array
@param <T> class type of object in arrays
@return joined array holding both arrays in same order as given


public static <T> List<Set<T>> split(Set<T> set, int maxSize) {

		Assert.notNull(set, "Missing set to be split!");
		Assert.isTrue(maxSize > 0, "Max size must be > 0!");

		if (set.size() < maxSize) {
			return Collections.singletonList(set);
		}

		List<Set<T>> list = new ArrayList<>();
		Iterator<T> iterator = set.iterator();

		while (iterator.hasNext()) {
			Set<T> newSet = new HashSet<>();
			for (int j = 0; j < maxSize && iterator.hasNext(); j++) {
				T item = iterator.next();
				newSet.add(item);
			}
			list.add(newSet);
		}
		return list;
	}

public
static
<
T
>
List
<
Set
<
T
>
>
split
(
Set
<
T
>
set
,
int
maxSize
)
{
Assert
.
notNull
(
set
,
"Missing set to be split!"
)
;
Assert
.
isTrue
(
maxSize
>
0
,
"Max size must be > 0!"
)
;
if
(
set
.
size
(
)
<
maxSize
)
{
return
Collections
.
singletonList
(
set
)
;
}
List
<
Set
<
T
>
>
list
=
new
ArrayList
<>
(
)
;
Iterator
<
T
>
iterator
=
set
.
iterator
(
)
;
while
(
iterator
.
hasNext
(
)
)
{
Set
<
T
>
newSet
=
new
HashSet
<>
(
)
;
for
(
int
j
=
0
;
j
<
maxSize
&&
iterator
.
hasNext
(
)
;
j
++
)
{
T
item
=
iterator
.
next
(
)
;
newSet
.
add
(
item
)
;
}
list
.
add
(
newSet
)
;
}
return
list
;
}

Splits set in 1..N chunks of maxSize or less

@param set     to be spitted
@param maxSize of a given chunk
@param <T>     type of class in set
@return list of sets containing all elements of original set without duplicates

Splits set in 1 .. N chunks of maxSize or less


public static Instant getMonthStart(Instant time) {

		Assert.notNull(time, "Missing date time");
		LocalDateTime dateTime = LocalDateTime.ofInstant(time, ZoneOffset.UTC);
		dateTime = dateTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).with(ChronoField.MILLI_OF_SECOND, 0);
		return dateTime.toInstant(ZoneOffset.UTC);
	}

public
static
Instant
getMonthStart
(
Instant
time
)
{
Assert
.
notNull
(
time
,
"Missing date time"
)
;
LocalDateTime
dateTime
=
LocalDateTime
.
ofInstant
(
time
,
ZoneOffset
.
UTC
)
;
dateTime
=
dateTime
.
withDayOfMonth
(
1
)
.
withHour
(
0
)
.
withMinute
(
0
)
.
withSecond
(
0
)
.
with
(
ChronoField
.
MILLI_OF_SECOND
,
0
)
;
return
dateTime
.
toInstant
(
ZoneOffset
.
UTC
)
;
}

Gets first millisecond of first day in month

@param time to get first millisecond
@return first millisecond of month for given time


public static Instant getMonthEnd(Instant time) {

		Assert.notNull(time, "Missing date time");
		LocalDateTime dateTime = LocalDateTime.ofInstant(time, ZoneOffset.UTC);
		dateTime = dateTime.withDayOfMonth(1).withHour(23).withMinute(59).withSecond(59).with(ChronoField.MILLI_OF_SECOND, 999);
		dateTime = dateTime.plus(1, ChronoUnit.MONTHS).minus(1, ChronoUnit.DAYS);
		return dateTime.toInstant(ZoneOffset.UTC);
	}

public
static
Instant
getMonthEnd
(
Instant
time
)
{
Assert
.
notNull
(
time
,
"Missing date time"
)
;
LocalDateTime
dateTime
=
LocalDateTime
.
ofInstant
(
time
,
ZoneOffset
.
UTC
)
;
dateTime
=
dateTime
.
withDayOfMonth
(
1
)
.
withHour
(
23
)
.
withMinute
(
59
)
.
withSecond
(
59
)
.
with
(
ChronoField
.
MILLI_OF_SECOND
,
999
)
;
dateTime
=
dateTime
.
plus
(
1
,
ChronoUnit
.
MONTHS
)
.
minus
(
1
,
ChronoUnit
.
DAYS
)
;
return
dateTime
.
toInstant
(
ZoneOffset
.
UTC
)
;
}

Returns last millisecond of last day in month ... +1 = next first day in month

@param time to get last second in month
@return last millisecond of month for given time

Returns last millisecond of last day in month ... + 1 = next first day in month


public static String trimToNull(String text) {

		text = trim(text);

		if (text == null || text.isEmpty()) {
			return null;
		}

		return text;
	}

public static String trimToNull ( String text ) { text = trim ( text ) ; if ( text == null || text . isEmpty ( ) ) { return null ; } return text ; }

Trims down text to null if empty

@param text to be trimmed
@return text or null if empty


public static String capitalize(String input) {

		if (input == null) {
			return null;
		}

		if (input.length() > 1) {
			for (int i = 0; i < input.length(); i++) {
				if (Character.isAlphabetic(input.charAt(i))) {
					return input.substring(0, i) + Character.toString(input.charAt(i)).toUpperCase() + input.substring(i + 1);
				}
			}
		}

		return input.toUpperCase();
	}

public static String capitalize ( String input ) { if ( input == null ) { return null ; } if ( input . length ( ) > 1 ) { for ( int i = 0 ; i < input . length ( ) ; i ++ ) { if ( Character . isAlphabetic ( input . charAt ( i ) ) ) { return input . substring ( 0 , i ) + Character . toString ( input . charAt ( i ) ) . toUpperCase ( ) + input . substring ( i + 1 ) ; } } } return input . toUpperCase ( ) ; }

Capitalizes first character in given string

@param input to capitalize first character
@return capitalized string or null if null


public static String join(Object[] args, String separator) {

		return join(args, separator, null);
	}

public static String join ( Object [ ] args , String separator ) { return join ( args , separator , null ) ; }

Joins array of objects into string, where items are separated
with a defined separator.

@param args      array of Object
@param separator to be used between elements
@return items joined into a single string

Joins array of objects into string where items are separated with a defined separator .


public static String join(Set<?> items, String separator) {

		return join(items, separator, null);
	}

public static String join ( Set < ? > items , String separator ) { return join ( items , separator , null ) ; }

Joins set of items to a single string, where items are separated
with a defined separator.

@param items     to join into string
@param separator to be used between elements
@return items joined into a single string

Joins set of items to a single string where items are separated with a defined separator .


public static List<String> getWords(String text) {

		List<String> output = new ArrayList<>();
		if (isNullOrEmptyTrimmed(text)) {
			return output;
		}

		Pattern p = Pattern.compile("\\b\\p{L}+\\b");

		Matcher m = p.matcher(text);
		while (m.find()) {
			output.add(m.group());
		}

		return output;
	}

public static List < String > getWords ( String text ) { List < String > output = new ArrayList <> ( ) ; if ( isNullOrEmptyTrimmed ( text ) ) { return output ; } Pattern p = Pattern . compile ( "\\b\\p{L}+\\b" ) ; Matcher m = p . matcher ( text ) ; while ( m . find ( ) ) { output . add ( m . group ( ) ) ; } return output ; }

Extracts words from text removing non alpha characters

@param text to extract words from
@return list of found words or empty list if none found


public static String trimTextDown(String text, int size) {

		if (text == null || text.length() <= size) {
			return text;
		}

		int pos = text.lastIndexOf(" ", size);

		if (pos < 0) {
			return text.substring(0, size);
		}

		return text.substring(0, pos);
	}

public
static
String
trimTextDown
(
String
text
,
int
size
)
{
if
(
text
==
||
text
.
length
(
)
<=
size
)
{
return
text
;
}
int
pos
=
text
.
lastIndexOf
(
" "
,
size
)
;
if
(
pos
<
0
)
{
return
text
.
substring
(
0
,
size
)
;
}
return
text
.
substring
(
0
,
pos
)
;
}

Reduces text to max given size preserving words

@param text to trim down
@param size max desired size
@return trimmed down text with "..." or original text if fitting size


public static String trimTextDown(String text, int sizeMinusAppend, String append) {

		Assert.notNull(append, "Missing append!");

		if (text == null || text.length() <= sizeMinusAppend) {
			return text;
		}

		sizeMinusAppend = sizeMinusAppend - append.length();

		int pos = text.lastIndexOf(" ", sizeMinusAppend);

		if (pos < 0) {
			return text.substring(0, sizeMinusAppend) + append;
		}

		return text.substring(0, pos) + append;
	}

public
static
String
trimTextDown
(
String
text
,
int
sizeMinusAppend
,
String
append
)
{
Assert
.
notNull
(
append
,
"Missing append!"
)
;
if
(
text
==
||
text
.
length
(
)
<=
sizeMinusAppend
)
{
return
text
;
}
sizeMinusAppend
=
sizeMinusAppend
append
.
length
(
)
;
int
pos
=
text
.
lastIndexOf
(
" "
,
sizeMinusAppend
)
;
if
(
pos
<
0
)
{
return
text
.
substring
(
0
,
sizeMinusAppend
)
+
append
;
}
return
text
.
substring
(
0
,
pos
)
+
append
;
}

Reduces text size to a given size

@param text            to reduce
@param sizeMinusAppend size final string should be max long
@param append          string to append at the end to indicate trimming
@return trimmed text with appended text of given max size, or original text if shorter than desired


public static List<String> asListOfChars(String text) {

		List<String> list = new ArrayList<>();

		if (StringUtils.isNullOrEmptyTrimmed(text)) {
			return list;
		}

		for (int i = 0; i < text.length(); i++) {
			list.add(Character.toString(text.charAt(i)));
		}

		return list;
	}

public static List < String > asListOfChars ( String text ) { List < String > list = new ArrayList <> ( ) ; if ( StringUtils . isNullOrEmptyTrimmed ( text ) ) { return list ; } for ( int i = 0 ; i < text . length ( ) ; i ++ ) { list . add ( Character . toString ( text . charAt ( i ) ) ) ; } return list ; }

Converts text to list of characters

@param text to be converted
@return list of characters


public static int relevance(String value, String search) {

		if (StringUtils.isNullOrEmptyTrimmed(value) ||
			StringUtils.isNullOrEmptyTrimmed(search)) {
			return -1;
		}

		if (search.length() > value.length()) {
			return -1;
		}

		int relevance = -1; // start at -1 ... so -1 is returned for no result
		int delta = 1; // first delta at 1 ... producing a sum of 0 when first letter is found

		int len = value.length();
		int searchLen = search.length();
		int letterIndex = 0;

		for (int searchIndex = 0; searchIndex < searchLen; searchIndex++) {

			char match = search.charAt(searchIndex);

			while (letterIndex < len) {
				char letter = value.charAt(letterIndex);
				letterIndex++;

				if (match == letter) {
					relevance = relevance + delta; // reverse to get higher value for better match
					delta = 0;
					break;
				}
				else {
					delta++;
				}
			}

			// we matched all characters ... and found the last one ...
			if (delta == 0 && searchIndex == searchLen - 1) {
				return relevance;
			}

			if (letterIndex == len) {
				break;
			}
		}

		return -1;
	}

Calculates matching relevance between given string and search expression

@param value  to search in
@param search to search for
@return -1 not relevant, 0..N - where lower values represents more relevant results


public static String unQuote(String text) {

		if (isNullOrEmptyTrimmed(text)) {
			return text;
		}

		if ((text.startsWith("\"") && text.endsWith("\"")) ||
		    (text.startsWith("'") && text.endsWith("'"))) {
			return text.substring(1, text.length() - 1);
		}

		return text;
	}

public static String unQuote ( String text ) { if ( isNullOrEmptyTrimmed ( text ) ) { return text ; } if ( ( text . startsWith ( "\"" ) && text . endsWith ( "\"" ) ) || ( text . startsWith ( "'" ) && text . endsWith ( "'" ) ) ) { return text . substring ( 1 , text . length ( ) - 1 ) ; } return text ; }

Removes double or single quotes if any are present

@param text to remove double quotes from
@return un quoted string


public static long getTimezoneTime(long time, int timezone) {

		Calendar calendar = getCalendar(time);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);

		hour = (hour + timezone) % 24;
		if (hour < 0) {
			hour = 24 + hour;
			calendar.add(Calendar.DAY_OF_MONTH, -1);
		}

		calendar.set(Calendar.HOUR_OF_DAY, hour);
		return calendar.getTimeInMillis();
	}

public static long getTimezoneTime ( long time , int timezone ) { Calendar calendar = getCalendar ( time ) ; int hour = calendar . get ( Calendar . HOUR_OF_DAY ) ; hour = ( hour + timezone ) % 24 ; if ( hour < 0 ) { hour = 24 + hour ; calendar . add ( Calendar . DAY_OF_MONTH , - 1 ) ; } calendar . set ( Calendar . HOUR_OF_DAY , hour ) ; return calendar . getTimeInMillis ( ) ; }

Returns time for given time zone
@param time current time
@param timezone time zone (-12 / +12)
@return time in other time zone


public List<Integer> hasTag(final Integer tagID) {
        final List<Integer> retValue = new ArrayList<Integer>();

        for (final FilterTag tag : getFilterTags()) {
            if (tag.getTag().getTagId().equals(tagID)) retValue.add(tag.getTagState());
        }

        return retValue;
    }

public List < Integer > hasTag ( final Integer tagID ) { final List < Integer > retValue = new ArrayList < Integer > ( ) ; for ( final FilterTag tag : getFilterTags ( ) ) { if ( tag . getTag ( ) . getTagId ( ) . equals ( tagID ) ) retValue . add ( tag . getTagState ( ) ) ; } return retValue ; }

Loops through the FilterTags held by this Filter, and returns the state of the tag if it exists, and -1 if it does not.

@param tagID The id of the tag to get the state of
@return -1 if the tag was not found, otherwise the state of the tag

Loops through the FilterTags held by this Filter and returns the state of the tag if it exists and - 1 if it does not .


private boolean isViolation(String severity) {
        if ("error".equals(severity)) {
            return "error".equals(violationSeverity) || "warning".equals(violationSeverity)
                    || "info".equals(violationSeverity);
        } else if ("warning".equals(severity)) {
            return "warning".equals(violationSeverity) || "info".equals(violationSeverity);
        } else if ("info".equals(severity)) {
            return "info".equals(violationSeverity);
        } else {
            return false;
        }
    }

private boolean isViolation ( String severity ) { if ( "error" . equals ( severity ) ) { return "error" . equals ( violationSeverity ) || "warning" . equals ( violationSeverity ) || "info" . equals ( violationSeverity ) ; } else if ( "warning" . equals ( severity ) ) { return "warning" . equals ( violationSeverity ) || "info" . equals ( violationSeverity ) ; } else if ( "info" . equals ( severity ) ) { return "info" . equals ( violationSeverity ) ; } else { return false ; } }

Checks if the given severity is considered a violation.

@param severity The severity to check
@return true if the given severity is a violation, otherwise false

Checks if the given severity is considered a violation .


public void iconSeverity(String level) {
        sink.figure();
        sink.figureGraphics("images/icon_" + level + "_sml.gif");
        sink.figure_();
    }

public void iconSeverity ( String level ) { sink . figure ( ) ; sink . figureGraphics ( "images/icon_" + level + "_sml.gif" ) ; sink . figure_ ( ) ; }

Render a simple icon of given level.

@param level one of INFO, WARNING or ERROR constants


public void iconSeverity(String level, int textType) {
        sink.figure();
        sink.figureGraphics("images/icon_" + level + "_sml.gif");
        sink.figure_();

        if (textType > 0) {
            sink.nonBreakingSpace();

            sink.text(bundle.getString("report.checkstyle." + level + suffix(textType)));
        }
    }

public void iconSeverity ( String level , int textType ) { sink . figure ( ) ; sink . figureGraphics ( "images/icon_" + level + "_sml.gif" ) ; sink . figure_ ( ) ; if ( textType > 0 ) { sink . nonBreakingSpace ( ) ; sink . text ( bundle . getString ( "report.checkstyle." + level + suffix ( textType ) ) ) ; } }

Render an icon of given level with associated text.

@param level    one of INFO, WARNING or ERROR constants
@param textType one of NO_TEXT, TEXT_SIMPLE, TEXT_TITLE or
TEXT_ABBREV constants

Render an icon of given level with associated text .


@Transient
    public String getTagsList(final boolean brLineBreak) {
        // define the line breaks for html and for tooltips
        final String lineBreak = brLineBreak ? "
" : "\n";
        final String boldStart = brLineBreak ? "" : "";
        final String boldEnd = brLineBreak ? "" : "";

        final TreeMap<NameIDSortMap, ArrayList<String>> tags = new TreeMap<NameIDSortMap, ArrayList<String>>();

        for (final TagToProject tagToProject : tagToProjects) {
            final Tag tag = tagToProject.getTag();
            final Set<TagToCategory> tagToCategories = tag.getTagToCategories();

            if (tagToCategories.size() == 0) {
                NameIDSortMap categoryDetails = new NameIDSortMap("Uncategorised", -1, 0);

                if (!tags.containsKey(categoryDetails)) tags.put(categoryDetails, new ArrayList<String>());

                tags.get(categoryDetails).add(tag.getTagName());
            } else {
                for (final TagToCategory category : tagToCategories) {
                    NameIDSortMap categoryDetails = new NameIDSortMap(category.getCategory().getCategoryName(),
                            category.getCategory().getCategoryId(),
                            category.getCategory().getCategorySort() == null ? 0 : category.getCategory().getCategorySort());

                    if (!tags.containsKey(categoryDetails)) tags.put(categoryDetails, new ArrayList<String>());

                    tags.get(categoryDetails).add(tag.getTagName());
                }
            }
        }

        String tagsList = "";
        for (final NameIDSortMap key : tags.keySet()) {
            // sort alphabetically
            Collections.sort(tags.get(key));

            if (tagsList.length() != 0) tagsList += lineBreak;

            tagsList += boldStart + key.getName() + boldEnd + ": ";

            String thisTagList = "";

            for (final String tag : tags.get(key)) {
                if (thisTagList.length() != 0) thisTagList += ", ";

                thisTagList += tag;
            }

            tagsList += thisTagList + " ";
        }

        return tagsList;
    }

Generates a HTML formatted and categorized list of the tags that are associated with this topic

@return A HTML String to display in a table


@Transient
    public void setNextAndClean(CSNode next) {
        setNextInternal(next);
        if (next != null) {
            next.setPreviousInternal(this);
        }
    }

@ Transient public void setNextAndClean ( CSNode next ) { setNextInternal ( next ) ; if ( next != null ) { next . setPreviousInternal ( this ) ; } }

Sets the Next Node and cleans up any old references.

@param next The next node.

Sets the Next Node and cleans up any old references .


@Transient
    public void setPreviousAndClean(CSNode previous) {
        setPreviousInternal(previous);
        if (previous != null) {
            previous.setNextInternal(this);
        }
    }

@ Transient public void setPreviousAndClean ( CSNode previous ) { setPreviousInternal ( previous ) ; if ( previous != null ) { previous . setNextInternal ( this ) ; } }

Sets the Previous Node and cleans up any old references.

@param previous The previous node.

Sets the Previous Node and cleans up any old references .


public Node find(String host, int port) {
		return socketToNodeMap.get(Utils.toKey(host, port));
	}

public Node find ( String host , int port ) { return socketToNodeMap . get ( Utils . toKey ( host , port ) ) ; }

Finds the node by host and port.

@param host
- the host.
@param port
- the port.
@return - the found node, or null otherwise.


public Set<Node> find(String host) {
		Set<Node> resultSet = new HashSet<Node>();

		if (host != null) {
			for (Node node : socketToNodeMap.values()) {
				if (host.equals(node.getHost())) {
					resultSet.add(node);
				}
			}
		}

		return resultSet;
	}

public Set < Node > find ( String host ) { Set < Node > resultSet = new HashSet < Node > ( ) ; if ( host != null ) { for ( Node node : socketToNodeMap . values ( ) ) { if ( host . equals ( node . getHost ( ) ) ) { resultSet . add ( node ) ; } } } return resultSet ; }

Finds the set of nodes by host.

@param host
- the host.
@return - the found nodes.


public Set<Node> getAllNotDead() {
		Set<Node> allNotDeadNodesSet = new HashSet<Node>();

		for (Node node : socketToNodeMap.values()) {
			if (!NodeStatus.DEAD.equals(node.getStatus())) {
				allNotDeadNodesSet.add(node);
			}
		}

		return allNotDeadNodesSet;
	}

public Set < Node > getAllNotDead ( ) { Set < Node > allNotDeadNodesSet = new HashSet < Node > ( ) ; for ( Node node : socketToNodeMap . values ( ) ) { if ( ! NodeStatus . DEAD . equals ( node . getStatus ( ) ) ) { allNotDeadNodesSet . add ( node ) ; } } return allNotDeadNodesSet ; }

Gets all the nodes not in status DEAD.

@return - all the nodes not in status DEAD.


public void add(Node node) {
		socketToNodeMap.put(Utils.toKey(node), node);
		sendEvent(node, NodeEventType.ADDED);
	}

public void add ( Node node ) { socketToNodeMap . put ( Utils . toKey ( node ) , node ) ; sendEvent ( node , NodeEventType . ADDED ) ; }

Adds one more node to the container.

@param node
- the node.


public void remove(Node node) {
		socketToNodeMap.remove(Utils.toKey(node));
		sendEvent(node, NodeEventType.REMOVED);
	}

public void remove ( Node node ) { socketToNodeMap . remove ( Utils . toKey ( node ) ) ; sendEvent ( node , NodeEventType . REMOVED ) ; }

Removes the specified node.

@param node
- the node.


public void markAsAlive(Node node) {
		if (!NodeStatus.ALIVE.equals(node.getStatus())) {
			socketToNodeMap.get(Utils.toKey(node)).markAsAlive();
			sendEvent(node, NodeEventType.MARKED_AS_ALIVE);
		}
	}

public void markAsAlive ( Node node ) { if ( ! NodeStatus . ALIVE . equals ( node . getStatus ( ) ) ) { socketToNodeMap . get ( Utils . toKey ( node ) ) . markAsAlive ( ) ; sendEvent ( node , NodeEventType . MARKED_AS_ALIVE ) ; } }

Marks the node as ALIVE in case of its status is not ALIVE.

@param node
- the node.

Marks the node as ALIVE in case of its status is not ALIVE .


public void markAsDead(Node node) {
		if (!NodeStatus.DEAD.equals(node.getStatus())) {
			socketToNodeMap.get(Utils.toKey(node)).markAsDead();
			sendEvent(node, NodeEventType.MARKED_AS_DEAD);
		}
	}

public void markAsDead ( Node node ) { if ( ! NodeStatus . DEAD . equals ( node . getStatus ( ) ) ) { socketToNodeMap . get ( Utils . toKey ( node ) ) . markAsDead ( ) ; sendEvent ( node , NodeEventType . MARKED_AS_DEAD ) ; } }

Marks the node as DEAD in case of its status is not DEAD.

@param node
- the node.

Marks the node as DEAD in case of its status is not DEAD .


private void sendEvent(Node node, NodeEventType type) {
		NodeEvent event = new NodeEvent(node, type);
		for (NodeEventHandler handler : handlers) {
			handler.handle(event);
		}
	}

private void sendEvent ( Node node , NodeEventType type ) { NodeEvent event = new NodeEvent ( node , type ) ; for ( NodeEventHandler handler : handlers ) { handler . handle ( event ) ; } }

Sends the event to all the handlers.

@param node
- the event node.
@param type
- the event type.


private String getCheckstyleVersion() {
        Package checkstyleApiPackage = Configuration.class.getPackage();

        return (checkstyleApiPackage == null) ? null : checkstyleApiPackage.getImplementationVersion();
    }

private String getCheckstyleVersion ( ) { Package checkstyleApiPackage = Configuration . class . getPackage ( ) ; return ( checkstyleApiPackage == null ) ? null : checkstyleApiPackage . getImplementationVersion ( ) ; }

Get the effective Checkstyle version at runtime.

@return the MANIFEST implementation version of Checkstyle API package (can be null)
@todo Copied from CheckstyleReportGenerator - move to a utility class

Get the effective Checkstyle version at runtime .


private void configureResourceLocator(final ResourceManager resourceManager,
                                          final CheckstyleExecutorRequest request,
                                          final List<Artifact> additionalArtifacts) {
        final MavenProject project = request.getProject();
        resourceManager.setOutputDirectory(new File(project.getBuild().getDirectory()));

        // Recurse up the parent hierarchy and add project directories to the search roots
        MavenProject parent = project;
        while (parent != null && parent.getFile() != null) {
            // MCHECKSTYLE-131 ( olamy ) I don't like this hack.
            // (dkulp) Me either.   It really pollutes the location stuff
            // by allowing searches of stuff outside the current module.
            File dir = parent.getFile().getParentFile();
            resourceManager.addSearchPath(FileResourceLoader.ID, dir.getAbsolutePath());
            parent = parent.getParent();
        }
        resourceManager.addSearchPath("url", "");

        // MCHECKSTYLE-225: load licenses from additional artifacts, not from classpath
        if (additionalArtifacts != null) {
            for (Artifact licenseArtifact : additionalArtifacts) {
                try {
                    // MCHECKSTYLE-287, MCHECKSTYLE-294: Ignore null licenseArtifacts ...
                    if (licenseArtifact != null) {
                        if (getLogger().isDebugEnabled()) {
                            getLogger().debug("Adding licenceArtifact [" + licenseArtifact.getGroupId() + ":"
                                    + licenseArtifact.getArtifactId() + ":" + licenseArtifact.getVersion()
                                    + "] to resourceManager.");
                        }
                        resourceManager.addSearchPath("jar", "jar:" + licenseArtifact.getFile().toURI().toURL());
                    }
                } catch (MalformedURLException e) {
                    // noop
                }
            }
        }
    }

Configures search paths in the resource locator.
This method should only be called once per execution.

@param request executor request data.

Configures search paths in the resource locator . This method should only be called once per execution .


public T build(Object... attributes) {
        List<Object> attributeList = new ArrayList<Object>(Arrays.asList(attributes)); //kinda wacky but Arrays.asList returns a unmodifiable list

        String[] traitNames = getTraitNames(attributeList);
        applyTraits(traitNames);

        T object = ReflectionUtils.createObject(factoryClass, constructorArgs);

        // merge default properties with supplied attributes
        Map<String, Object> propertyValues = createObjectPropertyValues(this.propertyValues, attributeList);

        // now set properties and fields to the created object
        setProperties(object, propertyValues);
        setFields(object, fieldValues);

        executeCallbacks(AfterFactoryBuild.class, object);
        return object;
    }


private Map<String, Object> createObjectPropertyValues(Map<String, Object> defaultPropertyValues, List<Object> attributes) {
        Map<String, Object> propertyValues = new HashMap<String, Object>(defaultPropertyValues);

        if(attributes != null) {
            Iterator<Object> iterator = attributes.iterator();
            Map<String, Object> propertyOverrideMap = new HashMap<String, Object>();

            while(iterator.hasNext()) {
                String name = (String)iterator.next();

                // we can only create a map entry if we have both a key and value, so make sure there's a value left
                if(iterator.hasNext()) {
                    Object object = iterator.next();
                    propertyOverrideMap.put(name, object);
                }
            }

            propertyValues.putAll(propertyOverrideMap);
        }

        return propertyValues;
    }

Merge passed attributes with the supplied property values.
@param defaultPropertyValues
@param attributes
@return

Merge passed attributes with the supplied property values .


private int currentSequence(String name) {
        Map<String, Integer> sequencesForClass = sequences.get(getClass());
        if(sequencesForClass == null) {
            sequencesForClass = new HashMap<String, Integer>();
            sequences.put(getClass(), sequencesForClass);
        }

        Integer seq = sequencesForClass.get(name);
        seq = seq == null ? 1 : seq + 1;

        sequencesForClass.put(name, seq);
        return seq;
    }

private int currentSequence ( String name ) { Map < String , Integer > sequencesForClass = sequences . get ( getClass ( ) ) ; if ( sequencesForClass == null ) { sequencesForClass = new HashMap < String , Integer > ( ) ; sequences . put ( getClass ( ) , sequencesForClass ) ; } Integer seq = sequencesForClass . get ( name ) ; seq = seq == null ? 1 : seq + 1 ; sequencesForClass . put ( name , seq ) ; return seq ; }

Retrieve the current sequence value for the given property.
@param name name of the property that should be assigned the sequence value.
@return The current value of the referenced sequence.

Retrieve the current sequence value for the given property .


@Override
    public int compareTo(final NodeID that) {

        // Fail fast
        if (that == this) {
            return 0;
        } else if (null == that) {
            return -1;
        }

        // Delegate to internal state
        return this.getId().compareTo(that.getId());
    }

@
Override
public
int
compareTo
(
final
NodeID
that
)
{
// Fail fast
if
(
that
==
this
)
{
return
0
;
}
else
if
(
==
that
)
{
return
1
;
}
// Delegate to internal state
return
this
.
getId
(
)
.
compareTo
(
that
.
getId
(
)
)
;
}

Compares the supplied NodeID to this one.

@param that A NodeID to compare to this one.
@return THe difference in

Compares the supplied NodeID to this one .


public List<NodeEvent> getAndClearEventslist() {
		ArrayList<NodeEvent> result = new ArrayList<NodeEvent>(eventslist);
		eventslist.clear();
		return result;
	}

public List < NodeEvent > getAndClearEventslist ( ) { ArrayList < NodeEvent > result = new ArrayList < NodeEvent > ( eventslist ) ; eventslist . clear ( ) ; return result ; }

Gets the copy of the buffer and clears the buffer.

@return - the copy of events since the last call of this method.

Gets the copy of the buffer and clears the buffer .


public SortedSet<PackageDoc> findPackagesFromClassesInJavaDocRun() {

        final SortedSet<PackageDoc> toReturn = new TreeSet<>(Comparators.PACKAGE_NAME_COMPARATOR);
        final ClassDoc[] currentExecutionClasses = classes();

        if (currentExecutionClasses != null) {

            Arrays.stream(currentExecutionClasses)
                    .map(ProgramElementDoc::containingPackage)
                    .forEach(toReturn::add);
        }

        // All Done.
        return toReturn;
    }

public
SortedSet
<
PackageDoc
>
findPackagesFromClassesInJavaDocRun
(
)
{
final
SortedSet
<
PackageDoc
>
toReturn
=
new
TreeSet
<>
(
Comparators
.
PACKAGE_NAME_COMPARATOR
)
;
final
ClassDoc
[
]
currentExecutionClasses
=
classes
(
)
;
if
(
currentExecutionClasses
!=
)
{
Arrays
.
stream
(
currentExecutionClasses
)
.
map
(
ProgramElementDoc
::
containingPackage
)
.
forEach
(
toReturn
::
add
)
;
}
// All Done.
return
toReturn
;
}

Finds all PackageDoc objects from the classes in this JavaDoc execution.

@return a non-null (but possibly empty) SortedSet containing all {@link PackageDoc}s from the current execution.

Finds all PackageDoc objects from the classes in this JavaDoc execution .


public static boolean setProperty(Object target, String name, Object value) {
        try {
            for (PropertyDescriptor pd : Introspector.getBeanInfo(target.getClass()).getPropertyDescriptors()) {
                if (pd.getWriteMethod() != null && pd.getName().equals(name)) {
                    pd.getWriteMethod().invoke(target, value);
                    return true;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return false;
    }

public static boolean setProperty ( Object target , String name , Object value ) { try { for ( PropertyDescriptor pd : Introspector . getBeanInfo ( target . getClass ( ) ) . getPropertyDescriptors ( ) ) { if ( pd . getWriteMethod ( ) != null && pd . getName ( ) . equals ( name ) ) { pd . getWriteMethod ( ) . invoke ( target , value ) ; return true ; } } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } return false ; }

Set the property identified by name to the provided value.
@param target
@param name
@param value
@return true on success, false if property wasn't found.

Set the property identified by name to the provided value .


public static boolean setField(Object target, String name, Object value) {
        try {
            Field field = target.getClass().getDeclaredField(name);
            field.setAccessible(true);
            field.set(target, value);
            return true;
        } catch (NoSuchFieldException e) {
            return false;
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

public static boolean setField ( Object target , String name , Object value ) { try { Field field = target . getClass ( ) . getDeclaredField ( name ) ; field . setAccessible ( true ) ; field . set ( target , value ) ; return true ; } catch ( NoSuchFieldException e ) { return false ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }

Set the field identified by name to the given value.
@param target
@param name
@param value
@return true on success, false if field wasn't found.

Set the field identified by name to the given value .


public static List<Method> getAnnotatedMethods(Class targetClass, Class<? extends Annotation> annotationType) {
        List<Method> annotatedMethods = new ArrayList<Method>();

        for(Method method : targetClass.getDeclaredMethods()) {
            if(method.isAnnotationPresent(annotationType)) {
                annotatedMethods.add(method);
            }
        }

        return annotatedMethods;
    }

public static List < Method > getAnnotatedMethods ( Class targetClass , Class < ? extends Annotation > annotationType ) { List < Method > annotatedMethods = new ArrayList < Method > ( ) ; for ( Method method : targetClass . getDeclaredMethods ( ) ) { if ( method . isAnnotationPresent ( annotationType ) ) { annotatedMethods . add ( method ) ; } } return annotatedMethods ; }

Get all methods on the given class that are annotated with the given annotation type.
@param targetClass
@param annotationType
@return

Get all methods on the given class that are annotated with the given annotation type .


public static void invokeMethod(Object target, Method method, Object... arguments) {
        method.setAccessible(true); // so we can call private and protected methods too

        try {
            method.invoke(target, arguments);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

Invoke the given method on the given target using the given arguments.
Allows to call private and protected methods.
@throws RuntimeException if method could not be invoked.
@param target
@param method
@param arguments

Invoke the given method on the given target using the given arguments . Allows to call private and protected methods .


public static void main(String[] args) throws Exception {
		if (args.length > 0) {
			loadClasses(args[0]);
		}

		startCacheServer();

		ConsoleUtils
				.waitForEnter(JavaProcessLauncher.PROCESS_STARTUP_COMPLETED);

		stopCacheServer();
	}

public static void main ( String [ ] args ) throws Exception { if ( args . length > 0 ) { loadClasses ( args [ 0 ] ) ; } startCacheServer ( ) ; ConsoleUtils . waitForEnter ( JavaProcessLauncher . PROCESS_STARTUP_COMPLETED ) ; stopCacheServer ( ) ; }

Server entry point.

@param args
of type String[]


private String getConfigAttribute(Configuration config, ChainedItem<Configuration> parentConfiguration,
                                      String attributeName, String defaultValue) {
        String ret;
        try {
            ret = config.getAttribute(attributeName);
        } catch (CheckstyleException e) {
            // Try to find the attribute in a parent, if there are any
            if (parentConfiguration != null) {
                ret =
                        getConfigAttribute(parentConfiguration.value, parentConfiguration.parent, attributeName,
                                defaultValue);
            } else {
                ret = defaultValue;
            }
        }
        return ret;
    }

Get the value of the specified attribute from the Checkstyle configuration.
If parentConfigurations is non-null and non-empty, the parent
configurations are searched if the attribute cannot be found in the
current configuration. If the attribute is still not found, the
specified default value will be returned.

@param config              The current Checkstyle configuration
@param parentConfiguration The configuration of the parent of the current configuration
@param attributeName       The name of the attribute
@param defaultValue        The default value to use if the attribute cannot be found in any configuration
@return The value of the specified attribute

Get the value of the specified attribute from the Checkstyle configuration . If parentConfigurations is non - null and non - empty the parent configurations are searched if the attribute cannot be found in the current configuration . If the attribute is still not found the specified default value will be returned .


private void doRulesSummary(CheckstyleResults results) {
        if (checkstyleConfig == null) {
            return;
        }

        sink.section1();
        sink.sectionTitle1();
        sink.text(bundle.getString("report.checkstyle.rules"));
        sink.sectionTitle1_();

        sink.table();

        sink.tableRow();
        sink.tableHeaderCell();
        sink.text(bundle.getString("report.checkstyle.rule.category"));
        sink.tableHeaderCell_();

        sink.tableHeaderCell();
        sink.text(bundle.getString("report.checkstyle.rule"));
        sink.tableHeaderCell_();

        sink.tableHeaderCell();
        sink.text(bundle.getString("report.checkstyle.violations"));
        sink.tableHeaderCell_();

        sink.tableHeaderCell();
        sink.text(bundle.getString("report.checkstyle.column.severity"));
        sink.tableHeaderCell_();

        sink.tableRow_();

        // Top level should be the checker.
        if ("checker".equalsIgnoreCase(checkstyleConfig.getName())) {
            String category = null;
            for (ConfReference ref : sortConfiguration(results)) {
                doRuleRow(ref, results, category);

                category = ref.category;
            }
        } else {
            sink.tableRow();
            sink.tableCell();
            sink.text(bundle.getString("report.checkstyle.norule"));
            sink.tableCell_();
            sink.tableRow_();
        }

        sink.table_();

        sink.section1_();
    }

private
void
doRulesSummary
(
CheckstyleResults
results
)
{
if
(
checkstyleConfig
==
)
{
return
;
}
sink
.
section1
(
)
;
sink
.
sectionTitle1
(
)
;
sink
.
text
(
bundle
.
getString
(
"report.checkstyle.rules"
)
)
;
sink
.
sectionTitle1_
(
)
;
sink
.
table
(
)
;
sink
.
tableRow
(
)
;
sink
.
tableHeaderCell
(
)
;
sink
.
text
(
bundle
.
getString
(
"report.checkstyle.rule.category"
)
)
;
sink
.
tableHeaderCell_
(
)
;
sink
.
tableHeaderCell
(
)
;
sink
.
text
(
bundle
.
getString
(
"report.checkstyle.rule"
)
)
;
sink
.
tableHeaderCell_
(
)
;
sink
.
tableHeaderCell
(
)
;
sink
.
text
(
bundle
.
getString
(
"report.checkstyle.violations"
)
)
;
sink
.
tableHeaderCell_
(
)
;
sink
.
tableHeaderCell
(
)
;
sink
.
text
(
bundle
.
getString
(
"report.checkstyle.column.severity"
)
)
;
sink
.
tableHeaderCell_
(
)
;
sink
.
tableRow_
(
)
;
// Top level should be the checker.
if
(
"checker"
.
equalsIgnoreCase
(
checkstyleConfig
.
getName
(
)
)
)
{
String
category
=
;
for
(
ConfReference
ref
:
sortConfiguration
(
results
)
)
{
doRuleRow
(
ref
,
results
,
category
)
;
category
=
ref
.
category
;
}
}
else
{
sink
.
tableRow
(
)
;
sink
.
tableCell
(
)
;
sink
.
text
(
bundle
.
getString
(
"report.checkstyle.norule"
)
)
;
sink
.
tableCell_
(
)
;
sink
.
tableRow_
(
)
;
}
sink
.
table_
(
)
;
sink
.
section1_
(
)
;
}

Create the rules summary section of the report.

@param results The results to summarize

Create the rules summary section of the report .


public boolean matchRule(AuditEvent event, String ruleName, String expectedMessage, String expectedSeverity) {
        if (!ruleName.equals(RuleUtil.getName(event))) {
            return false;
        }

        // check message too, for those that have a specific one.
        // like GenericIllegalRegexp and Regexp
        if (expectedMessage != null) {
            // event.getMessage() uses java.text.MessageFormat in its implementation.
            // Read MessageFormat Javadoc about single quote:
            // http://java.sun.com/j2se/1.4.2/docs/api/java/text/MessageFormat.html
            String msgWithoutSingleQuote = StringUtils.replace(expectedMessage, "'", "");

            return expectedMessage.equals(event.getMessage()) || msgWithoutSingleQuote.equals(event.getMessage());
        }
        // Check the severity. This helps to distinguish between
        // different configurations for the same rule, where each
        // configuration has a different severity, like JavadocMetod.
        // See also http://jira.codehaus.org/browse/MCHECKSTYLE-41
        if (expectedSeverity != null) {
            return expectedSeverity.equals(event.getSeverityLevel().getName());
        }

        return true;
    }

Check if a violation matches a rule.

@param event            the violation to check
@param ruleName         The name of the rule
@param expectedMessage  A message that, if it's not null, will be matched to the message from the violation
@param expectedSeverity A severity that, if it's not null, will be matched to the severity from the violation
@return The number of rule violations


private String createReceivedAtKey(String fromClusterName,
		String toClusterName) {

		return KEY_PREFIX + fromClusterName + "-" + toClusterName
			+ KEY_POSTFIX_DURATION;
	}

private String createReceivedAtKey ( String fromClusterName , String toClusterName ) { return KEY_PREFIX + fromClusterName + "-" + toClusterName + KEY_POSTFIX_DURATION ; }

Creates the receivedAt key

@param fromClusterName
- the name of cluster from which the entry received
@param toClusterName
- the name of cluster on which the entry received
@return - the receivedAt key


private void init() {
		try {
			debug("GuestNode#init(): Creating Cache");

			ClientCacheFactory clientCacheFactory = new ClientCacheFactory();

			Properties gemfireProperties = PropertiesHelper.filterProperties(
				System.getProperties(), GEMFIRE_PREFIX);

			for (Object keyObject : gemfireProperties.keySet()) {
				String key = (String) keyObject;
				String value = gemfireProperties.getProperty(key);

				String name = key.substring(GEMFIRE_PREFIX.length());

				debug("GuestNode#init(): Configuring ClientCacheFactory with key = "
					+ name + ", value = " + value);

				clientCacheFactory.set(name, value);
			}

			clientCacheFactory.setPoolSubscriptionEnabled(true);

			String locators = clustersProperties.getProperty(localClusterName);
			String[] locatorsArray = locators.split(",");
			for (String locator : locatorsArray) {
				String locatorHost = locator.substring(0, locator.indexOf("["));

				String locatorPortString = locator.substring(
					locator.indexOf("[") + 1, locator.indexOf("]"));
				int locatorPort = Integer.parseInt(locatorPortString);

				debug("GuestNode#init(): Adding locator to pool: locatorHost = "
					+ locatorHost + ", locatorPort = " + locatorPort);

				clientCacheFactory.addPoolLocator(locatorHost, locatorPort);
			}

			clientCache = clientCacheFactory.create();

			ClientRegionFactory<String, Long> clientRegionFactory = clientCache
				.createClientRegionFactory(ClientRegionShortcut.PROXY);

			region = clientCache.getRegion(regionName);

			debug("GuestNode#init(): Get region with name = " + regionName
				+ ": region = " + region);

			if (region == null) {
				region = clientRegionFactory.create(regionName);
			}
			debug("GuestNode#init(): Create region with name = " + regionName
				+ ": region = " + region);

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

		}
	}


private void waitForStarted() {
		debug("GuestNode#waitForStarted(): Waiting for other clusters started");

		while (true) {
			boolean othersStarted = true;

			for (Object key : clustersProperties.keySet()) {
				String clusterName = (String) key;

				Long startedAt = region.get(createStartedAtKey(clusterName));

				debug("GuestNode#waitForStarted(): Checking startedAt: startedAt = "
					+ startedAt
					+ ", processingStartedAt = "
					+ processingStartedAt);

				if ((startedAt == null)
					|| (startedAt.longValue() < processingStartedAt)) {

					othersStarted = false;
					break;

				}
			}

			if (othersStarted) {
				break;
			}

			try {
				TimeUnit.MILLISECONDS.sleep(CHECK_PERIOD);
			} catch (InterruptedException e) {
			}
		}

		debug("GuestNode#waitForStarted(): Other clusters started");
	}


private void waitForSent() {
		debug("GuestNode#waitForSent(): Waiting for other clusters sent");

		while (true) {
			boolean othersSent = true;

			Map<String, Long> clusterNameToReceivedAtMap = new HashMap<String, Long>();
			for (Object key : clustersProperties.keySet()) {
				String clusterName = (String) key;

				if (localClusterName.equals(clusterName)) {
					continue;
				}

				Long sentAt = region.get(createSentAtKey(clusterName));
				long receivedAt = System.currentTimeMillis();

				if ((sentAt != null)
					&& (sentAt.longValue() > processingStartedAt)) {

					clusterNameToReceivedAtMap.put(clusterName, receivedAt);
				}
			}

			for (Object key : clustersProperties.keySet()) {
				String clusterName = (String) key;

				if (localClusterName.equals(clusterName)) {
					continue;
				}

				Long receivedAt = clusterNameToReceivedAtMap.get(clusterName);

				if (receivedAt == null) {

					if (othersSent) {
						othersSent = false;
					}

				} else {
					region.put(
						createReceivedAtKey(clusterName, localClusterName),
						receivedAt);
				}
			}

			if (othersSent) {
				break;
			}

			try {
				TimeUnit.MILLISECONDS.sleep(CHECK_PERIOD);
			} catch (InterruptedException e) {
			}
		}

		debug("GuestNode#waitForSent(): Other clusters sent");
	}

Wait until received all the entries from other clients. Put the
receivedAt entries to cache.

Wait until received all the entries from other clients . Put the receivedAt entries to cache .


private void waitForConnected() {
		debug("GuestNode#waitForConnected(): Waiting for all the clusters connected");

		while (true) {
			boolean connected = true;

			for (Object fromKey : clustersProperties.keySet()) {
				String fromClusterName = (String) fromKey;

				for (Object toKey : clustersProperties.keySet()) {
					String toClusterName = (String) toKey;

					if (fromClusterName.equals(toClusterName)) {
						continue;
					}

					Long receivedAt = region.get(createReceivedAtKey(
						fromClusterName, toClusterName));

					if (receivedAt == null) {
						connected = false;
						break;
					}
				}
			}

			if (connected) {
				break;
			}

			try {
				TimeUnit.MILLISECONDS.sleep(CHECK_PERIOD);
			} catch (InterruptedException e) {
			}
		}

		debug("GuestNode#waitForConnected(): All the clusters connected");
	}

Wait until all the clients received all the receivedAt entries.

Wait until all the clients received all the receivedAt entries .


public boolean waitFor(long timeout) {
		debug("GuestNode#waitFor(long): Waiting for task finish with timeout = "
			+ timeout);

		ProcessingTask connectionCheckTask = new ProcessingTask();

		Utils.execute(connectionCheckTask, timeout);

		boolean connected = connectionCheckTask.isConnected();

		debug("GuestNode#waitFor(long): Task finished connected = " + connected);

		return connected;
	}

Waits for processing finished.

@param timeout
- the timeout in milliseconds
@return - true if the connection process finished successfully, false
otherwise


public void close() {
		try {
			debug("GuestNode#close(): Closing the cache");

			clientCache.close();

			debug("GuestNode#close(): Cache closed = " + clientCache.isClosed());
		} catch (Throwable t) {
			debug(
				"GuestNode#close(): Throwable caught with message = "
					+ t.getMessage(), t);
		}
	}


public void printState(boolean connected) {
		if (!quiet) {

			StringBuilder sb = new StringBuilder();

			if (connected) {

				sb.append(localClusterName).append(" <= ");

				Iterator<Object> it = clustersProperties.keySet().iterator();
				while (it.hasNext()) {
					String clusterName = (String) it.next();

					if (localClusterName.equals(clusterName)) {
						continue;
					}

					Long sentAt = region.get(createSentAtKey(clusterName));
					Long receivedAt = region.get(createReceivedAtKey(
						clusterName, localClusterName));

					long duration = receivedAt - sentAt;

					sb.append("[").append(clusterName).append(", ")
						.append(duration).append("ms]");
				}

			} else {

				sb.append("Connection process is not finished for ").append(
					localClusterName);

			}

			System.out.println(sb.toString());

		}
	}

Prints the current state of connections

@param connected


public static void main(String[] args) {
		try {
			if (args.length != 7) {
				Utils.exitWithFailure();
			}

			String cluster = args[0];
			Properties clustersProperties = PropertiesHelper
				.stringToProperties(args[1]);
			long timeout = Long.parseLong(args[2]);
			String regionName = args[3];
			boolean debugEnabled = ("true".equals(args[4]) ? true : false);
			boolean quiet = ("true".equals(args[5]) ? true : false);
			long processingStartedAt = Long.parseLong(args[6]);

			GuestNode guestNode = new GuestNode(cluster, clustersProperties,
				regionName, debugEnabled, quiet, processingStartedAt);

			boolean connected = guestNode.waitFor(timeout);

			guestNode.printState(connected);

			guestNode.close();

			if (connected) {
				Utils.exitWithSuccess();
			}

			Utils.exitWithFailure();
		} catch (Throwable t) {
			Utils.exitWithFailure();
		}
	}

public static void main ( String [ ] args ) { try { if ( args . length != 7 ) { Utils . exitWithFailure ( ) ; } String cluster = args [ 0 ] ; Properties clustersProperties = PropertiesHelper . stringToProperties ( args [ 1 ] ) ; long timeout = Long . parseLong ( args [ 2 ] ) ; String regionName = args [ 3 ] ; boolean debugEnabled = ( "true" . equals ( args [ 4 ] ) ? true : false ) ; boolean quiet = ( "true" . equals ( args [ 5 ] ) ? true : false ) ; long processingStartedAt = Long . parseLong ( args [ 6 ] ) ; GuestNode guestNode = new GuestNode ( cluster , clustersProperties , regionName , debugEnabled , quiet , processingStartedAt ) ; boolean connected = guestNode . waitFor ( timeout ) ; guestNode . printState ( connected ) ; guestNode . close ( ) ; if ( connected ) { Utils . exitWithSuccess ( ) ; } Utils . exitWithFailure ( ) ; } catch ( Throwable t ) { Utils . exitWithFailure ( ) ; } }

Configures and starts the guest node

@param args
- the configuration arguments


public List<XProperty> getOrderedProperties() {
        final List<XProperty> result = Introspector.getProperties(clazz);
        Collections.sort(result, new XProperty.NaturalOrder());
        return result;
    }

public List < XProperty > getOrderedProperties ( ) { final List < XProperty > result = Introspector . getProperties ( clazz ) ; Collections . sort ( result , new XProperty . NaturalOrder ( ) ) ; return result ; }

Returns properties in "natural" order, i.e. "ORDER BY VERSION, DECLARING CLASS, NAME"

@return

Returns properties in natural order i . e . &quot ; ORDER BY VERSION DECLARING CLASS NAME&quot ;


public short getVersionModelHashCode(int version) {
    	List<XProperty> classFields = getOrderedProperties();

        StringBuilder builder = new StringBuilder();
        for (XProperty field : classFields) {
            if (version == -1 || version >= field.getPropertyVersion()) {
                builder.append(field.getType()).append(field.getName());
            }
        }
        int hashCode = builder.toString().hashCode();
		return (short) ((hashCode & 0xFFFF ) ^ ((hashCode & 0xFFFF0000) >> 16)) ;
    }

public short getVersionModelHashCode ( int version ) { List < XProperty > classFields = getOrderedProperties ( ) ; StringBuilder builder = new StringBuilder ( ) ; for ( XProperty field : classFields ) { if ( version == - 1 || version >= field . getPropertyVersion ( ) ) { builder . append ( field . getType ( ) ) . append ( field . getName ( ) ) ; } } int hashCode = builder . toString ( ) . hashCode ( ) ; return ( short ) ( ( hashCode & 0xFFFF ) ^ ( ( hashCode & 0xFFFF0000 ) >> 16 ) ) ; }

Returns a hash code of class model for specified bean version based on fields that this model contains.

@param version bean version to get metadata hashcode.
@return the hashcode (16bits)

Returns a hash code of class model for specified bean version based on fields that this model contains .


public int getTotalNumberOfPages() throws QueryException {
		prepareResultData(false);
		if (isEmpty()) {
			return 1;
		}
		int total = totalNumberOfEntries / this.pageSize;
		if (totalNumberOfEntries % this.pageSize > 0) {
			total += 1;
		}
		return total;
	}

public int getTotalNumberOfPages ( ) throws QueryException { prepareResultData ( false ) ; if ( isEmpty ( ) ) { return 1 ; } int total = totalNumberOfEntries / this . pageSize ; if ( totalNumberOfEntries % this . pageSize > 0 ) { total += 1 ; } return total ; }

Returns a total number of query pages.

@return total number of pages
@throws com.gemstone.gemfire.cache.query.QueryException
during query execution


@SuppressWarnings("unchecked")
	private List<V> getValues(List<Object> entriesKeysForPage) {
		if (entriesKeysForPage.isEmpty()) {
			return Collections.emptyList();
		}
		Map<Object, V> entriesMap = queryRegion.getAll(entriesKeysForPage);

		List<V> entries = new ArrayList<V>(entriesKeysForPage.size());
		for (Object key : entriesKeysForPage) {
			entries.add(entriesMap.get(key));
		}
		return entries;
	}

@ SuppressWarnings ( "unchecked" ) private List < V > getValues ( List < Object > entriesKeysForPage ) { if ( entriesKeysForPage . isEmpty ( ) ) { return Collections . emptyList ( ) ; } Map < Object , V > entriesMap = queryRegion . getAll ( entriesKeysForPage ) ; List < V > entries = new ArrayList < V > ( entriesKeysForPage . size ( ) ) ; for ( Object key : entriesKeysForPage ) { entries . add ( entriesMap . get ( key ) ) ; } return entries ; }

Returns values for given keys.

@param entriesKeysForPage
of type List<Object>
@return List<V>


@SuppressWarnings({ "unchecked" })
	private void prepareResultData(boolean force) throws QueryException {
		if (this.infoLoaded && !force) {
			return;
		}

		PageKey pageKey = newKey(PAGE_NUMBER_FOR_GENERAL_INFO);

		List<Object> queryInfo = null;
		if (!force) {
			queryInfo = paginatedQueryInfoRegion.get(pageKey);
		}

		if (queryInfo == null) {
			Query query = queryService.newQuery(this.queryString);
			SelectResults<Object> results = null;
			try {
				results = (SelectResults<Object>) query.execute(pageKey
						.getQueryParameters());
			} catch (FunctionDomainException e) {
				handleException(e);
			} catch (TypeMismatchException e) {
				handleException(e);
			} catch (NameResolutionException e) {
				handleException(e);
			} catch (QueryInvocationTargetException e) {
				handleException(e);
			}

			if (results.size() > queryLimit) {
				this.limitExceeded = true;
				this.totalNumberOfEntries = queryLimit;
				String msg = "Size of query results has exceeded limit ("
						+ queryLimit + "). Truncated.";
				logger.warn(msg);
			} else {
				limitExceeded = false;
				this.totalNumberOfEntries = results.size();
			}

			queryInfo = Arrays.asList(new Object[] { results.size(),
					limitExceeded });
			storePage(PAGE_NUMBER_FOR_GENERAL_INFO, queryInfo);

			List<Object> keys = extractKeys(results);
			storeResults(keys);
		} else {
			this.totalNumberOfEntries = (Integer) queryInfo.get(0);
			this.limitExceeded = (Boolean) queryInfo.get(1);
		}
		this.infoLoaded = true;
	}

Stores paginated query info if it has not been stored yet.

@param force

@throws com.gemstone.gemfire.cache.query.QueryException
during query execution

Stores paginated query info if it has not been stored yet .


private void storeResults(List<Object> resultKeys) {
		if (resultKeys.size() > queryLimit) {
			resultKeys = resultKeys.subList(0, queryLimit);
		}

		int keyNumber = 0;
		int pageNumber = 0;
		List<Object> page = new ArrayList<Object>();

		for (Object key : resultKeys) {
			if (keyNumber % getPageSize() == 0 && keyNumber != 0) {
				storePage(++pageNumber, page);
				page.clear();
			}
			page.add(key);
			keyNumber++;
		}

		if (page.size() > 0 || pageNumber == 0) {
			storePage(++pageNumber, page);
		}
	}

private void storeResults ( List < Object > resultKeys ) { if ( resultKeys . size ( ) > queryLimit ) { resultKeys = resultKeys . subList ( 0 , queryLimit ) ; } int keyNumber = 0 ; int pageNumber = 0 ; List < Object > page = new ArrayList < Object > ( ) ; for ( Object key : resultKeys ) { if ( keyNumber % getPageSize ( ) == 0 && keyNumber != 0 ) { storePage ( ++ pageNumber , page ) ; page . clear ( ) ; } page . add ( key ) ; keyNumber ++ ; } if ( page . size ( ) > 0 || pageNumber == 0 ) { storePage ( ++ pageNumber , page ) ; } }

Stores paginated query pages and general info.

@param resultKeys
of type List<Object>

Stores paginated query pages and general info .


public T create(Object... attributes) {
        // build
        T object = build(attributes);

        // excute beforeCreate callback
        executeCallbacks(BeforeFactoryCreate.class, object);

        // persist
        persist(object);

        // execute after create callback
        executeCallbacks(AfterFactoryCreate.class, object);

        // return
        return object;
    }

public
T
create
(
Object
...
attributes
)
{
// build
T
object
=
build
(
attributes
)
;
// excute beforeCreate callback
executeCallbacks
(
BeforeFactoryCreate
.
class
,
object
)
;
// persist
persist
(
object
)
;
// execute after create callback
executeCallbacks
(
AfterFactoryCreate
.
class
,
object
)
;
// return
return
object
;
}

Create an object with the given attributes.
First builds the object, than persists it.
@param attributes
@return

Create an object with the given attributes . First builds the object than persists it .


@Override
    public int compare(final TagToCategory o1, final TagToCategory o2) {
        if (o1 == null && o2 == null) return 0;

        if (o1 == null) return lessThan;

        if (o2 == null) return greaterThan;

        if (o1.getSorting() == null && o2.getSorting() == null) return compareSecondLevel(o1, o2);

        if (o1.getSorting() == null) return greaterThan;
        if (o2.getSorting() == null) return lessThan;

        if (o1.getSorting().equals(o2.getSorting())) return compareSecondLevel(o1, o2);

        return o1.getSorting().compareTo(o2.getSorting()) * greaterThan;
    }

@ Override public int compare ( final TagToCategory o1 , final TagToCategory o2 ) { if ( o1 == null && o2 == null ) return 0 ; if ( o1 == null ) return lessThan ; if ( o2 == null ) return greaterThan ; if ( o1 . getSorting ( ) == null && o2 . getSorting ( ) == null ) return compareSecondLevel ( o1 , o2 ) ; if ( o1 . getSorting ( ) == null ) return greaterThan ; if ( o2 . getSorting ( ) == null ) return lessThan ; if ( o1 . getSorting ( ) . equals ( o2 . getSorting ( ) ) ) return compareSecondLevel ( o1 , o2 ) ; return o1 . getSorting ( ) . compareTo ( o2 . getSorting ( ) ) * greaterThan ; }

Sorting order is preferentially used to sort TagToCategory's, or the name of the Tag that
the TagToCategory's point to are used if both TagToCategory's sorting orders are null.

Sorting order is preferentially used to sort TagToCategory s or the name of the Tag that the TagToCategory s point to are used if both TagToCategory s sorting orders are null .


private void migrateBrokenLocales(final PreparedStatement preparedStmt, final Map<String, Integer> localeMap) throws SQLException {
        final Integer enUSLocaleID = localeMap.get("en-US");
        if (enUSLocaleID != null && enUSLocaleID > 0) {
            migrateBrokenLocale(preparedStmt, localeMap, "es_US", enUSLocaleID);
            migrateBrokenLocale(preparedStmt, localeMap, "en_AU", enUSLocaleID);
            migrateBrokenLocale(preparedStmt, localeMap, "ar", enUSLocaleID);
            migrateBrokenLocale(preparedStmt, localeMap, "as", enUSLocaleID);
        }
    }

private void migrateBrokenLocales ( final PreparedStatement preparedStmt , final Map < String , Integer > localeMap ) throws SQLException { final Integer enUSLocaleID = localeMap . get ( "en-US" ) ; if ( enUSLocaleID != null && enUSLocaleID > 0 ) { migrateBrokenLocale ( preparedStmt , localeMap , "es_US" , enUSLocaleID ) ; migrateBrokenLocale ( preparedStmt , localeMap , "en_AU" , enUSLocaleID ) ; migrateBrokenLocale ( preparedStmt , localeMap , "ar" , enUSLocaleID ) ; migrateBrokenLocale ( preparedStmt , localeMap , "as" , enUSLocaleID ) ; } }

Migrates locales from a very early version of PressGang that was using the wrong locale value.

@param preparedStmt
@param localeMap
@throws SQLException

Migrates locales from a very early version of PressGang that was using the wrong locale value .


public static boolean recalculateMinHash(final Topic topic, final List<MinHashXOR> minHashXORs) {
        boolean retValue = false;

        final Set<MinHash> existingMinHashes = topic.getMinHashes();

        final Map<Integer, Integer> minHashes = getMinHashes(topic.getTopicXML(), minHashXORs);

        for (final Integer funcId : minHashes.keySet()) {

            boolean found = false;
            for (final MinHash minHash : existingMinHashes) {
                if (minHash.getMinHashFuncID().equals(funcId)) {
                    if (!minHash.getMinHash().equals(minHashes.get(funcId))) {
                        minHash.setMinHash(minHashes.get(funcId));
                        retValue = true;
                    }
                    found = true;
                    break;
                }
            }

            if (!found) {
                retValue = true;
                final MinHash minHash = new MinHash();
                minHash.setMinHashFuncID(funcId);
                minHash.setMinHash(minHashes.get(funcId));
                topic.addMinHash(minHash);
            }
        }

        return retValue;
    }

public static boolean recalculateMinHash ( final Topic topic , final List < MinHashXOR > minHashXORs ) { boolean retValue = false ; final Set < MinHash > existingMinHashes = topic . getMinHashes ( ) ; final Map < Integer , Integer > minHashes = getMinHashes ( topic . getTopicXML ( ) , minHashXORs ) ; for ( final Integer funcId : minHashes . keySet ( ) ) { boolean found = false ; for ( final MinHash minHash : existingMinHashes ) { if ( minHash . getMinHashFuncID ( ) . equals ( funcId ) ) { if ( ! minHash . getMinHash ( ) . equals ( minHashes . get ( funcId ) ) ) { minHash . setMinHash ( minHashes . get ( funcId ) ) ; retValue = true ; } found = true ; break ; } } if ( ! found ) { retValue = true ; final MinHash minHash = new MinHash ( ) ; minHash . setMinHashFuncID ( funcId ) ; minHash . setMinHash ( minHashes . get ( funcId ) ) ; topic . addMinHash ( minHash ) ; } } return retValue ; }

Recalculate the min hash signature for a topic.
@param topic The topic to generate a signature for
@param minHashXORs The list of XOR values to apply to the hash code
@return true if the minhashes were updated, false otherwise

Recalculate the min hash signature for a topic .


public static Map<Integer, Integer> getMinHashes(final String xml, final List<MinHashXOR> minHashXORs) {
        final Map<Integer, Integer> retValue = new HashMap<Integer, Integer>();

        // Clean the XML to remove element names and other useless data
        final String cleanedXML = cleanXMLForMinHash(xml);

        // the first minhash uses the builtin hashcode only
        final Integer baseMinHash = getMinHashInternal(cleanedXML, null);
        if (baseMinHash != null) {
            retValue.put(0, baseMinHash);
        }

        for (int funcId = 1; funcId < org.jboss.pressgang.ccms.model.constants.Constants.NUM_MIN_HASHES; ++funcId) {
            boolean foundMinHash = false;
            for (final MinHashXOR minHashXOR : minHashXORs) {
                if (minHashXOR.getMinHashXORFuncId() == funcId) {
                    final Integer minHash = getMinHashInternal(cleanedXML, minHashXOR.getMinHashXOR());
                    if (minHash != null) {
                        retValue.put(funcId, minHash);
                    }
                    foundMinHash = true;
                    break;
                }
            }
            if (!foundMinHash) {
                throw new IllegalStateException("Did not find a minhash xor int for function " + funcId);
            }
        }

        return retValue;
    }

Generate the min hashes
@param xml The content to apply the signature to
@param minHashXORs The list of XOR values to apply to the hash code
@return


protected static String cleanXMLForMinHash(final String xml) {
        // Treat null and empty strings the same
        final String fixedXML = xml == null ? "" : xml;

        String text = null;
        try {
            final Document doc = XMLUtilities.convertStringToDocument(fixedXML);
            if (doc != null) {
                text = doc.getDocumentElement().getTextContent();
            }
        } catch (final Exception ex) {
            // Do nothing
        }

        // the xml was invalid, so just strip out xml elements manually
        if (text == null) {
            text = fixedXML.replaceAll("</?.*?/?>", " ");
        }

        return text;
    }

Cleans the provided XML by removing element names and other useless data.

@param xml The xml to be cleaned.
@return The cleaned xml.

Cleans the provided XML by removing element names and other useless data .


public static void validateAndFixRelationships(final Topic topic) {
        /* remove relationships to this topic in the parent collection */
        final ArrayList<TopicToTopic> removeList = new ArrayList<TopicToTopic>();
        for (final TopicToTopic topicToTopic : topic.getParentTopicToTopics())
            if (topicToTopic.getRelatedTopic().getTopicId().equals(topic.getTopicId())) removeList.add(topicToTopic);

        for (final TopicToTopic topicToTopic : removeList)
            topic.getParentTopicToTopics().remove(topicToTopic);

        /* remove relationships to this topic in the child collection */
        final ArrayList<TopicToTopic> removeChildList = new ArrayList<TopicToTopic>();
        for (final TopicToTopic topicToTopic : topic.getChildTopicToTopics())
            if (topicToTopic.getMainTopic().getTopicId().equals(topic.getTopicId())) removeChildList.add(topicToTopic);

        for (final TopicToTopic topicToTopic : removeChildList)
            topic.getChildTopicToTopics().remove(topicToTopic);
    }

Validate and Fix a topics relationships to ensure that the topics related topics are still matched by the Related Topics
themselves.

@param topic The topic to validate and fix the relationships for.

Validate and Fix a topics relationships to ensure that the topics related topics are still matched by the Related Topics themselves .


public static void updateContentHash(final Topic topic) {
        if (topic.getTopicXML() != null) {
            topic.setTopicContentHash(HashUtilities.generateSHA256(topic.getTopicXML()).toCharArray());
        }
    }

public static void updateContentHash ( final Topic topic ) { if ( topic . getTopicXML ( ) != null ) { topic . setTopicContentHash ( HashUtilities . generateSHA256 ( topic . getTopicXML ( ) ) . toCharArray ( ) ) ; } }

Set the content hash on the topic.
@param topic The topic to update


public static void validateAndFixTags(final Topic topic) {
        /*
         * validate the tags that are applied to this topic. generally the gui should enforce these rules, with the exception of
         * the bulk tag apply function
         */

        // Create a collection of Categories mapped to TagToCategories, sorted by the Category sorting order
        final TreeMap<Category, ArrayList<TagToCategory>> tagDB = new TreeMap<Category, ArrayList<TagToCategory>>(
                Collections.reverseOrder());

        for (final TopicToTag topicToTag : topic.getTopicToTags()) {
            final Tag tag = topicToTag.getTag();
            for (final TagToCategory tagToCategory : tag.getTagToCategories()) {
                final Category category = tagToCategory.getCategory();

                if (!tagDB.containsKey(category)) tagDB.put(category, new ArrayList<TagToCategory>());

                tagDB.get(category).add(tagToCategory);
            }
        }

        // now remove conflicting tags
        for (final Category category : tagDB.keySet()) {
            /* sort by the tags position in the category */
            Collections.sort(tagDB.get(category), new TagToCategorySortingComparator(false));

            /*
             * because of the way we have ordered the tagDB collections, and the ArrayLists it contains, this process will
             * remove those tags that belong to lower priority categories, and lower priority tags in those categories
             */

            final ArrayList<TagToCategory> tagToCategories = tagDB.get(category);

            // remove tags in the same mutually exclusive categories
            if (category.isMutuallyExclusive() && tagToCategories.size() > 1) {
                while (tagToCategories.size() > 1) {
                    final TagToCategory tagToCategory = tagToCategories.get(1);
                    /* get the lower priority tag */
                    final Tag removeTag = tagToCategory.getTag();
                    /* remove it from the tagDB collection */
                    tagToCategories.remove(tagToCategory);

                    /* and remove it from the tag collection */
                    final ArrayList<TopicToTag> removeTopicToTagList = new ArrayList<TopicToTag>();
                    for (final TopicToTag topicToTag : topic.getTopicToTags()) {
                        if (topicToTag.getTag().equals(removeTag)) removeTopicToTagList.add(topicToTag);
                    }

                    for (final TopicToTag removeTopicToTag : removeTopicToTagList) {
                        topic.getTopicToTags().remove(removeTopicToTag);
                    }
                }
            }

            /* remove tags that are explicitly defined as mutually exclusive */
            for (final TagToCategory tagToCategory : tagToCategories) {
                final Tag tag = tagToCategory.getTag();
                for (final Tag exclusionTag : tag.getExcludedTags()) {
                    if (filter(having(on(TopicToTag.class).getTag(), equalTo(tagToCategory.getTag())),
                            topic.getTopicToTags()).size() != 0 && // make
                            /*
                             * sure that we have not removed this tag already
                             */
                            filter(having(on(TopicToTag.class).getTag(), equalTo(exclusionTag)),
                                    topic.getTopicToTags()).size() != 0 && // make
                            /*
                             * sure the exclusion tag exists
                             */
                            !exclusionTag.equals(tagToCategory.getTag())) // make
                    /*
                     * sure we are not trying to remove ourselves
                     */ {
                        with(topic.getTopicToTags()).remove(having(on(TopicToTag.class).getTag(), equalTo(exclusionTag)));
                    }
                }
            }
        }
    }

/*
                             * sure the exclusion tag exists
                             */

Validate and Fix a topics tags so that mutually exclusive tags are enforced and also remove any tags that may have been
duplicated.

@param topic The topic to fix the tags for.

Validate and Fix a topics tags so that mutually exclusive tags are enforced and also remove any tags that may have been duplicated .


public static SortedMap<PackageDoc, SortedSet<ClassDoc>> sortClassesPerPackage(final ClassDoc... classDocs) {

        final SortedMap<PackageDoc, SortedSet<ClassDoc>> toReturn = new TreeMap<>(Comparators.PACKAGE_NAME_COMPARATOR);

        if (classDocs != null) {

            Arrays.stream(classDocs).forEach(current -> {

                // Retrieve (or create) the SortedSet of ClassDocs for the current PackageDocs.
                final SortedSet<ClassDoc> classDocsForCurrentPackage = toReturn.computeIfAbsent(
                        current.containingPackage(),
                        k -> new TreeSet<>(Comparators.CLASS_NAME_COMPARATOR));

                // Add the current ClassDoc to the SortedSet.
                classDocsForCurrentPackage.add(current);
            });
        }

        // All Done.
        return toReturn;
    }

Sorts all given ClassDocs into a SortedMap keyed by their respective PackageDocs.

@param classDocs an array of ClassDoc objects.
@return A SortedMap relating all ClassDocs to their respective PackageDoc.

Sorts all given ClassDocs into a SortedMap keyed by their respective PackageDocs .