Class Util
-
Nested Class Summary
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final Patternprivate static Collection<InetAddress> private static List<NetworkInterface> static final booleanprotected static intprotected static intprotected static floatprivate static final IntHashMap<Class<?>> static final intstatic final VarHandleprotected static final Stringprivate static final StackTypeprivate static booleanprivate static booleanstatic final Stringstatic final VarHandlestatic intThe max size of an address list, used in View or Digest when toString() is called.static final intprivate static final Patternprotected static final Stringprotected static final SplittableRandomprotected static ResourceBundleprotected static final Stringprivate static final byteprivate static final byte[]private static final byteprivate static final byte[]private static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byte[]private static final byteprivate static final byteprivate static final byteprivate static final byteprivate static final byte(package private) static DateTimeFormatterprotected static final String -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate static StackTypeTries 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)private static String_getProperty(String var, String default_value, Properties p) Parses a var which might be comma delimited, e.g.private static String_substituteVar(String val, Properties p) protected static voidstatic Addressstatic StringaddressToString(Address addr) static booleanallChannelsHaveSameView(JChannel... channels) static <T> booleanallEqual(Collection<T> elements) Returns true if all elements in the collection are the samestatic voidassertAllChannelsHaveSameView(JChannel... channels) static intassertPositive(int value, String message) static <T> voidasyncWaitUntilTrue(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.static StringattributeNameToMethodName(String attr_name) static intavailable(InputStream in) static voidbind(ServerSocket srv_sock, InetAddress bind_addr, int start_port, int end_port) static voidbind(Socket sock, InetAddress bind_addr, int start_port, int end_port) private static StringblockedState(ThreadInfo thread, LockInfo blockedLock, boolean parking) static Stringstatic byte[]bufferToArray(ByteBuffer buf) Returns a copy of the byte array between position and limit; requires a non-null bufferstatic voidbufferToArray(Address sender, ByteBuffer buf, Receiver target) static StringbyteArrayToHexString(byte[] b) static StringbyteArrayToHexString(byte[] b, int offset, int length) static StringbytesToString(byte[] bytes) static <E> List<E> static <E> List<E> static booleanstatic booleanstatic booleanstatic booleanprivate static booleancheckForPresence(String key, String value) private static booleancheckForPresence(String key, String... values) static booleanstatic booleanstatic voidcheckIfValidAddress(InetAddress bind_addr, String prot_name) static <E> booleancheckOrder(Collection<E> perm, List<E>... lists) static byteclearFlags(byte bits, byte flag) static voidstatic voidstatic voidCloses all non-coordinators first, in parallel, then closes the coord.static voidcloseReverse(Closeable... closeables) static byte[]static <E> E[]combine(E[]... arrays) static <E> E[]static <E> List<E> static intcompare(byte[] left, byte[] right) Compares 2 byte arrays, elements are treated as unignedstatic String[]components(String path, String separator) computeFragOffsets(byte[] buf, int frag_size) 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.static voidconnect(Socket sock, SocketAddress dest, int sock_conn_timeout) Utility method.static booleanconnect(SocketChannel ch, SocketAddress dest) private static booleanstatic <T> booleancontains(T key, T[] list) static booleancontainsId(short id, short[] ids) static booleancontainsViewId(Collection<View> views, ViewId vid) static Objectstatic MessageCopies a message.static byte[]createAuthenticationDigest(String passcode, long t1, double q1) static <K,V> ConcurrentMap <K, V> static <K,V> ConcurrentMap <K, V> createConcurrentMap(int initial_capacity) static <K,V> ConcurrentMap <K, V> createConcurrentMap(int initial_capacity, float load_factor, int concurrency_level) static DatagramSocketcreateDatagramSocket(SocketFactory factory, String service_name, InetAddress addr, int port) Creates a DatagramSocket bound to addr.static byte[]createDigest(String passcode, long t1, double q1) static <T extends Enum<T>>
TcreateEnum(String name, Type type) Creates an enum from a stringstatic MulticastSocketcreateMulticastSocket(SocketFactory factory, String service_name, InetAddress mcast_addr, int port, Log log) static Addressstatic AddresscreateRandomAddress(String name) static Address[]createRandomAddresses(int num) Returns an array of num random addresses, named A, B, C etcstatic Address[]createRandomAddresses(int num, boolean use_numbers) static ServerSocketcreateServerSocket(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port, int end_port, int recv_buf_size) static ServerSocketChannelcreateServerSocketChannel(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port, int end_port, int recv_buf_size) static Object[][]static byte[]defragmentBuffer(byte[][] fragments) Concatenates smaller fragments into entire buffers.static Collection<Address> Similar todetermineMergeCoords(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 viewdetermineLeftMembers(List<Address> old_mbrs, List<Address> new_mbrs) Returns all members that left between 2 views.static Collection<Address> determineMergeCoords(Map<Address, View> map) This is the same or a subset ofdetermineMergeParticipants(java.util.Map)and contains only members which are currently sub-partition coordinators.static Collection<Address> Determines the members which take part in a merge.static <T> booleandifferent(T one, T two) private static StringdumpThreadInfo(ThreadInfo thread) static Stringstatic <T> Enumeration<T> enumerate(T[] array, int offset, int length) static <T,R> Enumeration <R> static ThrowableexceptionFromBuffer(byte[] buf, int offset, int length) static Throwableprotected static ThrowableexceptionFromStream(DataInput in, int recursion_count) static ByteArraystatic voidexceptionToStream(Throwable t, DataOutput out) Poor man's serialization of an exception.protected static voidexceptionToStream(Set<Throwable> causes, Throwable t, DataOutput out) static intfactorial(int n) static booleanDeprecated.findClassesAnnotatedWith(String packageName, Class<? extends Annotation> a) findClassesAssignableFrom(String packageName, Class<?> assignableFrom, ClassLoader cl) findClassesAssignableFromPath(String packagePath, Class<?> assignableFrom, ClassLoader cl) static Fieldstatic MethodfindMethod(Class<?> cl, String method_name, Class<?>... parameter_types) static MethodfindMethod(Class<?> target_class, String method_name, Object[] args) Called by the ProbeHandler impl.static MethodfindMethod(Class<?> root_class, List<String> possible_names, Class<?>... parameter_types) static MethodfindMethod(Object target, List<String> possible_names, Class<?>... parameter_types) static StringflagsToString(short flags) static voidforAllComponents(Object target, BiConsumer<Object, String> func) Applies a function to all fields annotated with @Componentstatic voidforAllComponentTypes(Class<?> cl, BiConsumer<Class<?>, String> func) static voidforAllFieldsAndMethods(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.static Stringstatic byte[][]fragmentBuffer(byte[] buf, int frag_size, int length) Fragments a byte buffer into smaller fragments of (max.) frag_size.static byte[]generateArray(int length) static Stringstatic InetAddressgetAddress(String value, StackType ip_version) static InetAddressgetAddress(NetworkInterface intf, Util.AddressScope scope, StackType ip_version) Returns the first address on the given interface on the current host, which satisfies scopestatic InetAddressgetAddress(Util.AddressScope scope, StackType ip_version) Returns the first address on any interface which satisfies scope and ip_version.static InetAddressgetAddressByCustomCode(String value) static InetAddressgetAddressByPatternMatch(String pattern, StackType ip_version) Returns a valid interface address based on a pattern.private static Collection<InetAddress> static Collection<InetAddress> getAllAvailableAddresses(Predicate<InetAddress> filter) Returns all addresses of all interfaces (that are up) that satisfy a given filter (ignored if null)static List<NetworkInterface> static Field[]getAllDeclaredFieldsWithAnnotations(Class<?> clazz, Class<? extends Annotation>... annotations) static Method[]getAllDeclaredMethodsWithAnnotations(Class<?> clazz, Class<? extends Annotation>... annotations) 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.static <A extends Annotation>
AgetAnnotation(Class<?> clazz, Class<A> annotationClass) static NetworkInterfaceFinds a network interface or sub-interface with the given namestatic InetAddressFinds an address given a symbolic name.static StringgetComponents(Object target) Returns the non-null values of all fields of target annotated with @Componentstatic Fieldstatic Fieldstatic Objectstatic StackTypestatic InetAddressstatic InetAddressgetLoopback(StackType ip_version) IP related utilitiesstatic MBeanServerstatic StringgetMessage(String key) static Stringstatic intgetNextHigherPowerOfTwo(int num) static InetAddressReturns the first non-loopback address on any interface on the current hoststatic InetAddressgetNonLoopbackAddress(StackType ip_version) static StringTries to return a legible representation of a message's payloadstatic StringgetObjects(Iterable<Message> it) static Stringstatic StringgetProperty(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 mapstatic StringgetProperty(String s, Properties p) static intgetRank(Collection<Address> members, Address addr) static intReturns the rank of a member in a given viewstatic InputStreamgetResourceAsStream(String name, Class<?> clazz) static InputStreamgetResourceAsStream(String name, ClassLoader loader) static Protocol[]getTestStack(Protocol... additional_protocols) Returns a default stack for testing with transport = SHARED_LOOPBACKstatic Stringprotected static <E> intindex(Collection<E> list, E el) static booleaninterfaceHasIPAddresses(NetworkInterface intf, StackType ip_version) A function to check if an interface supports an IP version (i.e.static booleanstatic booleaninterruptAndWaitToDie(Thread t, long timeout) static booleanisAsciiString(String str) static booleanstatic booleanisCoordinator(View view, Address local_addr) static booleanisFlagSet(byte bits, byte flag) static booleanisFlagSet(short flags, Message.Flag flag) static booleanisPrimitiveType(Class<?> type) static booleanisPrimitiveType(Object obj) static booleanisStackAvailable(boolean ipv4) static booleanisTransientFlagSet(short flags, Message.TransientFlag flag) static booleanisUp(NetworkInterface ni) Always returns true unless there is a socket exception - will be removed when GraalVM issue https://github.com/oracle/graal/pull/1076 has been fixedstatic intleftMembers(Collection<Address> old_list, Collection<Address> new_list) static Class<?> Tries to load the class from the current thread's context class loader.static Class<?> loadClass(String classname, ClassLoader preferredLoader) Tries to load the class from the preferred loader.loadProtocolClass(String protocol_name, Class<?> cl) protected static byte[]marshalPrimitiveType(Byte type, Object obj) static booleanmatch(InetAddress addr, Util.AddressScope scope) static <T> booleanmatch(T obj1, T obj2) static MessagemessageFromBuffer(byte[] buf, int offset, int length, MessageFactory mf) static MessagemessageFromByteBuffer(byte[] buffer, int offset, int length, MessageFactory mf) static ByteArraymessageToBuffer(Message msg) static ByteArraystatic StringmethodNameToAttributeName(String methodName) Converts a method name to an attribute name, e.g.static StringmethodNameToJavaAttributeName(String methodName) Converts a method name to a Java attribute name, e.g.static longmicros()static <T> List<T> newElements(List<T> old_list, List<T> new_list) newMembers(List<Address> old_list, List<Address> new_list) protected static charstatic <T extends Number>
TnonNegativeValue(T num) static <T> TobjectFromBuffer(ByteArray b, ClassLoader loader) static <T> TobjectFromByteBuffer(byte[] buffer) Creates an object from a byte bufferstatic <T> TobjectFromByteBuffer(byte[] buffer, int offset, int length) static <T> TobjectFromByteBuffer(byte[] buffer, int offset, int length, ClassLoader loader) static <T> TobjectFromByteBuffer(ByteBuffer buffer, ClassLoader loader) Parses an object from aByteBuffer.static <T> Tstatic <T> TobjectFromStream(DataInput in, ClassLoader loader) static ByteArrayobjectToBuffer(Object obj) Serializes/Streams an object into a byte buffer.static byte[]objectToByteBuffer(Object obj) static voidobjectToStream(Object obj, DataOutput out) 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.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"]static voidparse(byte[] buf, int offset, int length, BiConsumer<Short, Message> msg_consumer, BiConsumer<Short, MessageBatch> batch_consumer, Consumer<GossipData> gossip_consumer, boolean tcp, boolean gossip) static voidparse(InputStream input, BiConsumer<Short, Message> msg_consumer, BiConsumer<Short, MessageBatch> batch_consumer, Consumer<GossipData> gossip_consumer, boolean tcp, boolean gossip) static List<PhysicalAddress> parseCommaDelimitedHosts(String hosts, int port_range) Input is "daddy[8880],sindhu[8880],camille[5555]".static List<InetSocketAddress> parseCommaDelimitedHosts2(String hosts, int port_range) Input is "daddy[8880],sindhu[8880],camille[5555]".static booleanparseCommaDelimitedHostsInto(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 IpAddressese.g.static InetSocketAddressParses a host:IP string into an InetSocketAddressstatic List<NetworkInterface> static RejectedExecutionHandlerparseRejectionPolicy(String rejection_policy) static String[]parseStringArray(String s, String separator) parseStringList(String l, String separator) static booleanpatternMatch(String pattern, String str) protected static <E> List<E> protected static <E> voidstatic <E> voidInefficient permutation of a generic list; uses too much copying among other things.static <T> Tstatic <T> List<T> Returns the next min(N,list.size()) elements after objstatic <T> TpickPrevious(List<T> list, T el) static <T> TpickPrevious(T[] array, T el) Returns the element before el.static <T> TpickRandomElement(Collection<T> set) static <T> TpickRandomElement(List<T> list) static <T> TpickRandomElement(T[] array) static <T> Tstatic <T> TprimitiveFromStream(DataInput in, byte type) static voidprimitiveToStream(Object obj, DataOutput out) static Stringstatic Stringstatic <T> Stringprint(Collection<T> objs) static Stringprint(List<NetworkInterface> interfaces) static <T> Stringstatic StringprintBytes(double bytes) MB nowadays doesn't mean 1024 * 1024 bytes, but 1 million bytes, see http://en.wikipedia.org/wiki/Megabytestatic <T> StringprintList(Collection<T> l) static <T> StringprintListWithDelimiter(Collection<T> list, String delimiter) static <T> StringprintListWithDelimiter(Collection<T> list, String delimiter, int limit) static <T> StringprintListWithDelimiter(Collection<T> list, String delimiter, int limit, boolean print_size) static <T> StringprintListWithDelimiter(T[] list, String delimiter, int limit) static <T> StringprintMapWithDelimiter(Map<T, T> map, String delimiter) static Stringstatic StringprintViews(JChannel... channels) static booleanproductGreaterThan(long n1, long n2, long val) static longrandom(long range) Returns a random value in the range [1 - range].static <T extends Streamable>
T[]static AddressreadAddress(DataInput in) static Address[]static <T extends Collection<Address>>
TreadAddresses(DataInput in, IntFunction<T> factory) static byte[]static ByteArrayreadBytes(InputStream in) Reads all bytes from an input stream, until eof (-1) is reachedstatic doublereadBytesDouble(String input) static intreadBytesInteger(String input) static longreadBytesLong(String input) static StringreadContents(InputStream input) static StringreadContents(InputStream input, char comment) static doublereadDoubleFromStdin(String message) readDuration(String input) static intreadDurationInt(String input, TimeUnit unit) static longreadDurationLong(String input, TimeUnit unit) protected static ThrowablereadException(DataInput in, int recursion_count) static Stringstatic byte[]readFileContents(InputStream input) static <T extends Streamable>
Tstatic <T extends Streamable>
TreadGenericStreamable(DataInput in, ClassLoader loader) static intreadIntFromStdin(String message) static StringreadLine(InputStream in) Reads a line of text.static longreadLongFromStdin(String message) static MessagereadMessage(DataInput in, MessageFactory mf) static MessageBatch[]readMessageBatch(DataInput in, boolean multicast, MessageFactory factory) Reads a list of messages into 2 MessageBatches: regular OOBreadMessageList(DataInput in, short transport_id, MessageFactory mf) private static Addressstatic SizeStreamablereadSizeStreamable(DataInput in, ClassLoader loader) static <T extends Streamable>
TreadStreamable(Supplier<T> factory, DataInput in) static StringreadString(DataInput in) static StringreadStringFromStdin(String message) static StringreadTillMatchingCharacter(InputStream in, char c) Returns all characters read from the current position until the next occurrence of 'c' has been read (including 'c'), or eof, whichever comes firststatic StringreadToken(InputStream in) Returns whitespace-separated strings from the input stream, or null if the end of the stream has been reachedstatic Viewstatic ViewIdreadViewId(DataInput in) private static voidstatic voidregisterChannel(JChannel channel, String name) static voidremoveFromViews(Address mbr, JChannel... channels) static voidresetCacheAddresses(boolean reset_interfaces, boolean reset_addresses) static booleanChecks whether 2 Addresses are on the same hoststatic voidsetCacheAddresses(List<NetworkInterface> interfaces, List<InetAddress> addresses) This is a workaround for use within android.static voidstatic bytesetFlag(byte bits, byte flag) static Stringstatic StringshortName(InetAddress hostname) static <T> voidshuffle(T[] array, int from, int to) Reorders elements of an array in-place.static voidDrops messages to/from other members and then closes the channel.static intsize(byte[] buf) static intstatic intstatic longsize(Collection<? extends Address> addrs) Returns the marshalled size of a Collection of Addresses.static intstatic longstatic intstatic intstatic intstatic intsizePrimitive(Object obj) protected static voidskipUntilEndOfLine(InputStream input) static voidsleep(long timeout) Sleep for timeout msecs.static voidsleep(long timeout, int nanos) static voidsleepRandom(long floor, long ceiling) Sleeps between floor and ceiling milliseconds, chosen randomlystatic booleanPerforms the flush of the given channelstatic booleanstartFlush(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.static booleanstartFlush(JChannel c, List<Address> flushParticipants) Performs the flush of the given channel and the specified flush participantsstatic booleanstartFlush(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.static <T extends Streamable>
TstreamableFromBuffer(Supplier<T> factory, byte[] buf, int off, int len) static <T extends Streamable>
TstreamableFromByteBuffer(Class<? extends Streamable> cl, byte[] buffer) static <T extends Streamable>
TstreamableFromByteBuffer(Class<? extends Streamable> cl, byte[] buffer, int offset, int length) static <T extends Streamable>
TstreamableFromByteBuffer(Class<? extends Streamable> cl, ByteBuffer buffer) static <T extends Streamable>
TstreamableFromByteBuffer(Supplier<T> factory, byte[] buffer) static <T extends Streamable>
TstreamableFromByteBuffer(Supplier<T> factory, byte[] buffer, int offset, int length) static ByteArraystatic byte[]static byte[]stringToBytes(String str) static StringsubstituteVariable(String val) Replaces variables of ${var:default} with System.getProperty(var, default).static StringsubstituteVariable(String input, Properties p) Replaces variables in a string.static StringsubstituteVariableOld(String val, Properties p) Replaces variables of ${var:default} with Properties then uses System.getProperty(var, default) if the value was not found.static Stringprotected static <E> List<E> static booleantossWeightedCoin(double probability) Tosses a coin weighted with probability and returns true or false.static StringtransientFlagsToString(short flags) static StringutcEpoch(long milliseconds) static StringutcNow()static InetAddressvalidateBindAddressFromInterface(InetAddress bind_addr, String bind_interface_str, StackType ip_version) Method used by PropertyConverters.BindInterface to check that a bind_addr is consistent with a specified interfacestatic booleanverifyArray(byte[] array) static booleanstatic booleanstatic voidwaitUntil(long timeout, long interval, BooleanSupplier condition) static voidwaitUntil(long timeout, long interval, BooleanSupplier condition, Supplier<String> msg) static voidwaitUntilAllChannelsHaveSameView(long timeout, long interval, Collection<JChannel> channels) static voidwaitUntilAllChannelsHaveSameView(long timeout, long interval, JChannel... channels) Blocks until all channels have the same viewstatic <T> voidwaitUntilListHasSize(List<T> list, int expected_size, long timeout, long interval) Waits until a list has the expected number of elements.static booleanwaitUntilNoX(long timeout, long interval, BooleanSupplier condition) static booleanwaitUntilTrue(long timeout, long interval, BooleanSupplier condition) static ByteBufferwrapDirect(byte[] array) static ByteBufferwrapDirect(byte[] array, int offset, int length) static <T extends Streamable>
voidwrite(T[] array, DataOutput out) static voidwriteAddress(Address addr, DataOutput out) static voidwriteAddresses(Collection<? extends Address> v, DataOutput out) Writes a list of Addresses.static voidwriteAddresses(Address[] addrs, DataOutput out) static voidwriteByteBuffer(byte[] buf, int offset, int length, DataOutput out) static voidwriteByteBuffer(byte[] buf, DataOutput out) protected static voidwriteException(Set<Throwable> causes, Throwable t, DataOutput out) static voidwriteGenericStreamable(Streamable obj, DataOutput out) static voidwriteMessage(Message msg, DataOutput dos, boolean multicast) static voidwriteMessageList(Address dest, Address src, byte[] cluster_name, List<Message> msgs, DataOutput dos, boolean multicast) Write a list of messages with the *same* destination and src addresses.static voidwriteMessageList(Address dest, Address src, byte[] cluster_name, Message[] msgs, int offset, int length, DataOutput dos, boolean multicast) static voidwriteMessageList(Address dest, Address src, byte[] cluster_name, FastArray<Message> msgs, DataOutput dos, boolean multicast) static voidwriteMessageListHeader(Address dest, Address src, byte[] cluster_name, int numMsgs, DataOutput dos, boolean multicast) private static voidwriteOtherAddress(Address addr, DataOutput out) protected static ByteArraywriteSerializable(Object obj) protected static ByteArraystatic voidwriteStreamable(Streamable obj, DataOutput out) static voidwriteString(String str, DataOutput out) static voidwriteTypeStreamable(Streamable obj, DataOutput out) static voidwriteView(View view, DataOutput out) static voidwriteViewId(ViewId vid, DataOutput out)
-
Field Details
-
TYPES
-
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
-
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
-
MAX_LIST_PRINT_SIZE
public static int MAX_LIST_PRINT_SIZEThe 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
-
CACHED_INTERFACES
-
CACHED_ADDRESSES
-
can_bind_to_mcast_addr
public static final boolean can_bind_to_mcast_addr -
resource_bundle
-
UTF_FORMAT
-
UUID_PREFIX
- See Also:
-
SITE_UUID_PREFIX
- See Also:
-
IP_PREFIX
- See Also:
-
OTHER_ADDR
- See Also:
-
RANDOM
-
FUNC
-
LONG_ARRAY_VIEW
-
INT_ARRAY_VIEW
-
-
Constructor Details
-
Util
public Util()
-
-
Method Details
-
getUnicastProtocols
-
fibersAvailable
Deprecated. -
virtualThreadsAvailable
public static boolean virtualThreadsAvailable() -
getNextHigherPowerOfTwo
public static int getNextHigherPowerOfTwo(int num) -
bold
-
getMessage
-
getTestStack
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 mschannels- 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
-
waitUntilTrue
-
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
-
allChannelsHaveSameView
-
assertAllChannelsHaveSameView
-
printViews
-
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 listexpected_size- The expected sizetimeout- The time to wait (in ms)interval- The interval at which to get the size of the list (in ms)
-
removeFromViews
-
createEnum
Creates an enum from a string -
createAuthenticationDigest
public static byte[] createAuthenticationDigest(String passcode, long t1, double q1) throws IOException, NoSuchAlgorithmException - Throws:
IOExceptionNoSuchAlgorithmException
-
createDigest
public static byte[] createDigest(String passcode, long t1, double q1) throws IOException, NoSuchAlgorithmException - Throws:
IOExceptionNoSuchAlgorithmException
-
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
- Throws:
IOException
-
close
-
close
-
closeReverse
-
closeFast
Closes all non-coordinators first, in parallel, then closes the coord. This should produce just 2 views -
shutdown
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
-
transientFlagsToString
-
isFlagSet
-
isTransientFlagSet
-
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
Creates an object from a byte buffer- Throws:
IOExceptionClassNotFoundException
-
objectFromByteBuffer
public static <T> T objectFromByteBuffer(byte[] buffer, int offset, int length) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
objectFromBuffer
public static <T> T objectFromBuffer(ByteArray b, ClassLoader loader) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
objectFromByteBuffer
public static <T> T objectFromByteBuffer(byte[] buffer, int offset, int length, ClassLoader loader) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
objectFromByteBuffer
Parses an object from aByteBuffer. Note that this changes the position of the buffer, so it this is not desired, useByteBuffer.duplicate()to create a copy and pass the copy to this method.- Throws:
Exception
-
objectToByteBuffer
- Throws:
IOException
-
objectToBuffer
Serializes/Streams an object into a byte buffer. The object has to implement interface Serializable or Externalizable or Streamable.- Throws:
IOException
-
writeStreamable
- Throws:
IOException
-
writeSerializable
- Throws:
IOException
-
marshalPrimitiveType
-
writeString
- Throws:
IOException
-
readString
- Throws:
IOException
-
size
-
size
-
sizePrimitive
-
writeTypeStreamable
- Throws:
IOException
-
primitiveToStream
- Throws:
IOException
-
primitiveFromStream
- Throws:
IOException
-
primitiveFromStream
- Throws:
IOException
-
objectToStream
- Throws:
IOException
-
objectFromStream
- Throws:
IOExceptionClassNotFoundException
-
objectFromStream
public static <T> T objectFromStream(DataInput in, ClassLoader loader) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
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
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
- Throws:
IOException
-
exceptionFromStream
public static Throwable exceptionFromStream(DataInput in) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
exceptionFromStream
protected static Throwable exceptionFromStream(DataInput in, int recursion_count) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
add
-
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:
IOExceptionClassNotFoundException
-
exceptionFromBuffer
public static Throwable exceptionFromBuffer(byte[] buf, int offset, int length) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
bufferToArray
Returns a copy of the byte array between position and limit; requires a non-null buffer -
bufferToArray
-
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:
IOExceptionClassNotFoundException
-
streamableToByteBuffer
- Throws:
IOException
-
streamableToBuffer
- Throws:
Exception
-
messageToBuffer
- Throws:
Exception
-
messageFromBuffer
public static Message messageFromBuffer(byte[] buf, int offset, int length, MessageFactory mf) throws Exception - Throws:
Exception
-
messageToByteBuffer
- Throws:
Exception
-
messageFromByteBuffer
public static Message messageFromByteBuffer(byte[] buffer, int offset, int length, MessageFactory mf) throws Exception - Throws:
Exception
-
getObject
Tries to return a legible representation of a message's payload -
getObjects
-
wrapDirect
-
wrapDirect
-
collectionToByteBuffer
- Throws:
IOException
-
stringToBytes
-
bytesToString
-
byteArrayToHexString
-
byteArrayToHexString
-
isAsciiString
-
hexToBin
-
compare
public static int compare(byte[] left, byte[] right) Compares 2 byte arrays, elements are treated as unigned -
convert
-
writeMessage
- Throws:
IOException
-
readMessage
public static Message readMessage(DataInput in, MessageFactory mf) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
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:
IOExceptionClassNotFoundException
-
readMessageBatch
public static MessageBatch[] readMessageBatch(DataInput in, boolean multicast, MessageFactory factory) throws IOException, ClassNotFoundException Reads a list of messages into 2 MessageBatches:- regular
- OOB
- Returns:
- an array of 2 MessageBatches in the order above, the first batch is at index 0
- Throws:
IOExceptionClassNotFoundException
-
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
- Throws:
IOException
-
readView
- Throws:
IOExceptionClassNotFoundException
-
writeViewId
- Throws:
IOException
-
readViewId
- Throws:
IOExceptionClassNotFoundException
-
writeAddress
- Throws:
IOException
-
readAddress
- Throws:
IOExceptionClassNotFoundException
-
size
-
size
-
size
-
size
-
size
public static int size(byte[] buf) -
readOtherAddress
- Throws:
IOExceptionClassNotFoundException
-
writeOtherAddress
- 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
- Throws:
IOException
-
readAddresses
public static <T extends Collection<Address>> T readAddresses(DataInput in, IntFunction<T> factory) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
readAddresses
- Throws:
IOExceptionClassNotFoundException
-
size
Returns the marshalled size of a Collection of Addresses. Assumes elements are of the same type !- Parameters:
addrs- Collection- Returns:
- long size
-
size
-
addressToString
-
addressFromString
- Throws:
Exception
-
writeStreamable
- Throws:
IOException
-
readStreamable
public static <T extends Streamable> T readStreamable(Supplier<T> factory, DataInput in) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
writeGenericStreamable
- Throws:
IOException
-
readGenericStreamable
public static <T extends Streamable> T readGenericStreamable(DataInput in) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
readGenericStreamable
public static <T extends Streamable> T readGenericStreamable(DataInput in, ClassLoader loader) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
readSizeStreamable
public static SizeStreamable readSizeStreamable(DataInput in, ClassLoader loader) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
write
- Throws:
IOException
-
read
- Throws:
Exception
-
readFile
- Throws:
FileNotFoundException
-
readContents
-
readContents
-
skipUntilEndOfLine
-
readFileContents
- Throws:
IOException
-
readToken
Returns whitespace-separated strings from the input stream, or null if the end of the stream has been reached -
readTillMatchingCharacter
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
- Throws:
Exception
-
readLongFromStdin
- Throws:
Exception
-
readDoubleFromStdin
- Throws:
Exception
-
readIntFromStdin
- Throws:
Exception
-
writeByteBuffer
- Throws:
IOException
-
writeByteBuffer
public static void writeByteBuffer(byte[] buf, int offset, int length, DataOutput out) throws IOException - Throws:
IOException
-
readByteBuffer
- Throws:
IOException
-
match
public static <T> boolean match(T obj1, T obj2) -
patternMatch
-
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
-
available
-
micros
public static long micros() -
factorial
public static int factorial(int n) -
permute
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 listpermutations- All permutations will be added to this list (as copies)
-
permute
-
car
-
cdr
-
combine
-
combine
-
combine
-
swap
-
orderedPermutation
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
-
checkOrder
-
index
-
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 modifiedfrom- the start index inclusiveto- the end index (exclusive), must be >= from (not checked)
-
enumerate
-
enumerate
public static <T,R> Enumeration<R> enumerate(T[] array, int offset, int length, Function<T, R> converter) -
nonNegativeValue
-
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
-
dumpThreadInfo
-
blockedState
-
interruptAndWaitToDie
-
interruptAndWaitToDie
-
printTime
-
suffix
-
print
-
readBytesLong
-
readBytesInteger
-
readBytesDouble
-
readBytes
-
readDurationLong
-
readDurationInt
-
readDuration
-
printBytes
MB nowadays doesn't mean 1024 * 1024 bytes, but 1 million bytes, see http://en.wikipedia.org/wiki/Megabyte- Parameters:
bytes-
-
format
-
components
-
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
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
-
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
Returns true if all elements in the collection are the same -
printList
-
printListWithDelimiter
-
printListWithDelimiter
-
printListWithDelimiter
public static <T> String printListWithDelimiter(Collection<T> list, String delimiter, int limit, boolean print_size) -
printListWithDelimiter
-
printMapWithDelimiter
-
leftMembers
-
newMembers
-
newElements
-
contains
public static <T> boolean contains(T key, T[] list) -
containsViewId
-
containsId
public static boolean containsId(short id, short[] ids) -
determineMergeParticipants
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
This is the same or a subset ofdetermineMergeParticipants(java.util.Map)and contains only members which are currently sub-partition coordinators.- Parameters:
map-- Returns:
-
determineActualMergeCoords
Similar todetermineMergeCoords(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
Returns the rank of a member in a given view- Parameters:
view- The viewaddr- 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
-
pickRandomElement
-
pickRandomElement
-
pickRandomElement
public static <T> T pickRandomElement(T[] array) -
pickNext
-
pickNext
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
-
generateArray
public static byte[] generateArray(int length) -
verifyArray
public static boolean verifyArray(byte[] array) -
verifyByteBuffer
-
createRandomAddress
-
createRandomAddresses
Returns an array of num random addresses, named A, B, C etc -
createRandomAddresses
-
createRandomAddress
-
createTimer
-
determineLeftMembers
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
-
print
-
print
-
loadClass
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 objectfilter- The filter. Needs to be able to handle Fields and Methods (superclass:AccessibleObject). If null, all fields/methods will be selectedfield_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
-
getAllDeclaredMethodsWithAnnotations
@SafeVarargs public static Method[] getAllDeclaredMethodsWithAnnotations(Class<?> clazz, Class<? extends Annotation>... annotations) -
getAnnotation
-
getField
-
getField
public static Field getField(Class<?> clazz, String field_name, boolean throw_exception) throws NoSuchFieldException - Throws:
NoSuchFieldException
-
setField
-
getField
-
findField
-
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
The method walks up the class hierarchy and returns all methods of this class and those inherited from superclasses and superinterfaces. -
getComponents
Returns the non-null values of all fields of target annotated with @Component -
forAllComponents
Applies a function to all fields annotated with @Component- Parameters:
target- The target objectfunc- The function accepting the value of the field and the component name (prefix)
-
forAllComponentTypes
-
isPrimitiveType
-
isPrimitiveType
-
findMethod
-
findMethod
-
findMethod
-
findClassesAssignableFrom
public static Set<Class<?>> findClassesAssignableFrom(String packageName, Class<?> assignableFrom, ClassLoader cl) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
findClassesAssignableFromPath
public static Set<Class<?>> findClassesAssignableFromPath(String packagePath, Class<?> assignableFrom, ClassLoader cl) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
findClassesAnnotatedWith
public static List<Class<?>> findClassesAnnotatedWith(String packageName, Class<? extends Annotation> a) throws IOException, ClassNotFoundException - Throws:
IOExceptionClassNotFoundException
-
recurse
private static void recurse(List<Class<?>> classes, String packageName, Class<? extends Annotation> a) throws ClassNotFoundException - Throws:
ClassNotFoundException
-
getResourceAsStream
-
getResourceAsStream
-
getChild
-
sameHost
Checks whether 2 Addresses are on the same host -
parseRejectionPolicy
-
parseCommaDelimitedStrings
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 elementsunresolved_hosts- A list of unresolved hostshosts- The string with host:port pairsport_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
Parses a host:IP string into an InetSocketAddress -
parseStringList
-
parseStringArray
-
readLine
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
Reads all bytes from an input stream, until eof (-1) is reached- Throws:
IOException
-
parseInterfaceList
- Throws:
Exception
-
print
-
shortName
-
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 channelflushParticipants- the flush participants in this flush attemptnumberOfAttempts- the number of flush attemptsrandomSleepTimeoutFloor- the minimum sleep time between attempts in msrandomSleepTimeoutCeiling- the maximum sleep time between attempts in ms- Returns:
- true if channel was flushed successfully, false otherwise
- See Also:
-
startFlush
Performs the flush of the given channel and the specified flush participants- Parameters:
c- the channelflushParticipants- 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 channelnumberOfAttempts- the number of flush attemptsrandomSleepTimeoutFloor- the minimum sleep time between attempts in msrandomSleepTimeoutCeiling- the maximum sleep time between attempts in ms- Returns:
- true if channel was flushed successfully, false otherwise
- See Also:
-
startFlush
Performs the flush of the given channel- Parameters:
c- the channel- Returns:
- true if channel was flushed successfully, false otherwise
- See Also:
-
shortName
-
generateLocalName
-
createConcurrentMap
public static <K,V> ConcurrentMap<K,V> createConcurrentMap(int initial_capacity, float load_factor, int concurrency_level) -
createConcurrentMap
-
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 interfaceIdea: 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:
UnknownHostExceptionSocketException
-
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
-
checkForPresence
-
contains
-
getLoopback
IP related utilities- Throws:
UnknownHostException
-
getLoopback
- Throws:
UnknownHostException
-
getNonLoopbackAddress
Returns the first non-loopback address on any interface on the current host- Throws:
SocketException
-
getNonLoopbackAddress
- Throws:
SocketException
-
getByName
Finds a network interface or sub-interface with the given name- Throws:
SocketException
-
getByName
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 hostip_version- The IP version, e.g.StackType.IPv4orStackType.IPv6- Returns:
- The resolved address
- Throws:
UnknownHostException- Thrown if host cannot be resolved to an InetAddress
-
getAddress
- 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
-
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
- Throws:
Exception
-
isUp
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
-
_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
- 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
Returns all addresses of all interfaces (that are up) that satisfy a given filter (ignored if null) -
getAllAvailableAddresses
-
checkIfValidAddress
- 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 fileprop_name- The name of the property, will be removed from props if founddefault_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
-
isCoordinator
-
getMBeanServer
-
registerChannel
-
substituteVariable
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
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
Replaces variables in a string.- Parameters:
input- The input stringp- 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
-
_substituteVar
-
getProperty
-
getProperty
-
_getProperty
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
Converts a method name to an attribute name, e.g. getFooBar() to foo_bar, isFlag to flag -
methodNameToJavaAttributeName
Converts a method name to a Java attribute name, e.g. getFooBar() to fooBar, isFlag to flag.- Parameters:
methodName-- Returns:
-
attributeNameToMethodName
-
getSites
-
otherSites
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
-
utcEpoch
-