Class Util

java.lang.Object
org.jgroups.util.Util

public class Util extends Object
Collection of various utility routines that can not be assigned to other classes.
  • Field Details

    • TYPES

      private static final Map<Class<?>,Byte> TYPES
    • CLASS_TYPES

      private static final IntHashMap<Class<?>> CLASS_TYPES
    • TYPE_NULL

      private static final byte TYPE_NULL
      See Also:
    • TYPE_BOOLEAN

      private static final byte TYPE_BOOLEAN
      See Also:
    • TYPE_BOOLEAN_OBJ

      private static final byte TYPE_BOOLEAN_OBJ
      See Also:
    • TYPE_BYTE

      private static final byte TYPE_BYTE
      See Also:
    • TYPE_BYTE_OBJ

      private static final byte TYPE_BYTE_OBJ
      See Also:
    • TYPE_CHAR

      private static final byte TYPE_CHAR
      See Also:
    • TYPE_CHAR_OBJ

      private static final byte TYPE_CHAR_OBJ
      See Also:
    • TYPE_DOUBLE

      private static final byte TYPE_DOUBLE
      See Also:
    • TYPE_DOUBLE_OBJ

      private static final byte TYPE_DOUBLE_OBJ
      See Also:
    • TYPE_FLOAT

      private static final byte TYPE_FLOAT
      See Also:
    • TYPE_FLOAT_OBJ

      private static final byte TYPE_FLOAT_OBJ
      See Also:
    • TYPE_INT

      private static final byte TYPE_INT
      See Also:
    • TYPE_INT_OBJ

      private static final byte TYPE_INT_OBJ
      See Also:
    • TYPE_LONG

      private static final byte TYPE_LONG
      See Also:
    • TYPE_LONG_OBJ

      private static final byte TYPE_LONG_OBJ
      See Also:
    • TYPE_SHORT

      private static final byte TYPE_SHORT
      See Also:
    • TYPE_SHORT_OBJ

      private static final byte TYPE_SHORT_OBJ
      See Also:
    • TYPE_STRING

      private static final byte TYPE_STRING
      See Also:
    • TYPE_BYTEARRAY

      private static final byte TYPE_BYTEARRAY
      See Also:
    • TYPE_CLASS

      private static final byte TYPE_CLASS
      See Also:
    • TYPE_STREAMABLE

      private static final byte TYPE_STREAMABLE
      See Also:
    • TYPE_SERIALIZABLE

      private static final byte TYPE_SERIALIZABLE
      See Also:
    • MAX_PORT

      public static final int MAX_PORT
      See Also:
    • METHOD_NAME_TO_ATTR_NAME_PATTERN

      private static final Pattern METHOD_NAME_TO_ATTR_NAME_PATTERN
    • ATTR_NAME_TO_METHOD_NAME_PATTERN

      private static final Pattern ATTR_NAME_TO_METHOD_NAME_PATTERN
    • CCHM_INITIAL_CAPACITY

      protected static int CCHM_INITIAL_CAPACITY
    • CCHM_LOAD_FACTOR

      protected static float CCHM_LOAD_FACTOR
    • CCHM_CONCURRENCY_LEVEL

      protected static int CCHM_CONCURRENCY_LEVEL
    • DEFAULT_HEADERS

      public static final int DEFAULT_HEADERS
    • JAVA_VERSION

      public static final String JAVA_VERSION
    • MAX_LIST_PRINT_SIZE

      public static int MAX_LIST_PRINT_SIZE
      The max size of an address list, used in View or Digest when toString() is called. Limiting this reduces the amount of log data
    • TYPE_NULL_ARRAY

      private static final byte[] TYPE_NULL_ARRAY
    • TYPE_BOOLEAN_TRUE

      private static final byte[] TYPE_BOOLEAN_TRUE
    • TYPE_BOOLEAN_FALSE

      private static final byte[] TYPE_BOOLEAN_FALSE
    • ipv4_stack_available

      private static boolean ipv4_stack_available
    • ipv6_stack_available

      private static boolean ipv6_stack_available
    • ip_stack_type

      private static final StackType ip_stack_type
    • CACHED_INTERFACES

      private static volatile List<NetworkInterface> CACHED_INTERFACES
    • CACHED_ADDRESSES

      private static volatile Collection<InetAddress> CACHED_ADDRESSES
    • can_bind_to_mcast_addr

      public static final boolean can_bind_to_mcast_addr
    • resource_bundle

      protected static ResourceBundle resource_bundle
    • UTF_FORMAT

      static DateTimeFormatter UTF_FORMAT
    • UUID_PREFIX

      protected static final String UUID_PREFIX
      See Also:
    • SITE_UUID_PREFIX

      protected static final String SITE_UUID_PREFIX
      See Also:
    • IP_PREFIX

      protected static final String IP_PREFIX
      See Also:
    • OTHER_ADDR

      protected static final String OTHER_ADDR
      See Also:
    • RANDOM

      protected static final SplittableRandom RANDOM
    • FUNC

      protected static final Function<String,List<Address>> FUNC
    • LONG_ARRAY_VIEW

      public static final VarHandle LONG_ARRAY_VIEW
    • INT_ARRAY_VIEW

      public static final VarHandle INT_ARRAY_VIEW
  • Constructor Details

    • Util

      public Util()
  • Method Details

    • getUnicastProtocols

      public static final Class<? extends Protocol>[] getUnicastProtocols()
    • fibersAvailable

      @Deprecated public static boolean fibersAvailable()
      Deprecated.
    • virtualThreadsAvailable

      public static boolean virtualThreadsAvailable()
    • getNextHigherPowerOfTwo

      public static int getNextHigherPowerOfTwo(int num)
    • bold

      public static String bold(String msg)
    • getMessage

      public static String getMessage(String key)
    • getTestStack

      public static Protocol[] getTestStack(Protocol... additional_protocols)
      Returns a default stack for testing with transport = SHARED_LOOPBACK
      Parameters:
      additional_protocols - Any number of protocols to add to the top of the returned protocol list
      Returns:
    • waitUntilAllChannelsHaveSameView

      public static void waitUntilAllChannelsHaveSameView(long timeout, long interval, JChannel... channels) throws TimeoutException
      Blocks until all channels have the same view
      Parameters:
      timeout - How long to wait (max in ms)
      interval - Check every interval ms
      channels - The channels which should form the view. The expected view size is channels.length. Must be non-null
      Throws:
      TimeoutException
    • waitUntilAllChannelsHaveSameView

      public static void waitUntilAllChannelsHaveSameView(long timeout, long interval, Collection<JChannel> channels) throws TimeoutException
      Throws:
      TimeoutException
    • waitUntil

      public static void waitUntil(long timeout, long interval, BooleanSupplier condition) throws TimeoutException
      Throws:
      TimeoutException
    • waitUntil

      public static void waitUntil(long timeout, long interval, BooleanSupplier condition, Supplier<String> msg) throws TimeoutException
      Throws:
      TimeoutException
    • waitUntilNoX

      public static boolean waitUntilNoX(long timeout, long interval, BooleanSupplier condition)
    • waitUntilTrue

      public static boolean waitUntilTrue(long timeout, long interval, BooleanSupplier condition)
    • asyncWaitUntilTrue

      public static <T> void asyncWaitUntilTrue(long timeout, long interval, BooleanSupplier cond, Supplier<T> on_success, Supplier<T> on_failure)
      In a separate thread (common ForkJoinPool): waits for the given timeout / interval until a condition is true. When true, executes the on_success supplier, else the on_failure supplier
    • assertPositive

      public static int assertPositive(int value, String message)
    • allChannelsHaveSameView

      public static boolean allChannelsHaveSameView(JChannel... channels)
    • assertAllChannelsHaveSameView

      public static void assertAllChannelsHaveSameView(JChannel... channels)
    • printViews

      public static String printViews(JChannel... channels)
    • waitUntilListHasSize

      public static <T> void waitUntilListHasSize(List<T> list, int expected_size, long timeout, long interval)
      Waits until a list has the expected number of elements. Throws an exception if not met
      Type Parameters:
      T - The type of the list
      Parameters:
      list - The list
      expected_size - The expected size
      timeout - The time to wait (in ms)
      interval - The interval at which to get the size of the list (in ms)
    • removeFromViews

      public static void removeFromViews(Address mbr, JChannel... channels)
    • createEnum

      public static <T extends Enum<T>> T createEnum(String name, Type type)
      Creates an enum from a string
    • createAuthenticationDigest

      public static byte[] createAuthenticationDigest(String passcode, long t1, double q1) throws IOException, NoSuchAlgorithmException
      Throws:
      IOException
      NoSuchAlgorithmException
    • createDigest

      public static byte[] createDigest(String passcode, long t1, double q1) throws IOException, NoSuchAlgorithmException
      Throws:
      IOException
      NoSuchAlgorithmException
    • connect

      public static void connect(Socket sock, SocketAddress dest, int sock_conn_timeout) throws IOException
      Utility method. If the dest address is IPv6, convert scoped link-local addrs into unscoped ones
      Parameters:
      sock -
      dest -
      sock_conn_timeout -
      Throws:
      IOException
    • connect

      public static boolean connect(SocketChannel ch, SocketAddress dest) throws IOException
      Throws:
      IOException
    • close

      public static void close(Closeable closeable)
    • close

      public static void close(Closeable... closeables)
    • closeReverse

      public static void closeReverse(Closeable... closeables)
    • closeFast

      public static void closeFast(JChannel... channels)
      Closes all non-coordinators first, in parallel, then closes the coord. This should produce just 2 views
    • shutdown

      public static void shutdown(JChannel ch) throws Exception
      Drops messages to/from other members and then closes the channel. Note that this member won't get excluded from the view until failure detection has kicked in and the new coord installed the new view
      Throws:
      Exception
    • setFlag

      public static byte setFlag(byte bits, byte flag)
    • isFlagSet

      public static boolean isFlagSet(byte bits, byte flag)
    • clearFlags

      public static byte clearFlags(byte bits, byte flag)
    • flagsToString

      public static String flagsToString(short flags)
    • transientFlagsToString

      public static String transientFlagsToString(short flags)
    • isFlagSet

      public static boolean isFlagSet(short flags, Message.Flag flag)
    • isTransientFlagSet

      public static boolean isTransientFlagSet(short flags, Message.TransientFlag flag)
    • copy

      public static Message copy(Message msg, boolean copy_buffer, short starting_id, short... copy_only_ids)
      Copies a message. Copies only headers with IDs >= starting_id or IDs which are in the copy_only_ids list
      Parameters:
      copy_buffer -
      starting_id -
      copy_only_ids -
    • objectFromByteBuffer

      public static <T> T objectFromByteBuffer(byte[] buffer) throws IOException, ClassNotFoundException
      Creates an object from a byte buffer
      Throws:
      IOException
      ClassNotFoundException
    • objectFromByteBuffer

      public static <T> T objectFromByteBuffer(byte[] buffer, int offset, int length) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • objectFromBuffer

      public static <T> T objectFromBuffer(ByteArray b, ClassLoader loader) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • objectFromByteBuffer

      public static <T> T objectFromByteBuffer(byte[] buffer, int offset, int length, ClassLoader loader) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • objectFromByteBuffer

      public static <T> T objectFromByteBuffer(ByteBuffer buffer, ClassLoader loader) throws Exception
      Parses an object from a ByteBuffer. Note that this changes the position of the buffer, so it this is not desired, use ByteBuffer.duplicate() to create a copy and pass the copy to this method.
      Throws:
      Exception
    • objectToByteBuffer

      public static byte[] objectToByteBuffer(Object obj) throws IOException
      Throws:
      IOException
    • objectToBuffer

      public static ByteArray objectToBuffer(Object obj) throws IOException
      Serializes/Streams an object into a byte buffer. The object has to implement interface Serializable or Externalizable or Streamable.
      Throws:
      IOException
    • writeStreamable

      protected static ByteArray writeStreamable(Streamable obj) throws IOException
      Throws:
      IOException
    • writeSerializable

      protected static ByteArray writeSerializable(Object obj) throws IOException
      Throws:
      IOException
    • marshalPrimitiveType

      protected static byte[] marshalPrimitiveType(Byte type, Object obj)
    • writeString

      public static void writeString(String str, DataOutput out) throws IOException
      Throws:
      IOException
    • readString

      public static String readString(DataInput in) throws IOException
      Throws:
      IOException
    • size

      public static int size(Object obj)
    • size

      public static int size(SizeStreamable s)
    • sizePrimitive

      public static int sizePrimitive(Object obj)
    • writeTypeStreamable

      public static void writeTypeStreamable(Streamable obj, DataOutput out) throws IOException
      Throws:
      IOException
    • primitiveToStream

      public static void primitiveToStream(Object obj, DataOutput out) throws IOException
      Throws:
      IOException
    • primitiveFromStream

      public static <T> T primitiveFromStream(DataInput in) throws IOException
      Throws:
      IOException
    • primitiveFromStream

      public static <T> T primitiveFromStream(DataInput in, byte type) throws IOException
      Throws:
      IOException
    • objectToStream

      public static void objectToStream(Object obj, DataOutput out) throws IOException
      Throws:
      IOException
    • objectFromStream

      public static <T> T objectFromStream(DataInput in) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • objectFromStream

      public static <T> T objectFromStream(DataInput in, ClassLoader loader) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • streamableFromByteBuffer

      public static <T extends Streamable> T streamableFromByteBuffer(Class<? extends Streamable> cl, byte[] buffer) throws Exception
      Throws:
      Exception
    • streamableFromByteBuffer

      public static <T extends Streamable> T streamableFromByteBuffer(Supplier<T> factory, byte[] buffer) throws Exception
      Throws:
      Exception
    • exceptionToStream

      public static void exceptionToStream(Throwable t, DataOutput out) throws IOException
      Poor man's serialization of an exception. Serializes only the message, stack trace and cause (not suppressed exceptions)
      Throws:
      IOException
    • exceptionToStream

      protected static void exceptionToStream(Set<Throwable> causes, Throwable t, DataOutput out) throws IOException
      Throws:
      IOException
    • exceptionToBuffer

      public static ByteArray exceptionToBuffer(Throwable t) throws IOException
      Throws:
      IOException
    • exceptionFromStream

      public static Throwable exceptionFromStream(DataInput in) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • exceptionFromStream

      protected static Throwable exceptionFromStream(DataInput in, int recursion_count) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • add

      protected static void add(byte type, Class<?> cl)
    • writeException

      protected static void writeException(Set<Throwable> causes, Throwable t, DataOutput out) throws IOException
      Throws:
      IOException
    • readException

      protected static Throwable readException(DataInput in, int recursion_count) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • exceptionFromBuffer

      public static Throwable exceptionFromBuffer(byte[] buf, int offset, int length) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • bufferToArray

      public static byte[] bufferToArray(ByteBuffer buf)
      Returns a copy of the byte array between position and limit; requires a non-null buffer
    • bufferToArray

      public static void bufferToArray(Address sender, ByteBuffer buf, Receiver target)
    • streamableFromByteBuffer

      public static <T extends Streamable> T streamableFromByteBuffer(Class<? extends Streamable> cl, byte[] buffer, int offset, int length) throws Exception
      Throws:
      Exception
    • streamableFromByteBuffer

      public static <T extends Streamable> T streamableFromByteBuffer(Class<? extends Streamable> cl, ByteBuffer buffer) throws Exception
      Throws:
      Exception
    • streamableFromByteBuffer

      public static <T extends Streamable> T streamableFromByteBuffer(Supplier<T> factory, byte[] buffer, int offset, int length) throws Exception
      Throws:
      Exception
    • streamableFromBuffer

      public static <T extends Streamable> T streamableFromBuffer(Supplier<T> factory, byte[] buf, int off, int len) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • streamableToByteBuffer

      public static byte[] streamableToByteBuffer(Streamable obj) throws IOException
      Throws:
      IOException
    • streamableToBuffer

      public static ByteArray streamableToBuffer(Streamable obj) throws Exception
      Throws:
      Exception
    • messageToBuffer

      public static ByteArray messageToBuffer(Message msg) throws Exception
      Throws:
      Exception
    • messageFromBuffer

      public static Message messageFromBuffer(byte[] buf, int offset, int length, MessageFactory mf) throws Exception
      Throws:
      Exception
    • messageToByteBuffer

      public static ByteArray messageToByteBuffer(Message msg) throws Exception
      Throws:
      Exception
    • messageFromByteBuffer

      public static Message messageFromByteBuffer(byte[] buffer, int offset, int length, MessageFactory mf) throws Exception
      Throws:
      Exception
    • getObject

      public static String getObject(Message msg)
      Tries to return a legible representation of a message's payload
    • getObjects

      public static String getObjects(Iterable<Message> it)
    • wrapDirect

      public static ByteBuffer wrapDirect(byte[] array)
    • wrapDirect

      public static ByteBuffer wrapDirect(byte[] array, int offset, int length)
    • collectionToByteBuffer

      public static byte[] collectionToByteBuffer(Collection<Address> c) throws IOException
      Throws:
      IOException
    • stringToBytes

      public static byte[] stringToBytes(String str)
    • bytesToString

      public static String bytesToString(byte[] bytes)
    • byteArrayToHexString

      public static String byteArrayToHexString(byte[] b)
    • byteArrayToHexString

      public static String byteArrayToHexString(byte[] b, int offset, int length)
    • isAsciiString

      public static boolean isAsciiString(String str)
    • hexToBin

      public static String hexToBin(String s)
    • compare

      public static int compare(byte[] left, byte[] right)
      Compares 2 byte arrays, elements are treated as unigned
    • convert

      public static Object convert(String arg, Class<?> type, TimeUnit unit)
    • writeMessage

      public static void writeMessage(Message msg, DataOutput dos, boolean multicast) throws IOException
      Throws:
      IOException
    • readMessage

      public static Message readMessage(DataInput in, MessageFactory mf) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • writeMessageList

      public static void writeMessageList(Address dest, Address src, byte[] cluster_name, List<Message> msgs, DataOutput dos, boolean multicast) throws IOException
      Write a list of messages with the *same* destination and src addresses. The message list is marshalled as follows (see doc/design/MarshallingFormat.txt for details):
       List: * | version | flags | dest | src | cluster-name | [Message*] |
      
       Message:  | presence | leading | flags | [src] | length | [buffer] | size | [Headers*] |
      
       
      Throws:
      IOException
    • writeMessageList

      public static void writeMessageList(Address dest, Address src, byte[] cluster_name, FastArray<Message> msgs, DataOutput dos, boolean multicast) throws IOException
      Throws:
      IOException
    • writeMessageList

      public static void writeMessageList(Address dest, Address src, byte[] cluster_name, Message[] msgs, int offset, int length, DataOutput dos, boolean multicast) throws IOException
      Throws:
      IOException
    • writeMessageListHeader

      public static void writeMessageListHeader(Address dest, Address src, byte[] cluster_name, int numMsgs, DataOutput dos, boolean multicast) throws IOException
      Throws:
      IOException
    • readMessageList

      public static List<Message> readMessageList(DataInput in, short transport_id, MessageFactory mf) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • readMessageBatch

      public static MessageBatch[] readMessageBatch(DataInput in, boolean multicast, MessageFactory factory) throws IOException, ClassNotFoundException
      Reads a list of messages into 2 MessageBatches:
      1. regular
      2. OOB
      Returns:
      an array of 2 MessageBatches in the order above, the first batch is at index 0
      Throws:
      IOException
      ClassNotFoundException
    • parse

      public static void parse(byte[] buf, int offset, int length, BiConsumer<Short,Message> msg_consumer, BiConsumer<Short,MessageBatch> batch_consumer, Consumer<GossipData> gossip_consumer, boolean tcp, boolean gossip)
    • parse

      public static void parse(InputStream input, BiConsumer<Short,Message> msg_consumer, BiConsumer<Short,MessageBatch> batch_consumer, Consumer<GossipData> gossip_consumer, boolean tcp, boolean gossip)
    • writeView

      public static void writeView(View view, DataOutput out) throws IOException
      Throws:
      IOException
    • readView

      public static View readView(DataInput in) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • writeViewId

      public static void writeViewId(ViewId vid, DataOutput out) throws IOException
      Throws:
      IOException
    • readViewId

      public static ViewId readViewId(DataInput in) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • writeAddress

      public static void writeAddress(Address addr, DataOutput out) throws IOException
      Throws:
      IOException
    • readAddress

      public static Address readAddress(DataInput in) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • size

      public static int size(Address addr)
    • size

      public static int size(View view)
    • size

      public static int size(ViewId vid)
    • size

      public static int size(String s)
    • size

      public static int size(byte[] buf)
    • readOtherAddress

      private static Address readOtherAddress(DataInput in) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • writeOtherAddress

      private static void writeOtherAddress(Address addr, DataOutput out) throws IOException
      Throws:
      IOException
    • writeAddresses

      public static void writeAddresses(Collection<? extends Address> v, DataOutput out) throws IOException
      Writes a list of Addresses. Can contain 65K addresses at most
      Parameters:
      v - A Collection of addresses
      Throws:
      IOException
    • writeAddresses

      public static void writeAddresses(Address[] addrs, DataOutput out) throws IOException
      Throws:
      IOException
    • readAddresses

      public static <T extends Collection<Address>> T readAddresses(DataInput in, IntFunction<T> factory) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • readAddresses

      public static Address[] readAddresses(DataInput in) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • size

      public static long size(Collection<? extends Address> addrs)
      Returns the marshalled size of a Collection of Addresses. Assumes elements are of the same type !
      Parameters:
      addrs - Collection
      Returns:
      long size
    • size

      public static long size(Address[] addrs)
    • addressToString

      public static String addressToString(Address addr)
    • addressFromString

      public static Address addressFromString(String s) throws Exception
      Throws:
      Exception
    • writeStreamable

      public static void writeStreamable(Streamable obj, DataOutput out) throws IOException
      Throws:
      IOException
    • readStreamable

      public static <T extends Streamable> T readStreamable(Supplier<T> factory, DataInput in) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • writeGenericStreamable

      public static void writeGenericStreamable(Streamable obj, DataOutput out) throws IOException
      Throws:
      IOException
    • readGenericStreamable

      public static <T extends Streamable> T readGenericStreamable(DataInput in) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • readGenericStreamable

      public static <T extends Streamable> T readGenericStreamable(DataInput in, ClassLoader loader) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • readSizeStreamable

      public static SizeStreamable readSizeStreamable(DataInput in, ClassLoader loader) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • write

      public static <T extends Streamable> void write(T[] array, DataOutput out) throws IOException
      Throws:
      IOException
    • read

      public static <T extends Streamable> T[] read(Class<T> clazz, DataInput in) throws Exception
      Throws:
      Exception
    • readFile

      public static String readFile(String filename) throws FileNotFoundException
      Throws:
      FileNotFoundException
    • readContents

      public static String readContents(InputStream input)
    • readContents

      public static String readContents(InputStream input, char comment)
    • skipUntilEndOfLine

      protected static void skipUntilEndOfLine(InputStream input)
    • readFileContents

      public static byte[] readFileContents(InputStream input) throws IOException
      Throws:
      IOException
    • readToken

      public static String readToken(InputStream in)
      Returns whitespace-separated strings from the input stream, or null if the end of the stream has been reached
    • readTillMatchingCharacter

      public static String readTillMatchingCharacter(InputStream in, char c) throws IOException
      Returns all characters read from the current position until the next occurrence of 'c' has been read (including 'c'), or eof, whichever comes first
      Throws:
      IOException
    • readStringFromStdin

      public static String readStringFromStdin(String message) throws Exception
      Throws:
      Exception
    • readLongFromStdin

      public static long readLongFromStdin(String message) throws Exception
      Throws:
      Exception
    • readDoubleFromStdin

      public static double readDoubleFromStdin(String message) throws Exception
      Throws:
      Exception
    • readIntFromStdin

      public static int readIntFromStdin(String message) throws Exception
      Throws:
      Exception
    • writeByteBuffer

      public static void writeByteBuffer(byte[] buf, DataOutput out) throws IOException
      Throws:
      IOException
    • writeByteBuffer

      public static void writeByteBuffer(byte[] buf, int offset, int length, DataOutput out) throws IOException
      Throws:
      IOException
    • readByteBuffer

      public static byte[] readByteBuffer(DataInput in) throws IOException
      Throws:
      IOException
    • match

      public static <T> boolean match(T obj1, T obj2)
    • patternMatch

      public static boolean patternMatch(String pattern, String str)
    • productGreaterThan

      public static boolean productGreaterThan(long n1, long n2, long val)
    • different

      public static <T> boolean different(T one, T two)
    • sleep

      public static void sleep(long timeout)
      Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted
    • sleep

      public static void sleep(long timeout, int nanos)
    • keyPress

      public static int keyPress(String msg)
    • available

      public static int available(InputStream in)
    • micros

      public static long micros()
    • factorial

      public static int factorial(int n)
    • permute

      public static <E> void permute(List<E> list, List<List<E>> permutations)
      Inefficient permutation of a generic list; uses too much copying among other things. PR welcome! :-)
      Type Parameters:
      E - the type of the list elements
      Parameters:
      list - The list
      permutations - All permutations will be added to this list (as copies)
    • permute

      protected static <E> void permute(List<E> prefix, List<E> list, int index, List<List<E>> permutations)
    • car

      public static <E> List<E> car(List<E> l)
    • cdr

      public static <E> List<E> cdr(List<E> l)
    • combine

      public static <E> List<E> combine(List<E> l1, List<E> l2)
    • combine

      @SafeVarargs public static <E> E[] combine(E[]... arrays)
    • combine

      @SafeVarargs public static <E> E[] combine(Class<?> cl, E... array)
    • swap

      protected static <E> List<E> swap(List<E> l, int index)
    • orderedPermutation

      public static <E> Collection<List<E>> orderedPermutation(List<E> a, List<E> b)
      Performs an ordered permutation of the elements of a and b such that the order of elements in list a and b is preserved. Example: {A1,A2} and {B1,B2} -> {A1,B1,A2,B2} but not {A1,B2,B1,A2}
    • permute

      protected static <E> List<E> permute(List<E> l1, List<E> l2, int remove_from_l1, int remove_from_l2)
    • checkOrder

      @SafeVarargs public static <E> boolean checkOrder(Collection<E> perm, List<E>... lists)
    • index

      protected static <E> int index(Collection<E> list, E el)
    • shuffle

      public static <T> void shuffle(T[] array, int from, int to)
      Reorders elements of an array in-place. No bounds checking is performed. Null elements are shuffled, too
      Type Parameters:
      T - the type of the array's elements
      Parameters:
      array - the array to be shuffled; the array will be modified
      from - the start index inclusive
      to - the end index (exclusive), must be >= from (not checked)
    • enumerate

      public static <T> Enumeration<T> enumerate(T[] array, int offset, int length)
    • enumerate

      public static <T, R> Enumeration<R> enumerate(T[] array, int offset, int length, Function<T,R> converter)
    • nonNegativeValue

      public static <T extends Number> T nonNegativeValue(T num)
    • random

      public static long random(long range)
      Returns a random value in the range [1 - range]. If range is 0, 1 will be returned. If range is negative, an exception will be thrown
    • sleepRandom

      public static void sleepRandom(long floor, long ceiling)
      Sleeps between floor and ceiling milliseconds, chosen randomly
    • tossWeightedCoin

      public static boolean tossWeightedCoin(double probability)
      Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8, chances are that in 80% of all cases, true will be returned and false in 20%.
    • dumpThreads

      public static String dumpThreads()
    • dumpThreadInfo

      private static String dumpThreadInfo(ThreadInfo thread)
    • blockedState

      private static String blockedState(ThreadInfo thread, LockInfo blockedLock, boolean parking)
    • interruptAndWaitToDie

      public static boolean interruptAndWaitToDie(Thread t)
    • interruptAndWaitToDie

      public static boolean interruptAndWaitToDie(Thread t, long timeout)
    • printTime

      public static String printTime(double time, TimeUnit unit)
    • suffix

      public static String suffix(TimeUnit u)
    • print

      public static String print(double time, TimeUnit unit)
    • readBytesLong

      public static long readBytesLong(String input)
    • readBytesInteger

      public static int readBytesInteger(String input)
    • readBytesDouble

      public static double readBytesDouble(String input)
    • readBytes

      private static Tuple<String,Long> readBytes(String input)
    • readDurationLong

      public static long readDurationLong(String input, TimeUnit unit)
    • readDurationInt

      public static int readDurationInt(String input, TimeUnit unit)
    • readDuration

      private static Tuple<String,Long> readDuration(String input)
    • printBytes

      public static String printBytes(double bytes)
      MB nowadays doesn't mean 1024 * 1024 bytes, but 1 million bytes, see http://en.wikipedia.org/wiki/Megabyte
      Parameters:
      bytes -
    • format

      public static String format(double val, String suffix)
    • components

      public static String[] components(String path, String separator)
    • fragmentBuffer

      public static byte[][] fragmentBuffer(byte[] buf, int frag_size, int length)
      Fragments a byte buffer into smaller fragments of (max.) frag_size. Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments of 248 bytes each and 1 fragment of 32 bytes.
      Returns:
      An array of byte buffers (byte[]).
    • computeFragOffsets

      public static List<Range> computeFragOffsets(int offset, int length, int frag_size)
      Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and return them in a list. Example:

      Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}). This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length of 2 bytes.

      Parameters:
      frag_size -
      Returns:
      List. A List of offset/length pairs
    • computeFragOffsets

      public static List<Range> computeFragOffsets(byte[] buf, int frag_size)
    • defragmentBuffer

      public static byte[] defragmentBuffer(byte[][] fragments)
      Concatenates smaller fragments into entire buffers.
      Parameters:
      fragments - An array of byte buffers (byte[])
      Returns:
      A byte buffer
    • allEqual

      public static <T> boolean allEqual(Collection<T> elements)
      Returns true if all elements in the collection are the same
    • printList

      public static <T> String printList(Collection<T> l)
    • printListWithDelimiter

      public static <T> String printListWithDelimiter(Collection<T> list, String delimiter)
    • printListWithDelimiter

      public static <T> String printListWithDelimiter(Collection<T> list, String delimiter, int limit)
    • printListWithDelimiter

      public static <T> String printListWithDelimiter(Collection<T> list, String delimiter, int limit, boolean print_size)
    • printListWithDelimiter

      public static <T> String printListWithDelimiter(T[] list, String delimiter, int limit)
    • printMapWithDelimiter

      public static <T> String printMapWithDelimiter(Map<T,T> map, String delimiter)
    • leftMembers

      public static List<Address> leftMembers(Collection<Address> old_list, Collection<Address> new_list)
    • newMembers

      public static List<Address> newMembers(List<Address> old_list, List<Address> new_list)
    • newElements

      public static <T> List<T> newElements(List<T> old_list, List<T> new_list)
    • contains

      public static <T> boolean contains(T key, T[] list)
    • containsViewId

      public static boolean containsViewId(Collection<View> views, ViewId vid)
    • containsId

      public static boolean containsId(short id, short[] ids)
    • determineMergeParticipants

      public static Collection<Address> determineMergeParticipants(Map<Address,View> map)
      Determines the members which take part in a merge. The resulting list consists of all merge coordinators plus members outside a merge partition, e.g. for views A={B,A,C}, B={B,C} and C={B,C}, the merge coordinator is B, but the merge participants are B and A.
      Parameters:
      map -
      Returns:
    • determineMergeCoords

      public static Collection<Address> determineMergeCoords(Map<Address,View> map)
      This is the same or a subset of determineMergeParticipants(java.util.Map) and contains only members which are currently sub-partition coordinators.
      Parameters:
      map -
      Returns:
    • determineActualMergeCoords

      public static Collection<Address> determineActualMergeCoords(Map<Address,View> map)
      Similar to determineMergeCoords(java.util.Map) but only actual coordinators are counted: an actual coord is when the sender of a view is the first member of that view
    • getRank

      public static int getRank(View view, Address addr)
      Returns the rank of a member in a given view
      Parameters:
      view - The view
      addr - The address of a member
      Returns:
      A value between 1 and view.size(). The first member has rank 1, the second 2 and so on. If the member is not found, 0 is returned
    • getRank

      public static int getRank(Collection<Address> members, Address addr)
    • pickRandomElement

      public static <T> T pickRandomElement(List<T> list)
    • pickRandomElement

      public static <T> T pickRandomElement(Collection<T> set)
    • pickRandomElement

      public static <T> T pickRandomElement(T[] array)
    • pickNext

      public static <T> T pickNext(List<T> list, T obj)
    • pickNext

      public static <T> List<T> pickNext(List<T> list, T obj, int num)
      Returns the next min(N,list.size()) elements after obj
    • pickPrevious

      public static <T> T pickPrevious(T[] array, T el)
      Returns the element before el. If el is the first element, returns the last element. Returns null if array.length < 2
    • pickPrevious

      public static <T> T pickPrevious(List<T> list, T el)
    • generateArray

      public static byte[] generateArray(int length)
    • verifyArray

      public static boolean verifyArray(byte[] array)
    • verifyByteBuffer

      public static boolean verifyByteBuffer(ByteBuffer buf)
    • createRandomAddress

      public static Address createRandomAddress()
    • createRandomAddresses

      public static Address[] createRandomAddresses(int num)
      Returns an array of num random addresses, named A, B, C etc
    • createRandomAddresses

      public static Address[] createRandomAddresses(int num, boolean use_numbers)
    • createRandomAddress

      public static Address createRandomAddress(String name)
    • createTimer

      public static Object[][] createTimer()
    • determineLeftMembers

      public static List<Address> determineLeftMembers(List<Address> old_mbrs, List<Address> new_mbrs)
      Returns all members that left between 2 views. All members that are element of old_mbrs but not element of new_mbrs are returned.
    • print

      public static <T> String print(Collection<T> objs)
    • print

      public static String print(Object[] objs)
    • print

      public static <T> String print(Map<T,T> map)
    • loadClass

      public static Class<?> loadClass(String classname, Class<?> clazz) throws ClassNotFoundException
      Tries to load the class from the current thread's context class loader. If not successful, tries to load the class from the current instance.
      Parameters:
      classname - Desired class.
      clazz - Class object used to obtain a class loader if no context class loader is available.
      Returns:
      Class, or null on failure.
      Throws:
      ClassNotFoundException
    • loadClass

      public static Class<?> loadClass(String classname, ClassLoader preferredLoader) throws ClassNotFoundException
      Tries to load the class from the preferred loader. If not successful, tries to load the class from the current thread's context class loader or system class loader.
      Parameters:
      classname - Desired class name.
      preferredLoader - The preferred class loader
      Returns:
      the loaded class.
      Throws:
      ClassNotFoundException - if the class could not be loaded by any loader
    • loadProtocolClass

      public static Class<? extends Protocol> loadProtocolClass(String protocol_name, Class<?> cl) throws Exception
      Throws:
      Exception
    • getAllDeclaredFieldsWithAnnotations

      @SafeVarargs public static Field[] getAllDeclaredFieldsWithAnnotations(Class<?> clazz, Class<? extends Annotation>... annotations)
    • forAllFieldsAndMethods

      public static void forAllFieldsAndMethods(Object obj, Predicate<? super AccessibleObject> filter, BiConsumer<Field,Object> field_func, BiConsumer<Method,Object> method_func)
      Applies a function against all fields and methods of a given target object which satisfy a given predicate.
      Parameters:
      obj - The target object
      filter - The filter. Needs to be able to handle Fields and Methods (superclass: AccessibleObject). If null, all fields/methods will be selected
      field_func - The function to be applied to all found fields. No-op if null.
      method_func - The function to be applied to all found methods. No-op if null.
    • getNameFromAnnotation

      public static String getNameFromAnnotation(AccessibleObject obj)
    • getAllDeclaredMethodsWithAnnotations

      @SafeVarargs public static Method[] getAllDeclaredMethodsWithAnnotations(Class<?> clazz, Class<? extends Annotation>... annotations)
    • getAnnotation

      public static <A extends Annotation> A getAnnotation(Class<?> clazz, Class<A> annotationClass)
    • getField

      public static Field getField(Class<?> clazz, String field_name)
    • getField

      public static Field getField(Class<?> clazz, String field_name, boolean throw_exception) throws NoSuchFieldException
      Throws:
      NoSuchFieldException
    • setField

      public static void setField(Field field, Object target, Object value)
    • getField

      public static Object getField(Field field, Object target)
    • findField

      public static Field findField(Object target, List<String> possible_names)
    • findMethod

      public static Method findMethod(Class<?> target_class, String method_name, Object[] args) throws Exception
      Called by the ProbeHandler impl. All args are strings. Needs to find a method where all parameter types are primitive types, so the strings can be converted
      Throws:
      Exception
    • getAllMethods

      public static Method[] getAllMethods(Class<?> target)
      The method walks up the class hierarchy and returns all methods of this class and those inherited from superclasses and superinterfaces.
    • getComponents

      public static List<Object> getComponents(Object target)
      Returns the non-null values of all fields of target annotated with @Component
    • forAllComponents

      public static void forAllComponents(Object target, BiConsumer<Object,String> func)
      Applies a function to all fields annotated with @Component
      Parameters:
      target - The target object
      func - The function accepting the value of the field and the component name (prefix)
    • forAllComponentTypes

      public static void forAllComponentTypes(Class<?> cl, BiConsumer<Class<?>,String> func)
    • isPrimitiveType

      public static boolean isPrimitiveType(Class<?> type)
    • isPrimitiveType

      public static boolean isPrimitiveType(Object obj)
    • findMethod

      public static Method findMethod(Object target, List<String> possible_names, Class<?>... parameter_types)
    • findMethod

      public static Method findMethod(Class<?> root_class, List<String> possible_names, Class<?>... parameter_types)
    • findMethod

      public static Method findMethod(Class<?> cl, String method_name, Class<?>... parameter_types)
    • findClassesAssignableFrom

      public static Set<Class<?>> findClassesAssignableFrom(String packageName, Class<?> assignableFrom, ClassLoader cl) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • findClassesAssignableFromPath

      public static Set<Class<?>> findClassesAssignableFromPath(String packagePath, Class<?> assignableFrom, ClassLoader cl) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • findClassesAnnotatedWith

      public static List<Class<?>> findClassesAnnotatedWith(String packageName, Class<? extends Annotation> a) throws IOException, ClassNotFoundException
      Throws:
      IOException
      ClassNotFoundException
    • recurse

      private static void recurse(List<Class<?>> classes, String packageName, Class<? extends Annotation> a) throws ClassNotFoundException
      Throws:
      ClassNotFoundException
    • getResourceAsStream

      public static InputStream getResourceAsStream(String name, Class<?> clazz)
    • getResourceAsStream

      public static InputStream getResourceAsStream(String name, ClassLoader loader)
    • getChild

      public static String getChild(Element root, String path)
    • sameHost

      public static boolean sameHost(Address one, Address two)
      Checks whether 2 Addresses are on the same host
    • parseRejectionPolicy

      public static RejectedExecutionHandler parseRejectionPolicy(String rejection_policy)
    • parseCommaDelimitedStrings

      public static List<String> parseCommaDelimitedStrings(String l)
      e.g. "A,B,C": List{"A", "B", "C"}
    • parseCommaDelimitedHosts

      public static List<PhysicalAddress> parseCommaDelimitedHosts(String hosts, int port_range) throws UnknownHostException
      Input is "daddy[8880],sindhu[8880],camille[5555]". Returns a list of IpAddresses
      Throws:
      UnknownHostException
    • parseCommaDelimitedHostsInto

      public static boolean parseCommaDelimitedHostsInto(Collection<PhysicalAddress> list, Collection<String> unresolved_hosts, String hosts, int default_port, int port_range, StackType stack_type)
      Parses a string into a list of IpAddresses
      Parameters:
      list - The list to which to add parsed elements
      unresolved_hosts - A list of unresolved hosts
      hosts - The string with host:port pairs
      port_range - The port range to consider
      Returns:
      True if all hostnames resolved fine, false otherwise
    • parseCommaDelimitedHosts2

      public static List<InetSocketAddress> parseCommaDelimitedHosts2(String hosts, int port_range) throws UnknownHostException
      Input is "daddy[8880],sindhu[8880],camille[5555]". Returns a list of InetSocketAddress. If a hostname doesn't resolve, then we'll use the hostname to create an address: new InetSocketAddress(host, port)
      Throws:
      UnknownHostException
    • parseHost

      public static InetSocketAddress parseHost(String s)
      Parses a host:IP string into an InetSocketAddress
    • parseStringList

      public static List<String> parseStringList(String l, String separator)
    • parseStringArray

      public static String[] parseStringArray(String s, String separator)
    • readLine

      public static String readLine(InputStream in) throws IOException
      Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
      Returns:
      A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
      Throws:
      IOException - If an I/O error occurs
    • readBytes

      public static ByteArray readBytes(InputStream in) throws IOException
      Reads all bytes from an input stream, until eof (-1) is reached
      Throws:
      IOException
    • parseInterfaceList

      public static List<NetworkInterface> parseInterfaceList(String s) throws Exception
      Throws:
      Exception
    • print

      public static String print(List<NetworkInterface> interfaces)
    • shortName

      public static String shortName(String hostname)
    • startFlush

      public static boolean startFlush(JChannel c, List<Address> flushParticipants, int numberOfAttempts, long randomSleepTimeoutFloor, long randomSleepTimeoutCeiling)
      Performs the flush of the given channel for the specified flush participants and the given number of attempts along with random sleep time after each such attempt.
      Parameters:
      c - the channel
      flushParticipants - the flush participants in this flush attempt
      numberOfAttempts - the number of flush attempts
      randomSleepTimeoutFloor - the minimum sleep time between attempts in ms
      randomSleepTimeoutCeiling - the maximum sleep time between attempts in ms
      Returns:
      true if channel was flushed successfully, false otherwise
      See Also:
    • startFlush

      public static boolean startFlush(JChannel c, List<Address> flushParticipants)
      Performs the flush of the given channel and the specified flush participants
      Parameters:
      c - the channel
      flushParticipants - the flush participants in this flush attempt
      See Also:
    • startFlush

      public static boolean startFlush(JChannel c, int numberOfAttempts, long randomSleepTimeoutFloor, long randomSleepTimeoutCeiling)
      Performs the flush of the given channel within the specfied number of attempts along with random sleep time after each such attempt.
      Parameters:
      c - the channel
      numberOfAttempts - the number of flush attempts
      randomSleepTimeoutFloor - the minimum sleep time between attempts in ms
      randomSleepTimeoutCeiling - the maximum sleep time between attempts in ms
      Returns:
      true if channel was flushed successfully, false otherwise
      See Also:
    • startFlush

      public static boolean startFlush(JChannel c)
      Performs the flush of the given channel
      Parameters:
      c - the channel
      Returns:
      true if channel was flushed successfully, false otherwise
      See Also:
    • shortName

      public static String shortName(InetAddress hostname)
    • generateLocalName

      public static String generateLocalName()
    • createConcurrentMap

      public static <K, V> ConcurrentMap<K,V> createConcurrentMap(int initial_capacity, float load_factor, int concurrency_level)
    • createConcurrentMap

      public static <K, V> ConcurrentMap<K,V> createConcurrentMap(int initial_capacity)
    • createConcurrentMap

      public static <K, V> ConcurrentMap<K,V> createConcurrentMap()
    • createServerSocket

      public static ServerSocket createServerSocket(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port, int end_port, int recv_buf_size) throws Exception
      Throws:
      Exception
    • bind

      public static void bind(ServerSocket srv_sock, InetAddress bind_addr, int start_port, int end_port) throws Exception
      Throws:
      Exception
    • bind

      public static void bind(Socket sock, InetAddress bind_addr, int start_port, int end_port) throws Exception
      Throws:
      Exception
    • createServerSocketChannel

      public static ServerSocketChannel createServerSocketChannel(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port, int end_port, int recv_buf_size) throws Exception
      Throws:
      Exception
    • createDatagramSocket

      public static DatagramSocket createDatagramSocket(SocketFactory factory, String service_name, InetAddress addr, int port) throws Exception
      Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use, start_port will be incremented until a socket can be created.
      Parameters:
      addr - The InetAddress to which the socket should be bound. If null, the socket will not be bound.
      port - The port which the socket should use. If 0, a random port will be used. If > 0, but port is already in use, it will be incremented until an unused port is found, or until MAX_PORT is reached.
      Throws:
      Exception
    • createMulticastSocket

      public static MulticastSocket createMulticastSocket(SocketFactory factory, String service_name, InetAddress mcast_addr, int port, Log log) throws IOException
      Throws:
      IOException
    • validateBindAddressFromInterface

      public static InetAddress validateBindAddressFromInterface(InetAddress bind_addr, String bind_interface_str, StackType ip_version) throws UnknownHostException, SocketException
      Method used by PropertyConverters.BindInterface to check that a bind_addr is consistent with a specified interface

      Idea: 1. We are passed a bind_addr, which may be null 2. If non-null, check that bind_addr is on bind_interface - if not, throw exception, otherwise, return the original bind_addr 3. If null, get first non-loopback address on bind_interface, using stack preference to get the IP version. If no non-loopback address, then just return null (i.e. bind_interface did not influence the decision).

      Throws:
      UnknownHostException
      SocketException
    • checkForLinux

      public static boolean checkForLinux()
    • checkForHp

      public static boolean checkForHp()
    • checkForSolaris

      public static boolean checkForSolaris()
    • checkForWindows

      public static boolean checkForWindows()
    • checkForAndroid

      public static boolean checkForAndroid()
    • checkForMac

      public static boolean checkForMac()
    • checkForPresence

      private static boolean checkForPresence(String key, String... values)
    • checkForPresence

      private static boolean checkForPresence(String key, String value)
    • contains

      private static boolean contains(String key, String value)
    • getLoopback

      public static InetAddress getLoopback(StackType ip_version) throws UnknownHostException
      IP related utilities
      Throws:
      UnknownHostException
    • getLoopback

      public static InetAddress getLoopback() throws UnknownHostException
      Throws:
      UnknownHostException
    • getNonLoopbackAddress

      public static InetAddress getNonLoopbackAddress() throws SocketException
      Returns the first non-loopback address on any interface on the current host
      Throws:
      SocketException
    • getNonLoopbackAddress

      public static InetAddress getNonLoopbackAddress(StackType ip_version) throws SocketException
      Throws:
      SocketException
    • getByName

      public static NetworkInterface getByName(String name) throws SocketException
      Finds a network interface or sub-interface with the given name
      Throws:
      SocketException
    • getByName

      public static InetAddress getByName(String host, StackType ip_version) throws UnknownHostException
      Finds an address given a symbolic name. Parameter ip_version has precedence over system props such as java.net.preferIPv4Stack or java.net.preferIPv6Addresses
      Parameters:
      host - The symbolic nbame of the host
      ip_version - The IP version, e.g. StackType.IPv4 or StackType.IPv6
      Returns:
      The resolved address
      Throws:
      UnknownHostException - Thrown if host cannot be resolved to an InetAddress
    • getAddress

      public static InetAddress getAddress(String value, StackType ip_version) throws Exception
      Throws:
      Exception
    • getAddress

      public static InetAddress getAddress(Util.AddressScope scope, StackType ip_version) throws SocketException
      Returns the first address on any interface which satisfies scope and ip_version. If ip_version is Dual, then IPv4 addresses are favored
      Throws:
      SocketException
    • getAddress

      public static InetAddress getAddress(NetworkInterface intf, Util.AddressScope scope, StackType ip_version)
      Returns the first address on the given interface on the current host, which satisfies scope
      Parameters:
      intf - the interface to be checked
    • match

      public static boolean match(InetAddress addr, Util.AddressScope scope)
    • getAddressByPatternMatch

      public static InetAddress getAddressByPatternMatch(String pattern, StackType ip_version) throws Exception
      Returns a valid interface address based on a pattern. Iterates over all interfaces that are up and returns the first match, based on the address or interface name
      Parameters:
      pattern - Can be "match-addr:<pattern></pattern>" or "match-interface:<pattern></pattern>". Example:

      match-addr:192.168.*

      Returns:
      InetAddress or null if not found
      Throws:
      Exception
    • getAddressByCustomCode

      public static InetAddress getAddressByCustomCode(String value) throws Exception
      Throws:
      Exception
    • isUp

      public static boolean isUp(NetworkInterface ni) throws SocketException
      Always returns true unless there is a socket exception - will be removed when GraalVM issue https://github.com/oracle/graal/pull/1076 has been fixed
      Throws:
      SocketException
    • interfaceHasIPAddresses

      public static boolean interfaceHasIPAddresses(NetworkInterface intf, StackType ip_version) throws UnknownHostException
      A function to check if an interface supports an IP version (i.e. has addresses defined for that IP version)
      Throws:
      UnknownHostException
    • getIpStackType

      public static StackType getIpStackType()
    • _getIpStackType

      private static StackType _getIpStackType()
      Tries to determine the type of IP stack from the available interfaces and their addresses and from the system properties (java.net.preferIPv4Stack and java.net.preferIPv6Addresses)
      Returns:
      StackType.IPv4 for an IPv4 only stack, StackType.IPv6 for an IPv6 only stack, and StackType.Unknown if the type cannot be detected
    • isStackAvailable

      public static boolean isStackAvailable(boolean ipv4)
    • getAllAvailableInterfaces

      public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException
      Throws:
      SocketException
    • resetCacheAddresses

      public static void resetCacheAddresses(boolean reset_interfaces, boolean reset_addresses)
    • setCacheAddresses

      public static void setCacheAddresses(List<NetworkInterface> interfaces, List<InetAddress> addresses)
      This is a workaround for use within android. Sometimes the standard java methods do not return all the addresses. This will allow for setting in android via the conectivity manager without needing to pass in the context. Also will allow android to update as connectivity changes.
    • getAllAvailableAddresses

      public static Collection<InetAddress> getAllAvailableAddresses(Predicate<InetAddress> filter)
      Returns all addresses of all interfaces (that are up) that satisfy a given filter (ignored if null)
    • getAllAvailableAddresses

      private static Collection<InetAddress> getAllAvailableAddresses()
    • checkIfValidAddress

      public static void checkIfValidAddress(InetAddress bind_addr, String prot_name) throws Exception
      Throws:
      Exception
    • getProperty

      public static String getProperty(String[] system_props, Properties props, String prop_name, String default_value)
      Returns a value associated wither with one or more system properties, or found in the props map
      Parameters:
      system_props -
      props - List of properties read from the configuration file
      prop_name - The name of the property, will be removed from props if found
      default_value - Used to return a default value if the properties or system properties didn't have the value
      Returns:
      The value, or null if not found
    • isCoordinator

      public static boolean isCoordinator(JChannel ch)
    • isCoordinator

      public static boolean isCoordinator(View view, Address local_addr)
    • getMBeanServer

      public static MBeanServer getMBeanServer()
    • registerChannel

      public static void registerChannel(JChannel channel, String name)
    • substituteVariable

      public static String substituteVariable(String val)
      Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns the same string, otherwise a copy of the string with variables substituted
      Parameters:
      val -
      Returns:
      A string with vars replaced, or the same string if no vars found
    • substituteVariableOld

      public static String substituteVariableOld(String val, Properties p)
      Replaces variables of ${var:default} with Properties then uses System.getProperty(var, default) if the value was not found. If no variables are found, returns the same string, otherwise a copy of the string with variables substituted
      Parameters:
      val -
      p -
      Returns:
      A string with vars replaced, or the same string if no vars found
    • substituteVariable

      public static String substituteVariable(String input, Properties p)
      Replaces variables in a string.
      Parameters:
      input - The input string
      p - A Properties hashmap, may be null
      Returns:
      The string with replaced variables, might be the same string as the input string if no substitution took place.
    • nextChar

      protected static char nextChar(String s, int index)
    • _substituteVar

      private static String _substituteVar(String val, Properties p)
    • getProperty

      public static String getProperty(String s, Properties p)
    • getProperty

      public static String getProperty(String s)
    • _getProperty

      private static String _getProperty(String var, String default_value, Properties p)
      Parses a var which might be comma delimited, e.g. bla,foo:1000: if 'bla' is set, return its value. Else, if 'foo' is set, return its value, else return "1000"
      Parameters:
      var -
      default_value -
      Returns:
    • methodNameToAttributeName

      public static String methodNameToAttributeName(String methodName)
      Converts a method name to an attribute name, e.g. getFooBar() to foo_bar, isFlag to flag
    • methodNameToJavaAttributeName

      public static String methodNameToJavaAttributeName(String methodName)
      Converts a method name to a Java attribute name, e.g. getFooBar() to fooBar, isFlag to flag.
      Parameters:
      methodName -
      Returns:
    • attributeNameToMethodName

      public static String attributeNameToMethodName(String attr_name)
    • getSites

      public static Map<String,List<Address>> getSites(View bridge_view, String excluding_site)
    • otherSites

      public static Collection<String> otherSites(View bridge_view, String excluding_site)
      Returns the sites of the view (all addresses are SiteUUIDs) minus the given site, Example: bridge_view=A:net1,B:net1,X:net2,Y:net2, excluding_site=net1 -> ["net2"]
      Parameters:
      bridge_view -
      excluding_site -
      Returns:
      the sites of members who are _not_ in excluding_site; each site is returned onlt once
    • utcNow

      public static String utcNow()
    • utcEpoch

      public static String utcEpoch(long milliseconds)