repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/NullValue.java
|
package org.infinispan.commons.util;
import java.io.Serializable;
import org.infinispan.commons.marshall.ProtoStreamTypeIds;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoTypeId;
/**
* A placeholder for {@literal null} in a cache, because caches do not allow {@literal null} values.
*
* @author Dan Berindei
* @since 13.0
*/
@ProtoTypeId(ProtoStreamTypeIds.NULL_VALUE)
public final class NullValue implements Serializable {
private static final long serialVersionUID = 2860710533033240004L;
public static final NullValue NULL = new NullValue();
private NullValue() {
}
private Object readResolve() {
return NULL;
}
@ProtoFactory
public static NullValue getInstance() {
return NULL;
}
// Object implementations of equals() and hashCode() work fine
}
| 870
| 23.194444
| 100
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/CloseableIteratorSet.java
|
package org.infinispan.commons.util;
import java.util.Set;
/**
* A set that defines an iterator method that returns a {@link org.infinispan.commons.util.CloseableIterator}
* instead of a non closeable one. This is needed so that iterators can be properly cleaned up. All other
* methods will internally clean up any iterators created and don't have other side effects.
*
* @author wburns
* @since 7.0
*/
public interface CloseableIteratorSet<E> extends Set<E>, CloseableIteratorCollection<E> {
@Override
CloseableSpliterator<E> spliterator();
}
| 563
| 30.333333
| 109
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ReflectionUtil.java
|
package org.infinispan.commons.util;
import static org.infinispan.commons.logging.Log.CONTAINER;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.infinispan.commons.CacheException;
/**
* Basic reflection utilities to enhance what the JDK provides.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
public class ReflectionUtil {
private static final String[] EMPTY_STRING_ARRAY = {};
private static final Class<?>[] primitives = {int.class, byte.class, short.class, long.class,
float.class, double.class, boolean.class, char.class};
private static final Class<?>[] primitiveArrays = {int[].class, byte[].class, short[].class, long[].class,
float[].class, double[].class, boolean[].class, char[].class};
public static final Class<?>[] EMPTY_CLASS_ARRAY = new Class[0];
/**
* Returns a set of Methods that contain the given method annotation. This includes all public, protected, package
* and private methods, as well as those of superclasses. Note that this does *not* include overridden methods.
*
* @param c class to inspect
* @param annotationType the type of annotation to look for
* @return List of Method objects that require injection.
*/
public static List<Method> getAllMethods(Class<?> c, Class<? extends Annotation> annotationType) {
List<Method> annotated = new ArrayList<>();
inspectRecursively(c, annotated, annotationType);
return annotated;
}
private static void getAnnotatedFieldHelper(List<Field> list, Class<?> c, Class<? extends Annotation> annotationType) {
Field[] declaredFields = c.getDeclaredFields();
for (Field field : declaredFields) {
if (field.isAnnotationPresent(annotationType)) {
list.add(field);
}
}
}
public static Method findMethod(Class<?> type, String methodName) {
try {
return type.getDeclaredMethod(methodName);
} catch (NoSuchMethodException e) {
if (type.equals(Object.class) || type.isInterface()) {
throw new CacheException(e);
}
return findMethod(type.getSuperclass(), methodName);
}
}
public static Method findMethod(Class<?> type, String methodName, Class<?>... parameters) {
try {
return type.getDeclaredMethod(methodName, parameters);
} catch (NoSuchMethodException e) {
if (type.equals(Object.class) || type.isInterface()) {
throw new CacheException(e);
}
return findMethod(type.getSuperclass(), methodName, parameters);
}
}
/**
* Inspects a class and its superclasses (all the way to {@link Object} for method instances that contain a given
* annotation. This even identifies private, package and protected methods, not just public ones.
*/
private static void inspectRecursively(Class<?> c, List<Method> s, Class<? extends Annotation> annotationType) {
for (Method m : c.getDeclaredMethods()) {
// don't bother if this method has already been overridden by a subclass
if (notFound(m, s) && m.isAnnotationPresent(annotationType)) {
s.add(m);
}
}
if (!c.equals(Object.class)) {
if (!c.isInterface()) {
inspectRecursively(c.getSuperclass(), s, annotationType);
}
for (Class<?> ifc : c.getInterfaces()) inspectRecursively(ifc, s, annotationType);
}
}
private static void inspectFieldsRecursively(Class<?> c, List<Field> s, Class<? extends Annotation> annotationType) {
if (c == null || c.isInterface()) {
return;
}
for (Field f : c.getDeclaredFields()) {
if (f.isAnnotationPresent(annotationType)) {
s.add(f);
}
}
if (!c.equals(Object.class)) {
inspectFieldsRecursively(c.getSuperclass(), s, annotationType);
}
}
/**
* Tests whether a method has already been found, i.e., overridden.
*
* @param m method to inspect
* @param s collection of methods found
* @return true a method with the same signature already exists.
*/
private static boolean notFound(Method m, Collection<Method> s) {
for (Method found : s) {
if (m.getName().equals(found.getName()) &&
Arrays.equals(m.getParameterTypes(), found.getParameterTypes()))
return false;
}
return true;
}
private static Field findFieldRecursively(Class<?> c, String fieldName) {
Field f = null;
try {
f = c.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
if (!c.equals(Object.class)) f = findFieldRecursively(c.getSuperclass(), fieldName);
}
return f;
}
/**
* Invokes a method using reflection, in an accessible manner (by using {@link Method#setAccessible(boolean)}
*
* @param instance instance on which to execute the method
* @param method method to execute
* @param parameters parameters
*/
public static Object invokeAccessibly(Object instance, Method method, Object... parameters) {
method.setAccessible(true);
return invokeMethod(instance, method, parameters);
}
public static Object invokeMethod(Object instance, Method method, Object[] parameters) {
try {
return method.invoke(instance, parameters);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause() != null ? e.getCause() : e;
throw new CacheException("Unable to invoke method " + method + " on object of type " + (instance == null ? "null" : instance
.getClass().getSimpleName()) +
(parameters != null ? " with parameters " + Arrays.asList(parameters) : ""), cause);
} catch (Exception e) {
throw new CacheException("Unable to invoke method " + method + " on object of type " + (instance == null ? "null" : instance
.getClass().getSimpleName()) +
(parameters != null ? " with parameters " + Arrays.asList(parameters) : ""), e);
}
}
public static void setAccessible(final Method m) {
try {
m.setAccessible(true);
} catch (Exception e) {
throw new CacheException("Unable to change method accessibility " + m, e);
}
}
public static void setAccessibly(Object instance, Field field, Object value) {
field.setAccessible(true);
setField(instance, field, value);
}
public static void setField(Object instance, Field field, Object value) {
try {
field.set(instance, value);
} catch (Exception e) {
throw new CacheException("Unable to set field " + field.getName() + " on object of type " +
(instance == null ? "null" : instance.getClass().getName()) + " to " + value, e);
}
}
public static Method findGetterForField(Class<?> c, String fieldName) {
Method retval = findGetterForFieldUsingReflection(c, fieldName);
if (retval == null) {
if (!c.equals(Object.class)) {
if (!c.isInterface()) {
retval = findGetterForField(c.getSuperclass(), fieldName);
if (retval == null) {
for (Class<?> ifc : c.getInterfaces()) {
retval = findGetterForField(ifc, fieldName);
if (retval != null) break;
}
}
}
}
}
return retval;
}
private static Method findGetterForFieldUsingReflection(Class<?> c, String fieldName) {
for (Method m : c.getDeclaredMethods()) {
String name = m.getName();
String s = null;
if (name.startsWith("get")) {
s = name.substring(3);
} else if (name.startsWith("is")) {
s = name.substring(2);
}
if (s != null && s.equalsIgnoreCase(fieldName)) {
return m;
}
}
return null;
}
public static Method findSetterForField(Class<?> c, String fieldName) {
if (c == Object.class) {
return null;
}
for (Method m : c.getDeclaredMethods()) {
String name = m.getName();
String s = null;
if (name.startsWith("set")) {
s = name.substring(3);
}
if (s != null && s.equalsIgnoreCase(fieldName)) {
return m;
}
}
// Try parent class until we run out
return findSetterForField(c.getSuperclass(), fieldName);
}
public static String extractFieldName(String setterOrGetter) {
String field = null;
if (setterOrGetter.startsWith("set") || setterOrGetter.startsWith("get"))
field = setterOrGetter.substring(3);
else if (setterOrGetter.startsWith("is"))
field = setterOrGetter.substring(2);
if (field != null && field.length() > 1) {
StringBuilder sb = new StringBuilder();
sb.append(Character.toLowerCase(field.charAt(0)));
if (field.length() > 2) sb.append(field.substring(1));
return sb.toString();
}
return null;
}
/**
* Retrieves the value of a field of an object instance via reflection
*
* @param instance to inspect
* @param fieldName name of field to retrieve
* @return a value
*/
public static Object getValue(Object instance, String fieldName) {
Field f = findFieldRecursively(instance.getClass(), fieldName);
if (f == null) throw new CacheException("Could not find field named '" + fieldName + "' on instance " + instance);
try {
f.setAccessible(true);
return f.get(instance);
} catch (IllegalAccessException iae) {
throw new CacheException("Cannot access field " + f, iae);
}
}
/**
* Inspects the class passed in for the class level annotation specified. If the annotation is not available, this
* method recursively inspects superclasses and interfaces until it finds the required annotation.
* <p/>
* Returns null if the annotation cannot be found.
*
* @param clazz class to inspect
* @param ann annotation to search for. Must be a class-level annotation.
* @return the annotation instance, or null
*/
public static <T extends Annotation> T getAnnotation(Class<?> clazz, Class<T> ann) {
while (true) {
// first check class
T a = clazz.getAnnotation(ann);
if (a != null) return a;
// check interfaces
if (!clazz.isInterface()) {
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> inter : interfaces) {
a = getAnnotation(inter, ann);
if (a != null) return a;
}
}
// check superclasses
Class<?> superclass = clazz.getSuperclass();
if (superclass == null) return null; // no where else to look
clazz = superclass;
}
}
/**
* Tests whether an annotation is present on a class. The order tested is: <ul> <li>The class itself</li> <li>All
* implemented interfaces</li> <li>Any superclasses</li> </ul>
*
* @param clazz class to test
* @param annotation annotation to look for
* @return true if the annotation is found, false otherwise
*/
public static boolean isAnnotationPresent(Class<?> clazz, Class<? extends Annotation> annotation) {
return getAnnotation(clazz, annotation) != null;
}
public static Class<?>[] toClassArray(String[] typeList, ClassLoader classLoader) throws ClassNotFoundException {
if (typeList == null) return EMPTY_CLASS_ARRAY;
Class<?>[] retval = new Class[typeList.length];
int i = 0;
for (String s : typeList) retval[i++] = getClassForName(s, classLoader);
return retval;
}
public static Class<?> getClassForName(String name, ClassLoader cl) throws ClassNotFoundException {
try {
return Util.loadClassStrict(name, cl);
} catch (ClassNotFoundException cnfe) {
// Could be a primitive - let's check
for (Class<?> primitive : primitives) if (name.equals(primitive.getName())) return primitive;
for (Class<?> primitive : primitiveArrays) if (name.equals(primitive.getName())) return primitive;
}
throw new ClassNotFoundException("Class " + name + " cannot be found");
}
public static String[] toStringArray(Class<?>[] classes) {
if (classes == null)
return EMPTY_STRING_ARRAY;
else {
String[] classNames = new String[classes.length];
for (int i=0; i<classes.length; i++) classNames[i] = classes[i].getName();
return classNames;
}
}
public static Field getField(String fieldName, Class<?> objectClass) {
try {
return objectClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
if (!objectClass.equals(Object.class)) {
return getField(fieldName, objectClass.getSuperclass());
} else {
return null;
}
}
}
public static <T> T unwrap(Object obj, Class<T> clazz) {
if (clazz != null && clazz.isAssignableFrom(obj.getClass()))
return clazz.cast(obj);
throw CONTAINER.unableToUnwrap(obj, clazz);
}
public static <T> T unwrapAny(Class<T> clazz, Object... objs) {
if (clazz != null) {
for (Object o : objs) {
if (clazz.isAssignableFrom(o.getClass()))
return clazz.cast(o);
}
}
throw CONTAINER.unableToUnwrapAny(Arrays.toString(objs), clazz);
}
public static int getIntAccessibly(Field f, Object instance) {
try {
f.setAccessible(true);
return f.getInt(instance);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
| 14,466
| 36.094872
| 158
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/AbstractDelegatingCollection.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* Delegating collection that delegates all calls to the collection returned from
* {@link AbstractDelegatingCollection#delegate()}
* @param <E> The type of collection
*/
public abstract class AbstractDelegatingCollection<E> implements Collection<E> {
protected abstract Collection<E> delegate();
@Override
public int size() {
return delegate().size();
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public boolean contains(Object o) {
return delegate().contains(o);
}
@Override
public Iterator<E> iterator() {
return delegate().iterator();
}
@Override
public void forEach(Consumer<? super E> action) {
delegate().forEach(action);
}
@Override
public Object[] toArray() {
return delegate().toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return delegate().toArray(a);
}
@Override
public boolean add(E e) {
return delegate().add(e);
}
@Override
public boolean remove(Object o) {
return delegate().remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return delegate().containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
return delegate().addAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return delegate().removeAll(c);
}
@Override
public boolean removeIf(Predicate<? super E> filter) {
return delegate().removeIf(filter);
}
@Override
public boolean retainAll(Collection<?> c) {
return delegate().retainAll(c);
}
@Override
public void clear() {
delegate().clear();
}
@Override
public Spliterator<E> spliterator() {
return delegate().spliterator();
}
@Override
public Stream<E> stream() {
return delegate().stream();
}
@Override
public Stream<E> parallelStream() {
return delegate().parallelStream();
}
}
| 2,231
| 19.477064
| 81
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/BeanUtils.java
|
package org.infinispan.commons.util;
import java.lang.reflect.Method;
import java.util.Locale;
/**
* Simple JavaBean manipulation helper methods
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
public class BeanUtils {
/**
* Retrieves a setter name based on a field name passed in
*
* @param fieldName field name to find setter for
* @return name of setter method
*/
public static String setterName(String fieldName) {
StringBuilder sb = new StringBuilder("set");
if (fieldName != null && fieldName.length() > 0) {
sb.append(fieldName.substring(0, 1).toUpperCase(Locale.ENGLISH));
if (fieldName.length() > 1) {
sb.append(fieldName.substring(1));
}
}
return sb.toString();
}
/**
* Retrieves a setter name based on a field name passed in
*
* @param fieldName field name to find setter for
* @return name of setter method
*/
public static String fluentSetterName(String fieldName) {
StringBuilder sb = new StringBuilder();
if (fieldName != null && fieldName.length() > 0) {
sb.append(fieldName.substring(0, 1));
if (fieldName.length() > 1) {
sb.append(fieldName.substring(1));
}
}
return sb.toString();
}
/**
* Returns a getter for a given class
*
* @param componentClass class to find getter for
* @return name of getter method
*/
public static String getterName(Class<?> componentClass) {
if (componentClass == null) return null;
StringBuilder sb = new StringBuilder("get");
sb.append(componentClass.getSimpleName());
return sb.toString();
}
/**
* Returns a setter for a given class
*
* @param componentClass class to find setter for
* @return name of getter method
*/
public static String setterName(Class<?> componentClass) {
if (componentClass == null) return null;
StringBuilder sb = new StringBuilder("set");
sb.append(componentClass.getSimpleName());
return sb.toString();
}
/**
* Returns a Method object corresponding to a getter that retrieves an instance of componentClass from target.
*
* @param target class that the getter should exist on
* @param componentClass component to get
* @return Method object, or null of one does not exist
*/
public static Method getterMethod(Class<?> target, Class<?> componentClass) {
try {
return target.getMethod(getterName(componentClass));
}
catch (NoSuchMethodException e) {
//if (log.isTraceEnabled()) log.trace("Unable to find method " + getterName(componentClass) + " in class " + target);
return null;
}
catch (NullPointerException e) {
return null;
}
}
/**
* Returns a Method object corresponding to a setter that sets an instance of componentClass from target.
*
* @param target class that the setter should exist on
* @param componentClass component to set
* @return Method object, or null of one does not exist
*/
public static Method setterMethod(Class<?> target, Class<?> componentClass) {
try {
return target.getMethod(setterName(componentClass), componentClass);
}
catch (NoSuchMethodException e) {
//if (log.isTraceEnabled()) log.trace("Unable to find method " + setterName(componentClass) + " in class " + target);
return null;
}
catch (NullPointerException e) {
return null;
}
}
}
| 3,620
| 30.763158
| 126
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/AbstractEntrySizeCalculatorHelper.java
|
package org.infinispan.commons.util;
/**
* Abstract class that provides a method to round up to the nearest value of 8 which is important for most jvm when
* doing size calculations. This is due to the fact that most JVMs align to the nearest 8 bytes for addressing
* purposes.
* {@inheritDoc}
*/
public abstract class AbstractEntrySizeCalculatorHelper<K, V> implements EntrySizeCalculator<K, V> {
// This is how large the object header info is
public static final int OBJECT_SIZE = sun.misc.Unsafe.ADDRESS_SIZE;
// This is how large an object pointer is - note that each object
// has to reference its class
public static final int POINTER_SIZE = sun.misc.Unsafe.ARRAY_OBJECT_INDEX_SCALE;
public static final int HEADER_AND_CLASS_REFERENCE = OBJECT_SIZE + POINTER_SIZE;
public static long roundUpToNearest8(long size) {
return (size + 7) & ~0x7;
}
}
| 890
| 39.5
| 115
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/HopscotchHashMap.java
|
package org.infinispan.commons.util;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;
/**
* Lookup on a table without collisions will require only single access, if there are collisions it will be
* limited to (number of collisions to particular bin + 1) and all those will lie in proximity (32 * reference size).
* Inserts can be O(n) in the worst case when we have to rehash whole table or search through close-to-full for an empty
* spot.
* <p>
* Not thread safe (though, look-ups are safe when there are no concurrent modifications).
*
* @see <a href="https://en.wikipedia.org/wiki/Hopscotch_hashing">Hopscotch hashing</a>
*/
public class HopscotchHashMap<K, V> extends ArrayMap<K, V> {
private static final int H = 32;
private static final int MAX_REHASH_CYCLES = 100;
private int[] hopinfo;
private int a, b, M, m, wM;
private int mask;
public HopscotchHashMap(int initialCapacity) {
// round to nearest power of 2
initialCapacity = Math.max(32, initialCapacity);
wM = Integer.numberOfLeadingZeros(initialCapacity - 1);
M = 32 - wM;
m = 1 << M;
mask = m - 1;
randomizeFunction();
keys = new Object[m];
values = new Object[m];
hopinfo = new int[m];
}
private void randomizeFunction() {
ThreadLocalRandom random = ThreadLocalRandom.current();
a = random.nextInt() | 1; // a should be odd
b = random.nextInt() >>> M;
}
private int bin(int hashCode) {
return ((a * hashCode) + b) >>> wM;
}
@Override
public V get(Object key) {
Objects.requireNonNull(key);
int bin = bin(key.hashCode());
// first, optimistically assume that the key is on its bin
Object storedKey = keys[bin];
if (storedKey != null && storedKey.equals(key)) {
return (V) values[bin];
}
// we can ignore the first position since we already tested it
int bininfo = hopinfo[bin] & ~1;
// try to lookup equal key in neighbourhood
while (bininfo != 0) {
int offset = Integer.numberOfTrailingZeros(bininfo);
int bo = (bin + offset) & mask;
storedKey = keys[bo];
if (storedKey.equals(key)) {
return (V) values[bo];
}
bininfo = bininfo & ~(1 << offset);
}
return null;
}
@Override
public V put(K key, V value) {
Objects.requireNonNull(key);
Objects.requireNonNull(value);
++modCount;
try {
if (shouldGrow()) {
// If the table is utilized close to its capacity the optimistic assumption
// that we can read directly on bin does not hold.
return rehashAndPutInternal(key, value);
} else {
return putInternal(key, value);
}
} catch (RehashException e) {
return rehashAndPutInternal(key, value);
}
}
private V rehashAndPutInternal(K key, V value) {
Object[] oldKeys = keys;
Object[] oldValues = values;
for (int cycle = 0; cycle < MAX_REHASH_CYCLES; ++cycle) {
randomizeFunction();
try {
rehash(oldKeys, oldValues);
return putInternal(key, value);
} catch (RehashException ignored) {
}
}
throw new IllegalStateException("Did not manage to rehash table with " + size + " elements");
}
private void rehash(Object[] oldKeys, Object[] oldValues) throws RehashException {
if (shouldGrow()) {
m *= 2;
mask = m - 1;
++M;
--wM;
}
keys = new Object[m];
values = new Object[m];
if (m > hopinfo.length) {
hopinfo = new int[m];
} else {
Arrays.fill(hopinfo, 0);
}
size = 0;
for (int i = 0; i < oldKeys.length; ++i) {
if (oldKeys[i] == null) {
continue;
}
putInternal(oldKeys[i], oldValues[i]);
}
}
private boolean shouldGrow() {
// keep load factor < 0.5 if possible, and m <= 2^31
return size * 2 >= m && wM > 1;
}
private V putInternal(Object key, Object value) throws RehashException {
int bin = bin(key.hashCode());
int bininfo = hopinfo[bin];
// try to lookup equal key in neighbourhood
while (bininfo != 0) {
int offset = Integer.numberOfTrailingZeros(bininfo);
int bo = (bin + offset) & mask;
Object storedKey = keys[bo];
if (storedKey.equals(key)) {
Object prev = values[bo];
values[bo] = value;
return (V) prev;
}
bininfo = bininfo & ~(1 << offset);
}
if (keys[bin] == null) {
keys[bin] = key;
values[bin] = value;
hopinfo[bin] = hopinfo[bin] | 1;
++size;
return null;
}
int empty = (bin + 1) & mask;
// linear probe search
while (keys[empty] != null && empty != bin) {
empty = (empty + 1) & mask;
}
if (empty == bin) {
// there's no space in the table
assert size == m;
throw new RehashException();
}
for (;;) {
// we'll reach with the head as far back as we can
int head;
if (empty > bin) {
head = empty - H + 1;
if (head <= bin) {
break;
}
} else {
head = (empty - H + 1) & mask;
}
int headinfo;
int distance;
do {
headinfo = hopinfo[head];
distance = (empty - head) & mask;
// mask bits after empty
headinfo &= (1 << distance) - 1;
if (headinfo != 0) {
break;
}
// if the current head cannot help, we'll move it one step closer to the empty slot
head = (head + 1) & mask;
} while (head != empty);
if (head == empty) {
// there's no element that can be moved
// make sure that we don't have duplicity on the empty pos before rehash
keys[empty] = null;
values[empty] = null;
throw new RehashException();
}
int offset = Integer.numberOfTrailingZeros(headinfo);
int newEmpty = (head + offset) & mask;
keys[empty] = keys[newEmpty];
values[empty] = values[newEmpty];
// reload headinfo because we have masked bits after empty
headinfo = hopinfo[head];
hopinfo[head] = (headinfo & ~(1 << offset)) | (1 << distance);
empty = newEmpty;
}
keys[empty] = key;
values[empty] = value;
int offset = (empty - bin) & mask;
hopinfo[bin] = hopinfo[bin] | 1 << offset;
++size;
return null;
}
@Override
public V remove(Object key) {
Objects.requireNonNull(key);
++modCount;
int bin = bin(key.hashCode());
int bininfo = hopinfo[bin];
int previnfo = bininfo;
// try to lookup equal key in neighbourhood
while (bininfo != 0) {
int offset = Integer.numberOfTrailingZeros(bininfo);
int bo = (bin + offset) & mask;
Object storedKey = keys[bo];
if (storedKey.equals(key)) {
Object prev = values[bo];
previnfo = previnfo & ~(1 << offset);
if (previnfo != 0 && offset == 0) {
// if this bin has more entries and this is the first position, try to optimize further lookups
// by moving the entry to the first position
offset = Integer.numberOfTrailingZeros(previnfo);
bo = (bin + offset) & mask;
keys[bin] = keys[bo];
values[bin] = values[bo];
previnfo = previnfo & ~(1 << offset) | 1;
}
keys[bo] = null;
values[bo] = null;
hopinfo[bin] = previnfo;
--size;
return (V) prev;
}
bininfo = bininfo & ~(1 << offset);
}
return null;
}
private static class RehashException extends Exception {
public RehashException() {
super(null, null, false, false);
}
}
}
| 8,189
| 31.5
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ClasspathURLStreamHandler.java
|
package org.infinispan.commons.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
/**
* A {@link URLStreamHandlerFactory} which can handle <tt>classpath:</tt> URI schemes. It will attempt to load resources
* from the thread's context classloader (if it exists) and then fallback to the system classloader. The factory must be
* registered as the URL stream handler factory using the {@link #register()} method.
* <p>
* On Java 9+, this class is available as a URLStreamHandlerProvider service loader implementation which, if present in
* the boot classpath, will be automatically registered and used by the {@link URL} class.
*
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 12.1
**/
public class ClasspathURLStreamHandler implements URLStreamHandlerFactory {
private static final URLStreamHandlerFactory INSTANCE = new ClasspathURLStreamHandler();
/**
* Registers this URL handler as the JVM-wide URL stream handler. It can only be invoked once in the lifecycle of an
* application. Refer to the {@link URL} documentation for restrictions and alternative methods of registration.
*/
public static void register() {
URL.setURLStreamHandlerFactory(INSTANCE);
}
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
if ("classpath".equals(protocol)) {
return new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u) throws IOException {
String path = u.getPath();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL resource = classLoader == null ? null : classLoader.getResource(path);
if (resource == null) {
resource = ClassLoader.getSystemClassLoader().getResource(path);
}
if (resource != null) {
return resource.openConnection();
} else {
throw new FileNotFoundException(u.toString());
}
}
};
}
return null;
}
}
| 2,255
| 39.285714
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/RemovableCloseableIterator.java
|
package org.infinispan.commons.util;
import java.util.function.Consumer;
/**
* A CloseableIterator implementation that allows for a CloseableIterator that doesn't allow remove operations to
* implement remove by delegating the call to the provided consumer to remove the previously read value.
*
* @author wburns
* @since 9.1
*/
public class RemovableCloseableIterator<C> extends RemovableIterator<C> implements CloseableIterator<C> {
protected final CloseableIterator<C> realIterator;
public RemovableCloseableIterator(CloseableIterator<C> realIterator, Consumer<? super C> consumer) {
super(realIterator, consumer);
this.realIterator = realIterator;
}
@Override
public void close() {
currentValue = null;
previousValue = null;
realIterator.close();
}
}
| 813
| 29.148148
| 113
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/SmallIntSet.java
|
package org.infinispan.commons.util;
import static org.infinispan.commons.marshall.MarshallUtil.marshallByteArray;
import static org.infinispan.commons.marshall.MarshallUtil.unmarshallByteArray;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.BitSet;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.PrimitiveIterator;
import java.util.Set;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
/**
* Represent a set of integers (e.g. segments) as a {@code BitSet}.
*
* Memory usage depends on the highest element, as in {@link BitSet} and unlike in other collections such as
* {@link java.util.HashSet}.
*
* @author Dan Berindei
* @since 9.0
* @deprecated since 9.3 This class will no longer be public. Please use {@link IntSets} methods such as
* {@link IntSets#mutableEmptySet()}, {@link IntSets#mutableCopyFrom(Set)}
*/
@Deprecated
public class SmallIntSet implements IntSet {
private final BitSet bitSet;
public static SmallIntSet of(int i1) {
SmallIntSet set = new SmallIntSet(i1 + 1);
set.set(i1);
return set;
}
public static SmallIntSet of(int i1, int i2) {
SmallIntSet set = new SmallIntSet(Math.max(i1, i2) + 1);
set.set(i1);
set.set(i2);
return set;
}
public static SmallIntSet of(int i1, int i2, int i3) {
SmallIntSet set = new SmallIntSet();
set.set(i1);
set.set(i2);
set.set(i3);
return set;
}
public static SmallIntSet of(int... elements) {
SmallIntSet set = new SmallIntSet(elements.length);
for (int i : elements) {
set.set(i);
}
return set;
}
public static SmallIntSet of(PrimitiveIterator.OfInt iterator) {
SmallIntSet set = new SmallIntSet();
iterator.forEachRemaining((IntConsumer) set::set);
return set;
}
public static SmallIntSet from(byte[] bytes) {
BitSet bitSet = BitSet.valueOf(bytes);
return new SmallIntSet(bitSet);
}
/**
* Either converts the given set to an IntSet if it is one or creates a new IntSet and copies the contents
* @param set
* @return
*/
public static SmallIntSet from(Set<Integer> set) {
if (set instanceof SmallIntSet) {
return (SmallIntSet) set;
} else {
return new SmallIntSet(set);
}
}
public SmallIntSet() {
this(new BitSet());
}
/**
* Create a new {@code IntSet} and pre-allocate space for elements {@code 0..initialRange-1}.
*/
public SmallIntSet(int initialRange) {
this(new BitSet(initialRange));
}
public SmallIntSet(Set<Integer> set) {
if (set instanceof SmallIntSet) {
BitSet bitSet = ((SmallIntSet) set).bitSet;
this.bitSet = new BitSet(bitSet.size());
this.bitSet.or(bitSet);
} else if (set instanceof IntSet) {
this.bitSet = new BitSet();
((IntSet) set).forEach((IntConsumer) bitSet::set);
} else {
bitSet = new BitSet();
set.forEach(bitSet::set);
}
}
private SmallIntSet(BitSet bitSet) {
this.bitSet = bitSet;
}
@Override
public int size() {
return bitSet.cardinality();
}
public int capacity() {
return bitSet.size();
}
@Override
public boolean isEmpty() {
return bitSet.isEmpty();
}
@Override
public boolean contains(Object o) {
return (o instanceof Integer) && contains((Integer) o);
}
public boolean contains(Integer o) {
return bitSet.get(o);
}
/**
* Check if the set contains an integer without boxing the parameter.
*/
public boolean contains(int i) {
return bitSet.get(i);
}
@Override
public PrimitiveIterator.OfInt iterator() {
return new BitSetIntIterator(bitSet);
}
static class BitSetIntIterator implements PrimitiveIterator.OfInt {
private final BitSet bitSet;
private int offset;
private int prev;
BitSetIntIterator(BitSet bitSet) {
this.bitSet = bitSet;
this.offset = bitSet.nextSetBit(0);
this.prev = -1;
}
@Override
public int nextInt() {
if (offset < 0) {
throw new NoSuchElementException();
}
prev = offset;
offset = bitSet.nextSetBit(offset + 1);
return prev;
}
@Override
public boolean hasNext() {
return offset >= 0;
}
@Override
public void remove() {
if (prev < 0) {
throw new IllegalStateException();
}
bitSet.clear(prev);
prev = -1;
}
}
@Override
public int[] toIntArray() {
int size = size();
int[] dest = new int[size];
copyToArray(size, dest);
return dest;
}
@Override
public byte[] toBitSet() {
return bitSet.toByteArray();
}
@Override
public int nextSetBit(int fromIndex) {
return bitSet.nextSetBit(fromIndex);
}
private void copyToArray(int size, int[] dest) {
int lastSetBit = -1;
for (int i = 0; i < size; i++) {
lastSetBit = bitSet.nextSetBit(lastSetBit + 1);
dest[i] = lastSetBit;
}
}
@Override
public Object[] toArray() {
int size = size();
Integer[] dest = new Integer[size];
copyToArray(size, dest);
return dest;
}
@Override
public <T> T[] toArray(T[] a) {
if (!(a instanceof Integer[])) {
throw new IllegalArgumentException("Only Integer arrays are supported");
}
int size = size();
Integer[] dest = a.length < size ? new Integer[size] : (Integer[]) a;
copyToArray(size, dest);
return (T[]) dest;
}
private void copyToArray(int size, Integer[] dest) {
int lastSetBit = -1;
for (int i = 0; i < size; i++) {
lastSetBit = bitSet.nextSetBit(lastSetBit + 1);
dest[i] = lastSetBit;
}
}
@Override
public boolean add(Integer i) {
return add((int) i);
}
/**
* Add an integer to the set without boxing the parameter.
*/
public boolean add(int i) {
if (bitSet.get(i)) {
return false;
}
bitSet.set(i);
return true;
}
/**
* Add an integer to the set without boxing the parameter or checking if the integer was already present in the set.
*/
public void set(int i) {
bitSet.set(i);
}
/**
* If {@code value} is {@code true}, add the integer to the set, otherwise remove the integer from the set.
*/
public void set(int i, boolean value) {
bitSet.set(i, value);
}
@Override
public boolean remove(Object o) {
if (!(o instanceof Integer)) {
return false;
}
return remove((int) o);
}
/**
* Remove an integer from the set without boxing.
*/
public boolean remove(int i) {
boolean wasSet = bitSet.get(i);
if (wasSet) {
bitSet.clear(i);
return true;
}
return false;
}
@Override
public boolean containsAll(Collection<?> c) {
if (c instanceof IntSet) {
return containsAll((IntSet) c);
}
return c.stream().allMatch(this::contains);
}
@Override
public boolean containsAll(IntSet set) {
if (set instanceof SmallIntSet) {
BitSet bs = ((SmallIntSet) set).bitSet;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
if (!bitSet.get(i)) {
return false;
}
}
return true;
}
PrimitiveIterator.OfInt iter = set.iterator();
while (iter.hasNext()) {
if (!bitSet.get(iter.nextInt())) {
return false;
}
}
return true;
}
@Override
public boolean addAll(IntSet set) {
boolean modified = false;
if (set instanceof SmallIntSet) {
int countBefore = bitSet.cardinality();
bitSet.or(((SmallIntSet) set).bitSet);
modified = countBefore != bitSet.cardinality();
} else {
PrimitiveIterator.OfInt iter = set.iterator();
while (iter.hasNext()) {
modified |= add(iter.nextInt());
}
}
return modified;
}
@Override
public boolean addAll(Collection<? extends Integer> c) {
if (c instanceof IntSet) {
return addAll((IntSet) c);
}
boolean modified = false;
for (Integer integer : c) {
modified |= add(integer);
}
return modified;
}
@Override
public boolean removeAll(IntSet set) {
boolean modified = false;
if (set instanceof SmallIntSet) {
int countBefore = bitSet.cardinality();
bitSet.andNot(((SmallIntSet) set).bitSet);
modified = countBefore != bitSet.cardinality();
} else {
PrimitiveIterator.OfInt iter = set.iterator();
while (iter.hasNext()) {
modified |= remove(iter.nextInt());
}
}
return modified;
}
@Override
public boolean removeAll(Collection<?> c) {
if (c instanceof IntSet) {
return removeAll((IntSet) c);
}
boolean modified = false;
for (Object integer : c) {
modified |= remove(integer);
}
return modified;
}
@Override
public boolean retainAll(Collection<?> c) {
if (c instanceof IntSet) {
return retainAll((IntSet) c);
}
boolean modified = false;
for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet.nextSetBit(i + 1)) {
if (!c.contains(i)) {
bitSet.clear(i);
modified = true;
}
}
return modified;
}
@Override
public boolean retainAll(IntSet c) {
boolean modified = false;
for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet.nextSetBit(i + 1)) {
if (!c.contains(i)) {
bitSet.clear(i);
modified = true;
}
}
return modified;
}
@Override
public void clear() {
bitSet.clear();
}
@Override
public IntStream intStream() {
return bitSet.stream();
}
@Override
public void forEach(IntConsumer action) {
for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet.nextSetBit(i + 1)) {
action.accept(i);
}
}
@Override
public void forEach(Consumer<? super Integer> action) {
for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet.nextSetBit(i + 1)) {
// Has cost of auto boxing, oh well
action.accept(i);
}
}
@Override
public Spliterator.OfInt intSpliterator() {
// We just invoke default method as ints can be sparse in BitSet
return IntSet.super.intSpliterator();
}
@Override
public boolean removeIf(IntPredicate filter) {
boolean removed = false;
for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet.nextSetBit(i + 1)) {
if (filter.test(i)) {
bitSet.clear(i);
removed = true;
}
}
return removed;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Set))
return false;
if (o instanceof SmallIntSet) {
SmallIntSet integers = (SmallIntSet) o;
return bitSet.equals(integers.bitSet);
} else {
Set set = (Set) o;
return size() == set.size() && containsAll(set);
}
}
@Override
public int hashCode() {
return bitSet.hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
for (int i = bitSet.nextSetBit(0); i >= 0; i = bitSet.nextSetBit(i + 1)) {
if (sb.length() > "{".length()) {
sb.append(' ');
}
int runStart = i;
while (bitSet.get(i + 1)) {
i++;
}
if (i == runStart) {
sb.append(i);
} else {
sb.append(runStart).append('-').append(i);
}
}
sb.append('}');
return sb.toString();
}
public static void writeTo(ObjectOutput output, SmallIntSet set) throws IOException {
marshallByteArray(set == null ? null : set.bitSet.toByteArray(), output);
}
public static SmallIntSet readFrom(ObjectInput input) throws IOException {
byte[] bytes = unmarshallByteArray(input);
return bytes == null ? null : new SmallIntSet(BitSet.valueOf(bytes));
}
}
| 12,603
| 24.208
| 119
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/EvictionListener.java
|
package org.infinispan.commons.util;
import java.util.Map;
/**
* Eviction listener that is notified when entries are evicted from the underlying container due
* to the given eviction policy.
* @author wburns
* @since 9.0
* @deprecated since 10.0 - This class is not used internally anymore
*/
@Deprecated
public interface EvictionListener<K, V> {
/**
* Called back after entries have been evicted
* @param evicted
*/
void onEntryEviction(Map<K, V> evicted);
/**
* Called back before an entry is evicted
* @param entry
*/
void onEntryChosenForEviction(Map.Entry<K, V> entry);
/**
* Called back when an entry has been activated
* @param key
*/
void onEntryActivated(Object key);
/**
* Called when an entry is specifically removed from the container.
* @param entry
*/
void onEntryRemoved(Map.Entry<K, V> entry);
}
| 896
| 22
| 96
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/InjectiveFunction.java
|
package org.infinispan.commons.util;
import java.util.function.Function;
/**
* This is a marker interface to be used with {@link Function} which signals to some implementors that
* the function returns distinct values. This can be helpful because when a function is applied to data is ambiguous
* if the resulting data produced is distinct or not. This allows some callers of this method to apply additional
* performance optimizations taking this into account.
* <p>
* If a <b>function</b> is implemented with this and it doesn't produce distinct values, the operation of the
* consumer of this function may be undefined.
*
* @author wburns
* @since 9.0
*/
public interface InjectiveFunction<T, R> extends Function<T, R> {
}
| 741
| 38.052632
| 117
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/KeyValueWithPrevious.java
|
package org.infinispan.commons.util;
import java.io.Serializable;
import org.infinispan.protostream.WrappedMessage;
import org.infinispan.protostream.annotations.ProtoFactory;
import org.infinispan.protostream.annotations.ProtoField;
public class KeyValueWithPrevious<K, V> implements Serializable {
/**
* The serialVersionUID
*/
private static final long serialVersionUID = -7875910676423622104L;
private final K key;
private final V value;
private final V prev;
public KeyValueWithPrevious(K key, V value, V prev) {
this.key = key;
this.value = value;
this.prev = prev;
}
@ProtoFactory
KeyValueWithPrevious(WrappedMessage wrappedKey, WrappedMessage wrappedValue, WrappedMessage wrappedPrev) {
this.key = (K) wrappedKey.getValue();
this.value = (V) wrappedValue.getValue();
this.prev = (V) wrappedPrev.getValue();
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public V getPrev() {
return prev;
}
@ProtoField(1)
WrappedMessage getWrappedKey() {
return new WrappedMessage(key);
}
@ProtoField(2)
WrappedMessage getWrappedValue() {
return new WrappedMessage(value);
}
@ProtoField(3)
WrappedMessage getWrappedPrev() {
return new WrappedMessage(prev);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
KeyValueWithPrevious keyValueWithPrevious = (KeyValueWithPrevious) o;
if (key != null ? !key.equals(keyValueWithPrevious.key) : keyValueWithPrevious.key != null) return false;
if (prev != null ? !prev.equals(keyValueWithPrevious.prev) : keyValueWithPrevious.prev != null) return false;
if (value != null ? !value.equals(keyValueWithPrevious.value) : keyValueWithPrevious.value != null) return false;
return true;
}
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (prev != null ? prev.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "KeyValueWithPrevious{" +
"key=" + key +
", value=" + value +
", prev=" + prev +
'}';
}
}
| 2,399
| 25.666667
| 119
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/Closeables.java
|
package org.infinispan.commons.util;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.stream.BaseStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.reactivestreams.Publisher;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;
/**
* This class consists exclusively of static methods that operate on or return closeable interfaces. This is helpful
* when wanting to change a given interface to an appropriate closeable interface.
* @since 8.0
*/
public class Closeables {
private Closeables() { }
/**
* Takes a provided closeable iterator and wraps it appropriately so it can be used as a closeable spliterator that
* will close the iterator when the spliterator is closed.
* @param iterator The closeable iterator to change to a spliterator
* @param size The approximate size of the iterator. If no size is known {@link Long#MAX_VALUE} should be passed
* @param characteristics The characteristics of the given spliterator as defined on the {@link Spliterator}
* interface
* @param <E> The type that is the same between the iterator and spliterator
* @return A spliterator that when closed will close the provided iterator
*/
public static <E> CloseableSpliterator<E> spliterator(CloseableIterator<? extends E> iterator, long size,
int characteristics) {
return new CloseableIteratorAsCloseableSpliterator<>(iterator, size, characteristics);
}
/**
* Creates a closeable spliterator from the given spliterator that does nothing when close is called.
* @param spliterator The spliterator to wrap to allow it to become a closeable spliterator.
* @param <T> The type of the spliterators
* @return A spliterator that does nothing when closed
*/
public static <T> CloseableSpliterator<T> spliterator(Spliterator<T> spliterator) {
if (spliterator instanceof CloseableSpliterator) {
return (CloseableSpliterator<T>) spliterator;
}
return new SpliteratorAsCloseableSpliterator<>(spliterator);
}
/**
* Creates a closeable spliterator that when closed will close the underlying stream as well
* @param stream The stream to change into a closeable spliterator
* @param <R> The type of the stream
* @return A spliterator that when closed will also close the underlying stream
*/
public static <R> CloseableSpliterator<R> spliterator(BaseStream<R, Stream<R>> stream) {
Spliterator<R> spliterator = stream.spliterator();
if (spliterator instanceof CloseableSpliterator) {
return (CloseableSpliterator<R>) spliterator;
}
return new StreamToCloseableSpliterator<>(stream, spliterator);
}
/**
* Creates a closeable iterator that when closed will close the underlying stream as well
* @param stream The stream to change into a closeable iterator
* @param <R> The type of the stream
* @return An iterator that when closed will also close the underlying stream
*/
public static <R> CloseableIterator<R> iterator(BaseStream<R, Stream<R>> stream) {
Iterator<R> iterator = stream.iterator();
if (iterator instanceof CloseableIterator) {
return (CloseableIterator<R>) iterator;
}
return new StreamToCloseableIterator<>(stream, iterator);
}
/**
* Creates a closeable iterator from the given iterator that does nothing when close is called.
* @param iterator The iterator to wrap to allow it to become a closeable iterator
* @param <E> The type of the iterators
* @return An iterator that does nothing when closed
*/
public static <E> CloseableIterator<E> iterator(Iterator<? extends E> iterator) {
if (iterator instanceof CloseableIterator) {
return (CloseableIterator<E>) iterator;
}
return new IteratorAsCloseableIterator<>(iterator);
}
/**
* Creates a stream that when closed will also close the underlying spliterator
* @param spliterator spliterator to back the stream and subsequently close
* @param parallel whether or not the returned stream is parallel or not
* @param <E> the type of the stream
* @return the stream to use
*/
public static <E> Stream<E> stream(CloseableSpliterator<E> spliterator, boolean parallel) {
Stream<E> stream = StreamSupport.stream(spliterator, parallel);
stream.onClose(spliterator::close);
return stream;
}
/**
* Creates a stream that when closed will also close the underlying iterator
* @param iterator iterator to back the stream and subsequently close
* @param parallel whether or not the returned stream is parallel or not
* @param size the size of the iterator if known, otherwise {@link Long#MAX_VALUE} should be passed.
* @param characteristics the characteristics of the iterator to be used
* @param <E> the type of the stream
* @return the stream to use
*/
public static <E> Stream<E> stream(CloseableIterator<E> iterator, boolean parallel, long size, int characteristics) {
Stream<E> stream = StreamSupport.stream(Spliterators.spliterator(iterator, size, characteristics), parallel);
stream.onClose(iterator::close);
return stream;
}
private static class IteratorAsCloseableIterator<E> implements CloseableIterator<E> {
private final Iterator<? extends E> iterator;
public IteratorAsCloseableIterator(Iterator<? extends E> iterator) {
this.iterator = iterator;
}
@Override
public void close() {
// This does nothing
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public E next() {
return iterator.next();
}
@Override
public void remove() {
iterator.remove();
}
}
private static class SpliteratorAsCloseableSpliterator<T> implements CloseableSpliterator<T> {
private final Spliterator<T> spliterator;
public SpliteratorAsCloseableSpliterator(Spliterator<T> spliterator) {
this.spliterator = spliterator;
}
@Override
public void close() {
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
return spliterator.tryAdvance(action);
}
@Override
public Spliterator<T> trySplit() {
return spliterator.trySplit();
}
@Override
public long estimateSize() {
return spliterator.estimateSize();
}
@Override
public int characteristics() {
return spliterator.characteristics();
}
}
private static class CloseableIteratorAsCloseableSpliterator<E> extends SpliteratorAsCloseableSpliterator<E> {
private final CloseableIterator<? extends E> iterator;
CloseableIteratorAsCloseableSpliterator(CloseableIterator<? extends E> iterator, long size, int characteristics) {
super(Spliterators.spliterator(iterator, size, characteristics));
this.iterator = iterator;
}
@Override
public void close() {
this.iterator.close();
}
}
private static class StreamToCloseableIterator<E> extends IteratorAsCloseableIterator<E> {
private final BaseStream<E, Stream<E>> stream;
public StreamToCloseableIterator(BaseStream<E, Stream<E>> stream, Iterator<E> iterator) {
super(iterator);
this.stream = stream;
}
@Override
public void close() {
stream.close();
}
}
private static class StreamToCloseableSpliterator<T> extends SpliteratorAsCloseableSpliterator<T> {
private final BaseStream<T, Stream<T>> stream;
public StreamToCloseableSpliterator(BaseStream<T, Stream<T>> stream, Spliterator<T> spliterator) {
super(spliterator);
this.stream = stream;
}
@Override
public void close() {
stream.close();
}
}
/**
* Converts a {@link Publisher} to a {@link CloseableIterator} by utilizing items fetched into an array and
* refetched as they are consumed from the iterator. The iterator when closed will also close the underlying
* {@link org.reactivestreams.Subscription} when subscribed to the publisher.
* @param publisher the publisher to convert
* @param fetchSize how many entries to hold in memory at once in preparation for the iterators consumption
* @param <E> value type
* @return an iterator that when closed will cancel the subscription
*/
public static <E> CloseableIterator<E> iterator(Publisher<E> publisher, int fetchSize) {
// This iterator from rxjava3 implements Disposable akin to Closeable
Flowable<E> flowable = Flowable.fromPublisher(publisher);
@SuppressWarnings("checkstyle:forbiddenmethod")
Iterable<E> iterable = flowable.blockingIterable(fetchSize);
Iterator<E> iterator = iterable.iterator();
return new CloseableIterator<E>() {
@Override
public void close() {
((Disposable) iterator).dispose();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public E next() {
return iterator.next();
}
};
}
}
| 9,475
| 35.871595
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/OS.java
|
package org.infinispan.commons.util;
/**
* Operating system family.
*
* Technically Solaris is UNIX, but for test purposes we are classifying it as a separate family.
*
* @since 9.2
*/
public enum OS {
UNIX, WINDOWS, SOLARIS, LINUX, MAC_OS;
public static OS getCurrentOs() {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
return WINDOWS;
} else if (os.contains("sunos")) {
return SOLARIS;
} else if (os.contains("linux")) {
return LINUX;
} else if (os.toLowerCase().contains("mac os")) {
return MAC_OS;
} else {
return UNIX;
}
}
}
| 671
| 23
| 97
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/CloseableIteratorCollection.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.stream.Stream;
/**
* A collection that defines an iterator method that returns a {@link CloseableIterator}
* instead of a non closeable one. This is needed so that iterators can be properly cleaned up. All other
* methods will internally clean up any iterators created and don't have other side effects.
*
* @author wburns
* @since 7.0
*/
public interface CloseableIteratorCollection<E> extends Collection<E> {
/**
* {@inheritDoc}
* <p>
* This iterator should be explicitly closed when iteration upon it is completed. Failure to do so could cause
* resources to not be freed properly
*/
@Override
CloseableIterator<E> iterator();
/**
* {@inheritDoc}
* <p>
* This spliterator should be explicitly closed after it has been used. Failure to do so could cause
* resources to not be freed properly
*/
@Override
CloseableSpliterator<E> spliterator();
/**
* {@inheritDoc}
* <p>
* This stream should be explicitly closed after it has been used. Failure to do so could cause
* resources to not be freed properly
*/
@Override
default Stream<E> stream() {
return Collection.super.stream();
}
/**
* {@inheritDoc}
* <p>
* This stream should be explicitly closed after it has been used. Failure to do so could cause
* resources to not be freed properly
*/
@Override
default Stream<E> parallelStream() {
return Collection.super.parallelStream();
}
}
| 1,566
| 27.490909
| 113
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ServiceFinder.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* ServiceFinder is a {@link java.util.ServiceLoader} replacement which understands multiple classpaths.
*
* @author Tristan Tarrant
* @author Brett Meyer
* @since 6.0
*/
public class ServiceFinder {
private static final Log LOG = LogFactory.getLog(ServiceFinder.class);
public static <T> Collection<T> load(Class<T> contract, ClassLoader... loaders) {
Map<String, T> services = new LinkedHashMap<>();
if (loaders.length == 0) {
try {
ServiceLoader<T> loadedServices = ServiceLoader.load(contract);
addServices(loadedServices, services);
} catch (Exception e) {
// Ignore
}
}
else {
for (ClassLoader loader : loaders) {
if (loader == null)
throw new NullPointerException();
try {
ServiceLoader<T> loadedServices = ServiceLoader.load(contract, loader);
addServices(loadedServices, services);
} catch (Exception e) {
// Ignore
}
}
}
if (services.isEmpty()) {
LOG.debugf("No service impls found: %s", contract.getSimpleName());
}
return services.values();
}
private static <T> void addServices(ServiceLoader<T> loadedServices, Map<String, T> services) {
Iterator<T> i = loadedServices.iterator();
while (i.hasNext()) {
try {
T service = i.next();
if (services.putIfAbsent(service.getClass().getName(), service) == null) {
LOG.debugf("Loading service impl: %s", service.getClass().getName());
} else {
LOG.debugf("Ignoring already loaded service: %s", service.getClass().getName());
}
} catch (ServiceConfigurationError e) {
LOG.warnf("Skipping service: %s", Util.unwrapExceptionMessage(e));
LOG.debug("Skipping service impl", e);
}
}
}
}
| 2,276
| 31.070423
| 104
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/JVMMemoryInfoInfo.java
|
package org.infinispan.commons.util;
import java.io.IOException;
import java.lang.management.BufferPoolMXBean;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.lang.management.MemoryUsage;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import org.infinispan.commons.dataconversion.internal.Json;
import org.infinispan.commons.dataconversion.internal.JsonSerialization;
import com.sun.management.HotSpotDiagnosticMXBean;
/**
* @since 10.0
*/
@SuppressWarnings("unused")
public final class JVMMemoryInfoInfo implements JsonSerialization {
private final MemoryMXBean memoryMBean;
private final List<MemoryPoolMXBean> memoryPoolMBeans;
private final List<BufferPoolMXBean> bufferPoolsMBeans;
private final List<GarbageCollectorMXBean> garbageCollectorMXBeans;
HotSpotDiagnosticMXBean hotSpotDiagnosticMXBean;
public JVMMemoryInfoInfo() {
garbageCollectorMXBeans = ManagementFactory.getGarbageCollectorMXBeans();
memoryMBean = ManagementFactory.getMemoryMXBean();
memoryPoolMBeans = ManagementFactory.getMemoryPoolMXBeans();
bufferPoolsMBeans = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
hotSpotDiagnosticMXBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
}
public List<MemoryManager> getGc() {
return garbageCollectorMXBeans.stream().map(MemoryManager::new).collect(Collectors.toList());
}
public List<MemoryPool> getMemoryPools() {
return memoryPoolMBeans.stream().map(MemoryPool::new).collect(Collectors.toList());
}
public List<BufferPool> getBufferPools() {
return bufferPoolsMBeans.stream().map(BufferPool::new).collect(Collectors.toList());
}
public MemoryUsage getHeap() {
return memoryMBean.getHeapMemoryUsage();
}
public MemoryUsage getNonHeap() {
return memoryMBean.getNonHeapMemoryUsage();
}
public void heapDump(Path path, boolean live) throws IOException {
hotSpotDiagnosticMXBean.dumpHeap(path.toString(), live);
}
private static Json asJson(MemoryUsage usage) {
return Json.object("init", usage.getInit())
.set("used", usage.getUsed())
.set("committed", usage.getCommitted())
.set("max", usage.getMax());
}
@Override
public Json toJson() {
return Json.object()
.set("memory_pools", Json.make(getMemoryPools()))
.set("gc", Json.make(getGc()))
.set("buffer_pools", Json.make(getBufferPools()))
.set("heap", asJson(getHeap()))
.set("non_heap", asJson(getNonHeap()));
}
private static class BufferPool implements JsonSerialization {
private final long memoryUsed;
private final String name;
private final long totalCapacity;
private final long count;
BufferPool(BufferPoolMXBean bufferPoolMXBean) {
memoryUsed = bufferPoolMXBean.getMemoryUsed();
name = bufferPoolMXBean.getName();
totalCapacity = bufferPoolMXBean.getTotalCapacity();
count = bufferPoolMXBean.getCount();
}
public long getMemoryUsed() {
return memoryUsed;
}
public String getName() {
return name;
}
public long getTotalCapacity() {
return totalCapacity;
}
public long getCount() {
return count;
}
@Override
public Json toJson() {
return Json.object()
.set("name", name)
.set("memory_used", memoryUsed)
.set("total_capacity", totalCapacity)
.set("count", count);
}
}
private static class MemoryPool implements JsonSerialization {
private final String name;
private final MemoryType type;
private final MemoryUsage usage;
private final MemoryUsage peakUsage;
MemoryPool(MemoryPoolMXBean memoryPoolMXBean) {
this.name = memoryPoolMXBean.getName();
this.type = memoryPoolMXBean.getType();
this.usage = memoryPoolMXBean.getUsage();
this.peakUsage = memoryPoolMXBean.getPeakUsage();
}
public String getName() {
return name;
}
public MemoryType getType() {
return type;
}
public MemoryUsage getUsage() {
return usage;
}
public MemoryUsage getPeakUsage() {
return peakUsage;
}
@Override
public Json toJson() {
return Json.object()
.set("name", name)
.set("type", type)
.set("usage", asJson(usage))
.set("peak_usage", asJson(peakUsage));
}
}
private static class MemoryManager implements JsonSerialization {
private final String name;
private final String[] memoryPoolNames;
private final boolean valid;
private final long collectionCount;
private final long collectionTime;
MemoryManager(GarbageCollectorMXBean memoryManagerMXBean) {
name = memoryManagerMXBean.getName();
memoryPoolNames = memoryManagerMXBean.getMemoryPoolNames();
valid = memoryManagerMXBean.isValid();
collectionCount = memoryManagerMXBean.getCollectionCount();
collectionTime = memoryManagerMXBean.getCollectionTime();
}
public long getCollectionCount() {
return collectionCount;
}
public long getCollectionTime() {
return collectionTime;
}
public String getName() {
return name;
}
public String[] getMemoryPoolNames() {
return memoryPoolNames;
}
public boolean isValid() {
return valid;
}
@Override
public Json toJson() {
return Json.object()
.set("name", name)
.set("valid", valid)
.set("collection_count", collectionCount)
.set("collection_time", collectionTime)
.set("memory_pool_names", Json.make(getMemoryPoolNames()));
}
}
}
| 6,224
| 29.218447
| 99
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/AbstractDelegatingMap.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
public abstract class AbstractDelegatingMap<K, V> implements Map<K, V> {
protected abstract Map<K, V> delegate();
@Override
public V putIfAbsent(K key, V value) {
return delegate().putIfAbsent(key, value);
}
@Override
public int size() {
return delegate().size();
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public boolean containsKey(Object key) {
return delegate().containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return delegate().containsValue(value);
}
@Override
public V get(Object key) {
return delegate().get(key);
}
@Override
public V getOrDefault(Object key, V defaultValue) {
return delegate().getOrDefault(key, defaultValue);
}
@Override
public V put(K key, V value) {
return delegate().put(key, value);
}
@Override
public V remove(Object key) {
return delegate().remove(key);
}
@Override
public boolean remove(Object key, Object value) {
return delegate().remove(key, value);
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
return delegate().replace(key, oldValue, newValue);
}
@Override
public V replace(K key, V value) {
return delegate().replace(key, value);
}
@Override
public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
delegate().replaceAll(function);
}
@Override
public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
return delegate().compute(key, remappingFunction);
}
@Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
return delegate().computeIfAbsent(key, mappingFunction);
}
@Override
public V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
return delegate().computeIfPresent(key, remappingFunction);
}
@Override
public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
return delegate().merge(key, value, remappingFunction);
}
@Override
public void forEach(BiConsumer<? super K, ? super V> action) {
delegate().forEach(action);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
delegate().putAll(m);
}
@Override
public void clear() {
delegate().clear();
}
@Override
public Set<K> keySet() {
return delegate().keySet();
}
@Override
public Collection<V> values() {
return delegate().values();
}
@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
return delegate().entrySet();
}
}
| 3,004
| 22.115385
| 102
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ReversibleOrderedSet.java
|
package org.infinispan.commons.util;
import java.util.Iterator;
import java.util.Set;
/**
* A set that allows reverse iteration of the set elements, exposed via the {@link #reverseIterator()} method. This
* only really makes sense for ordered Set implementations, such as sets which are linked.
*
* @author Manik Surtani
* @since 4.0
*/
public interface ReversibleOrderedSet<E> extends Set<E> {
Iterator<E> reverseIterator();
}
| 440
| 26.5625
| 116
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/SaslUtils.java
|
package org.infinispan.commons.util;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.ServiceLoader;
import java.util.Set;
import javax.security.sasl.SaslClientFactory;
import javax.security.sasl.SaslServerFactory;
import org.infinispan.commons.logging.Log;
/**
* Utility methods for handling SASL authentication
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author Tristan Tarrant
*/
public final class SaslUtils {
/**
* Returns a collection of all of the registered {@code SaslServerFactory}s where the order is based on the order of
* the Provider registration and/or class path order. Class path providers are listed before global providers; in
* the event of a name conflict, the class path provider is preferred.
*
* @param classLoader the class loader to use
* @param providers an array of security {@link Provider}s to search first. Can be null.
* @param includeGlobal {@code true} to include globally registered providers, {@code false} to exclude them
* @return the {@code Iterator} of {@code SaslServerFactory}s
*/
public static Collection<SaslServerFactory> getSaslServerFactories(ClassLoader classLoader, Provider[] providers, boolean includeGlobal) {
return getFactories(SaslServerFactory.class, classLoader, providers, includeGlobal);
}
/**
* Returns a collection of all the registered {@code SaslClientFactory}s where the order is based on the order of the
* Provider registration and/or class path order. Class path providers are listed before global providers; in the
* event of a name conflict, the class path provider is preferred.
*
* @param classLoader the class loader to use
* @param providers an array of security {@link Provider}s to search first. Can be null.
* @param includeGlobal {@code true} to include globally registered providers, {@code false} to exclude them
* @return the {@code Iterator} of {@code SaslClientFactory}s
*/
public static Collection<SaslClientFactory> getSaslClientFactories(ClassLoader classLoader, Provider[] providers, boolean includeGlobal) {
return getFactories(SaslClientFactory.class, classLoader, providers, includeGlobal);
}
private static <T> Collection<T> getFactories(Class<T> type, ClassLoader classLoader, Provider[] providers, boolean includeGlobal) {
Set<T> factories = new LinkedHashSet<>();
if (providers != null) {
findFactories(type, factories, providers);
}
final ServiceLoader<T> loader = ServiceLoader.load(type, classLoader);
for (T factory : loader) {
factories.add(factory);
}
if (includeGlobal) {
findFactories(type, factories, Security.getProviders());
}
return factories;
}
private static <T> void findFactories(Class<T> type, Set<T> factories, Provider[] providers) {
for (Provider currentProvider : providers) {
for (Provider.Service service : currentProvider.getServices()) {
if (type.getSimpleName().equals(service.getType())) {
try {
factories.add((T) service.newInstance(null));
} catch (NoSuchAlgorithmException e) {
Log.SECURITY.debugf(e, "Could not add service '%s'", service);
}
}
}
}
}
}
| 3,502
| 42.246914
| 141
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/Version.java
|
package org.infinispan.commons.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Properties;
import net.jcip.annotations.Immutable;
/**
* Contains version information about this release of Infinispan.
*
* @author Bela Ban
* @since 4.0
*/
@Immutable
public class Version {
private static final int MAJOR_SHIFT = 11;
private static final int MINOR_SHIFT = 6;
private static final int MAJOR_MASK = 0x00f800;
private static final int MINOR_MASK = 0x0007c0;
private static final int PATCH_MASK = 0x00003f;
private static final Version INSTANCE = new Version();
public static final String INFINISPAN_VERSION = "infinispan.version";
public static final String INFINISPAN_BRAND_NAME = "infinispan.brand.name";
public static final String INFINISPAN_BRAND_VERSION = "infinispan.brand.version";
public static final String INFINISPAN_CODENAME = "infinispan.codename";
public static final String INFINISPAN_CORE_SCHEMA_VERSION = "infinispan.core.schema.version";
public static final String INFINISPAN_MODULE_SLOT_PREFIX = "infinispan.module.slot.prefix";
public static final String INFINISPAN_MODULE_SLOT_VERSION = "infinispan.module.slot.version";
private final String version;
private final String brandName;
private final String brandVersion;
private final String codename;
private final String schemaVersion;
private final byte[] versionId;
private final String moduleSlot;
private final short versionShort;
private final short marshallVersion;
private final String majorMinor;
private final String major;
private final String minor;
private final Properties properties;
private Version() {
this(Version.class.getResourceAsStream("/META-INF/infinispan-version.properties"));
}
private Version(InputStream is) {
properties = new Properties();
try {
properties.load(is);
// Closing it here is harmless
Util.close(is);
} catch (IOException e) {
// Ignore errors, we'll use fallbacks
}
version = properties.getProperty(INFINISPAN_VERSION, "0.0.0-SNAPSHOT");
brandName = properties.getProperty(INFINISPAN_BRAND_NAME, "Infinispan");
brandVersion = properties.getProperty(INFINISPAN_BRAND_VERSION, version);
codename = properties.getProperty(INFINISPAN_CODENAME, "N/A");
schemaVersion = properties.getProperty(INFINISPAN_CORE_SCHEMA_VERSION, "0.0");
String parts[] = getParts(version);
versionId = readVersionBytes(parts[0], parts[1], parts[2], parts[3]);
versionShort = getVersionShort(version);
String modulePrefix = properties.getProperty(INFINISPAN_MODULE_SLOT_PREFIX, "ispn");
String moduleVersion = properties.getProperty(INFINISPAN_MODULE_SLOT_VERSION, parts[0] + "." + parts[1]);
moduleSlot = String.format("%s-%s", modulePrefix, moduleVersion);
marshallVersion = Short.valueOf(parts[0] + parts[1]);
majorMinor = String.format("%s.%s", parts[0], parts[1]);
major = parts[0];
minor = parts[1];
}
public static Version from(InputStream is) {
return new Version(is);
}
/*
* The following methods are per-instance
*/
public String version() {
return version;
}
public String brandName() {
return brandName;
}
public String brandVersion() {
return brandVersion;
}
/*
* The following methods use a singleton instance
*/
public static String getVersion() {
return INSTANCE.version;
}
public static String getBrandName() {
return INSTANCE.brandName;
}
public static String getBrandVersion() {
return INSTANCE.brandVersion;
}
public static String getCodename() {
return INSTANCE.codename;
}
public static String getModuleSlot() {
return INSTANCE.moduleSlot;
}
public static short getMarshallVersion() {
return INSTANCE.marshallVersion;
}
public static String getSchemaVersion() {
return INSTANCE.schemaVersion;
}
public static String getMajorMinor() {
return INSTANCE.majorMinor;
}
public static String getMajor() {
return INSTANCE.major;
}
public static String getMinor() {
return INSTANCE.minor;
}
public static boolean compareTo(byte[] v) {
return Arrays.equals(INSTANCE.versionId, v);
}
public static short getVersionShort() {
return INSTANCE.versionShort;
}
public static short getVersionShort(String versionString) {
if (versionString == null)
throw new IllegalArgumentException("versionString is null");
String parts[] = getParts(versionString);
int a = 0;
int b = 0;
int c = 0;
if (parts.length > 0)
a = Integer.parseInt(parts[0]);
if (parts.length > 1)
b = Integer.parseInt(parts[1]);
if (parts.length > 2)
c = Integer.parseInt(parts[2]);
return encodeVersion(a, b, c);
}
private static short encodeVersion(int major, int minor, int patch) {
return (short) ((major << MAJOR_SHIFT) + (minor << MINOR_SHIFT) + patch);
}
public static String decodeVersion(short version) {
int major = (version & MAJOR_MASK) >> MAJOR_SHIFT;
int minor = (version & MINOR_MASK) >> MINOR_SHIFT;
int patch = (version & PATCH_MASK);
return major + "." + minor + "." + patch;
}
/**
* Serialization only looks at major and minor, not micro or below.
*/
public static String decodeVersionForSerialization(short version) {
int major = (version & MAJOR_MASK) >> MAJOR_SHIFT;
int minor = (version & MINOR_MASK) >> MINOR_SHIFT;
return major + "." + minor;
}
public static String getProperty(String name) {
return INSTANCE.properties.getProperty(name);
}
/**
* Prints version information.
*/
public static void main(String[] args) {
printFullVersionInformation();
}
/**
* Prints full version information to the standard output.
*/
public static void printFullVersionInformation() {
System.out.println(INSTANCE.brandName);
System.out.println();
System.out.printf("Version: \t%s%n", INSTANCE.brandVersion);
System.out.printf("Codename: \t%s%n", INSTANCE.codename);
System.out.println();
}
/**
* Returns version information as a string.
*/
public static String printVersion() {
return INSTANCE.brandName + " '" + INSTANCE.codename + "' " + INSTANCE.brandVersion;
}
private static byte[] readVersionBytes(String major, String minor, String micro, String modifier) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int i = 0; i < major.length(); i++)
baos.write(major.charAt(i));
for (int i = 0; i < minor.length(); i++)
baos.write(minor.charAt(i));
for (int i = 0; i < micro.length(); i++)
baos.write(micro.charAt(i));
if ("SNAPSHOT".equals(modifier))
baos.write('S');
else
for (int i = 0; i < modifier.length(); i++)
baos.write(modifier.charAt(i));
return baos.toByteArray();
}
private static String[] getParts(String version) {
return version.split("[\\.\\-]");
}
}
| 7,324
| 30.303419
| 111
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/FilterIterator.java
|
package org.infinispan.commons.util;
import java.util.Iterator;
import java.util.function.Predicate;
/**
* Iterator that also filters out entries based on the provided predicate. This iterator implements
* {@link CloseableIterator} and will close the provided iterator if it also implemented CloseableIterator.
* <p>
* This iterator supports removal as long as the provided iterator supports removal. Although note only entries
* returned by the filter can be removed.
* @author wburns
* @since 9.3
*/
public class FilterIterator<E> extends AbstractIterator<E> implements CloseableIterator<E> {
private final Iterator<E> iter;
private final Predicate<? super E> filter;
public FilterIterator(Iterator<E> iter, Predicate<? super E> filter) {
this.iter = iter;
this.filter = filter;
}
@Override
protected E getNext() {
while (iter.hasNext()) {
E next = iter.next();
if (filter.test(next)) {
return next;
}
}
return null;
}
@Override
public void close() {
if (iter instanceof CloseableIterator) {
((CloseableIterator) iter).close();
}
}
@Override
public void remove() {
iter.remove();
}
}
| 1,235
| 25.297872
| 111
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/TimedThreadDump.java
|
package org.infinispan.commons.util;
import java.util.concurrent.TimeUnit;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
public class TimedThreadDump {
private static final Log log = LogFactory.getLog(TimedThreadDump.class);
private final long interval;
private long lastUse = 0;
private TimedThreadDump() {
this.interval = TimeUnit.SECONDS.toMillis(Long.getLong("infinispan.backpressure.dump.interval.sec", 60));
}
private static final TimedThreadDump INSTANCE = new TimedThreadDump();
public static TimedThreadDump instance() {
return INSTANCE;
}
public static boolean generateThreadDump() {
return instance().generateThreadDump(System.currentTimeMillis());
}
private boolean generateThreadDump(long millisTime) {
if (log.isTraceEnabled()) {
boolean dump;
synchronized (this) {
dump = lastUse + interval < millisTime;
if (dump) {
lastUse = millisTime;
}
}
if (dump) {
log.trace(Util.threadDump());
return true;
}
}
return false;
}
}
| 1,184
| 24.76087
| 111
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/MurmurHash3BloomFilter.java
|
package org.infinispan.commons.util;
import java.util.ArrayList;
import java.util.List;
import java.util.function.ToIntFunction;
import org.infinispan.commons.hash.MurmurHash3;
/**
* BloomFilter implementation that allows for up to 10 hash functions all using MurmurHash3 with different
* seeds. The same seed(s) is used for the given number of hash functions. That is if you create this
* filter in one JVM with 3 functions it will be the same bloom filter as another JVM with 3 functions in another.
* <p>
* The default number of hash functions is 3.
*/
public class MurmurHash3BloomFilter extends BloomFilter<byte[]> {
MurmurHash3BloomFilter(int bitsToUse, IntSet intSet, int hashFunctions) {
super(bitsToUse, intSet, (Iterable) functions(hashFunctions));
}
private static int defaultHashFunctionCount() {
return Integer.parseInt(System.getProperty("infinispan.bloom-filter.hash-functions", "3"));
}
public static BloomFilter<byte[]> createFilter(int bitsToUse) {
return createFilter(bitsToUse, defaultHashFunctionCount());
}
public static BloomFilter<byte[]> createFilter(int bitsToUse, int hashFunctions) {
return new MurmurHash3BloomFilter(bitsToUse, IntSets.mutableEmptySet(bitsToUse), hashFunctions);
}
public static BloomFilter<byte[]> createConcurrentFilter(int bitsToUse) {
return createConcurrentFilter(bitsToUse, defaultHashFunctionCount());
}
public static BloomFilter<byte[]> createConcurrentFilter(int bitsToUse, int hashFunctions) {
return new MurmurHash3BloomFilter(bitsToUse, IntSets.concurrentSet(bitsToUse), hashFunctions);
}
private static Iterable<ToIntFunction<byte[]>> functions(int hashFunctions) {
if (hashFunctions <= 0) {
throw new IllegalArgumentException("Number of hash functions must be positive, received " + hashFunctions);
}
List<ToIntFunction<byte[]>> functions = new ArrayList<>(hashFunctions);
for (int i = 0; i < hashFunctions; ++i) {
int prime = getPrime(i);
functions.add(bytes -> MurmurHash3.MurmurHash3_x64_32(bytes, prime));
}
return functions;
}
private static int getPrime(int offset) {
switch (offset) {
case 0:
return 239;
case 1:
return 1847;
case 2:
return 2719;
case 3:
return 3989;
case 4:
return 4481;
case 5:
return 5407;
case 6:
return 6047;
case 7:
return 7537;
case 8:
return 8467;
case 9:
return 9973;
default:
throw new IllegalArgumentException("Only support up to 10 hash functions");
}
}
}
| 2,759
| 33.5
| 116
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ImmutableIntSet.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import java.util.stream.IntStream;
/**
* Immutable wrapper for {@link IntSet}.
*
* @author Dan Berindei
* @since 9.2
* @deprecated since 9.3 This class will no longer be public, please use {@link IntSets#immutableSet(IntSet)}
*/
@Deprecated
public class ImmutableIntSet extends AbstractImmutableIntSet {
private final IntSet set;
public ImmutableIntSet(IntSet set) {
this.set = set;
}
@Override
public boolean contains(int i) {
return set.contains(i);
}
@Override
public boolean addAll(IntSet set) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(IntSet set) {
return this.set.containsAll(set);
}
@Override
public int size() {
return set.size();
}
@Override
public boolean isEmpty() {
return set.isEmpty();
}
@Override
public boolean contains(Object o) {
return set.contains(o);
}
@Override
public PrimitiveIterator.OfInt iterator() {
return new ImmutableIterator(set.iterator());
}
@Override
public int[] toIntArray() {
return set.toIntArray();
}
@Override
public Object[] toArray() {
return set.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return set.toArray(a);
}
@Override
public boolean containsAll(Collection<?> c) {
return set.containsAll(c);
}
@Override
public IntStream intStream() {
return set.intStream();
}
@Override
public void forEach(IntConsumer action) {
set.forEach(action);
}
@Override
public void forEach(Consumer<? super Integer> action) {
set.forEach(action);
}
@Override
public Spliterator.OfInt intSpliterator() {
return set.intSpliterator();
}
@Override
public byte[] toBitSet() {
return set.toBitSet();
}
@Override
public int nextSetBit(int fromIndex) {
return set.nextSetBit(fromIndex);
}
private static class ImmutableIterator implements PrimitiveIterator.OfInt {
private OfInt iterator;
ImmutableIterator(OfInt iterator) {
this.iterator = iterator;
}
@Override
public int nextInt() {
return iterator.nextInt();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
}
}
| 2,550
| 18.929688
| 109
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/AggregatedClassLoader.java
|
package org.infinispan.commons.util;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* A ClassLoader that delegates loading of classes and resources to a list of delegate ClassLoaders. The loading is
* attempted in the order returned by the provided {@link Collection}.
*
* @author anistor@redhat.com
* @since 9.2
*/
public final class AggregatedClassLoader extends ClassLoader {
private final ClassLoader[] classLoaders;
/**
* Create an aggregated ClassLoader from a Collection of ClassLoaders
*
* @param classLoaders a non-empty Collection of ClassLoaders
*/
public AggregatedClassLoader(Collection<ClassLoader> classLoaders) {
super(null);
if (classLoaders == null || classLoaders.isEmpty()) {
throw new IllegalArgumentException("classLoaders argument cannot be null or empty");
}
this.classLoaders = classLoaders.toArray(new ClassLoader[classLoaders.size()]);
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
Set<URL> urls = new HashSet<>();
for (ClassLoader cl : classLoaders) {
Enumeration<URL> resources = cl.getResources(name);
while (resources.hasMoreElements()) {
urls.add(resources.nextElement());
}
}
return new Enumeration<URL>() {
final Iterator<URL> it = urls.iterator();
@Override
public boolean hasMoreElements() {
return it.hasNext();
}
@Override
public URL nextElement() {
return it.next();
}
};
}
@Override
protected URL findResource(String name) {
for (ClassLoader cl : classLoaders) {
URL res = cl.getResource(name);
if (res != null) {
return res;
}
}
return super.findResource(name);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
for (ClassLoader cl : classLoaders) {
try {
return cl.loadClass(name);
} catch (Exception ex) {
// ignored
}
}
throw new ClassNotFoundException(name);
}
}
| 2,308
| 26.488095
| 115
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/SegmentAwareKey.java
|
package org.infinispan.commons.util;
import java.util.Objects;
/**
* Encapsulates the key and its segment.
*
* @author Pedro Ruivo
* @since 12
*/
public class SegmentAwareKey<K> {
private final K key;
private final int segment;
public SegmentAwareKey(K key, int segment) {
this.key = Objects.requireNonNull(key);
this.segment = segment;
}
public K getKey() {
return key;
}
public int getSegment() {
return segment;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SegmentAwareKey<?> that = (SegmentAwareKey<?>) o;
return segment == that.segment && key.equals(that.key);
}
@Override
public int hashCode() {
return Objects.hash(key, segment);
}
@Override
public String toString() {
return "SegmentAwareKey{" +
"key=" + Util.toStr(key) +
", segment=" + segment +
'}';
}
}
| 1,014
| 19.3
| 64
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/LegacyKeySupportSystemProperties.java
|
package org.infinispan.commons.util;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* A wrapper around system properties that supports legacy keys
*
* @author Manik Surtani
* @version 4.1
*/
public class LegacyKeySupportSystemProperties {
private static final Log log = LogFactory.getLog(LegacyKeySupportSystemProperties.class);
private static void warnLegacy(String oldKey, String newKey) {
if (log.isInfoEnabled())
log.infof("Could not find value for key %1$s, but did find value under deprecated key %2$s. Please use %1$s as support for %2$s will eventually be discontinued.",
newKey, oldKey);
}
public static String getProperty(String key, String legacyKey) {
String val = System.getProperty(key);
if (val == null) {
val = System.getProperty(legacyKey);
if (val != null) warnLegacy(legacyKey, key);
}
return val;
}
public static String getProperty(String key, String legacyKey, String defaultValue) {
String val = System.getProperty(key);
if (val == null) {
val = System.getProperty(legacyKey);
if (val != null)
warnLegacy(legacyKey, key);
else
val = defaultValue;
}
return val;
}
}
| 1,319
| 29.697674
| 171
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/CloseableIterator.java
|
package org.infinispan.commons.util;
import java.util.Iterator;
/**
* Interface that provides semantics of a {@link Iterator} and {@link AutoCloseable} interfaces. This is
* useful when you have data that must be iterated on and may hold resources in the underlying implementation that
* must be closed.
* <p>Some implementations may close resources automatically when the iterator is finished being iterated on however
* this is an implementation detail and all callers should call {@link AutoCloseable#close()} method to be
* sure all resources are freed properly.</p>
*
* @author wburns
* @since 7.0
*/
public interface CloseableIterator<E> extends AutoCloseable, Iterator<E> {
@Override
void close();
}
| 726
| 35.35
| 116
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/IntSet.java
|
package org.infinispan.commons.util;
import java.util.Iterator;
import java.util.Objects;
import java.util.PrimitiveIterator;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* A set that represents primitive ints. This interface describes methods that can be used without having to box an int.
* This set does not support negative numbers.
* @author wburns
* @since 9.2
*/
public interface IntSet extends Set<Integer> {
/**
* Adds the given int to this set and returns {@code true} if it was set or {@code false} if it was already present
* @param i the int value to add
* @return whether this int was already present
*/
boolean add(int i);
/**
* Adds or sets the int without returning whether it was previously set
* @param i the value to make sure is in the set
*/
void set(int i);
/**
* Removes, if present, the int from the set and returns if it was present or not
* @param i the int to remove
* @return whether the int was present in the set before it was removed
*/
boolean remove(int i);
/**
* Whether this set contains the given int
* @param i the int to check
* @return if the set contains the int
*/
boolean contains(int i);
/**
* Adds all ints from the provided set into this one
* @param set the set of ints to add
* @return if this set has a new int in it
*/
boolean addAll(IntSet set);
/**
* Whether this set contains all ints in the given IntSet
* @param set the set to check if all are present
* @return if the set contains all the ints
*/
boolean containsAll(IntSet set);
/**
* Removes all ints from this IntSet that are in the provided IntSet
* @param set the ints to remove from this IntSet
* @return if this set removed any ints
*/
boolean removeAll(IntSet set);
/**
* Modifies this set to remove all ints that are not present in the provided IntSet
* @param c the ints this set should kep
* @return if this set removed any ints
*/
boolean retainAll(IntSet c);
/**
* A primtive iterator that allows iteration over the int values. This iterator supports removal if the set is
* modifiable.
* @return the iterator
*/
PrimitiveIterator.OfInt iterator();
/**
* A stream of ints representing the data in this set
* @return the stream
*/
IntStream intStream();
@Override
default Stream<Integer> stream() {
return Set.super.stream();
}
/**
* Performs the given action for each int of the {@code IntSet}
* until all elements have been processed or the action throws an
* exception. Unless otherwise specified by the implementing class,
* actions are performed in the order of iteration (if an iteration order
* is specified). Exceptions thrown by the action are relayed to the
* caller.
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* PrimitiveIterator.OfInt iterator = iterator();
* while (iterator.hasNext()) {
* action.accept(iterator.nextInt());
* }
* }</pre>
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @since 9.3
*/
default void forEach(IntConsumer action) {
Objects.requireNonNull(action);
PrimitiveIterator.OfInt iterator = iterator();
while (iterator.hasNext()) {
action.accept(iterator.nextInt());
}
}
/**
* Creates a {@code Spliterator.OfInt} over the ints in this set.
*
* <p>The {@code Spliterator.OfInt} reports {@link Spliterator#DISTINCT}.
* Implementations should document the reporting of additional
* characteristic values.
*
* @implSpec
* The default implementation creates a
* <em><a href="Spliterator.html#binding">late-binding</a></em> spliterator
* from the set's {@code Iterator}. The spliterator inherits the
* <em>fail-fast</em> properties of the set's iterator.
* <p>
* The created {@code Spliterator.OfInt} additionally reports
* {@link Spliterator#SIZED}.
*
* @implNote
* The created {@code Spliterator.OfInt} additionally reports
* {@link Spliterator#SUBSIZED}.
*
* @return a {@code Spliterator.OfInt} over the ints in this set
* @since 9.3
*/
default Spliterator.OfInt intSpliterator() {
return Spliterators.spliterator(iterator(), size(), Spliterator.DISTINCT);
}
/**
* Removes all of the ints of this set that satisfy the given
* predicate. Errors or runtime exceptions thrown during iteration or by
* the predicate are relayed to the caller.
*
* @implSpec
* The default implementation traverses all elements of the collection using
* its {@link #iterator}. Each matching element is removed using
* {@link Iterator#remove()}. If the collection's iterator does not
* support removal then an {@code UnsupportedOperationException} will be
* thrown on the first matching element.
*
* @param filter a predicate which returns {@code true} for ints to be
* removed
* @return {@code true} if any ints were removed
* @throws NullPointerException if the specified filter is null
* @throws UnsupportedOperationException if elements cannot be removed
* from this collection. Implementations may throw this exception if a
* matching element cannot be removed or if, in general, removal is not
* supported.
* @since 9.3
*/
default boolean removeIf(IntPredicate filter) {
Objects.requireNonNull(filter);
boolean removed = false;
PrimitiveIterator.OfInt iterator = iterator();
while (iterator.hasNext()) {
if (filter.test(iterator.nextInt())) {
iterator.remove();
removed = true;
}
}
return removed;
}
/**
* Returns an array containing all of the elements in this set.
* If this set makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the
* elements in the same order.
* @return this int set as an array
* @since 9.3
*/
default int[] toIntArray() {
int[] array = new int[size()];
PrimitiveIterator.OfInt iter = iterator();
int i = 0;
while (iter.hasNext()) {
array[i] = iter.next();
}
return array;
}
/**
* Returns a byte array that has a bit set for each int in this set where each byte represents 8 numbers. That is
* if the ints 2, 5 and 9 are set this will return a byte array consisting of 2 bytes in little-endian representation
* of those values.
* <p>
* Depending upon the implementation this array may or may not have trailing bytes and may be condensed to save space.
* @return a byte array containing a little-endian representation
* of all the ints of this int set as bits
* @since 12.0
*/
byte[] toBitSet();
/**
* Returns the next int in the set that is greater than or equal to the given value.
*
* @param fromIndex: inclusive index to start searching.
* @return the index of the next set bit, or -1 if there is no such bit
*/
int nextSetBit(int fromIndex);
}
| 7,518
| 32.566964
| 121
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ConcurrentSmallIntSet.java
|
package org.infinispan.commons.util;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.PrimitiveIterator;
import java.util.Set;
import java.util.Spliterator;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
import org.infinispan.commons.io.UnsignedNumeric;
/**
* Concurrent implementation of an {@link IntSet}. This implementation is limited in that it can only inserts ints up
* to an initialized maximum. Any attempt to insert/remove a larger value will result in an
* {@link IllegalArgumentException} thrown. Note that operations spanning multiple values (ie.
* {@link #containsAll(IntSet)}, {@link #removeAll(IntSet)}) are not performed atomically and are done on a per value
* basis.
* @author wburns
* @since 9.3
*/
class ConcurrentSmallIntSet implements IntSet {
private final AtomicIntegerArray array;
// Note per Java Language Specification 15.19 Shift Operators
// If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand
// are used as the shift distance.
private static final int ADDRESS_BITS_PER_INT = 5;
/* Used to shift left or right for a partial int mask */
private static final int INT_MASK = 0xffff_ffff;
private final AtomicInteger currentSize = new AtomicInteger();
/**
* Creates a new, empty map which can accommodate ints in value up to {@code maxCapacityExclusive - 1}. This number
* will be rounded up to the nearest 32.
* @param maxCapacityExclusive The implementation performs sizing to ensure values up to this can be stored
*/
public ConcurrentSmallIntSet(int maxCapacityExclusive) {
if (maxCapacityExclusive < 1) {
throw new IllegalArgumentException("maxCapacityExclusive (" + maxCapacityExclusive + ") < 1");
}
// We add 31 as that is 2^5 -1 so we round up
int intLength = intIndex(maxCapacityExclusive + 31);
array = new AtomicIntegerArray(intLength);
}
private void valueNonZero(int value) {
if (value < 0) {
throw new IllegalArgumentException("The provided value " + value + " must be 0 or greater");
}
}
private void checkBounds(int index) {
if (index >= array.length()) {
throw new IllegalArgumentException("Provided integer " + index + " was larger than originally initialized size " + array.length());
}
}
private int intIndex(int bitIndex) {
return bitIndex >> ADDRESS_BITS_PER_INT;
}
// Same idea as BitSet#nextSetBit
@Override
public int nextSetBit(int fromIndex) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex);
int u = intIndex(fromIndex);
int arrayLength = array.length();
if (u >= arrayLength)
return -1;
int possible = array.get(u) & (INT_MASK << fromIndex);
while (true) {
if (possible != 0) {
return (u << ADDRESS_BITS_PER_INT) + Integer.numberOfTrailingZeros(possible);
}
if (++u == arrayLength) {
return -1;
}
possible = array.get(u);
}
}
@Override
public boolean add(int i) {
valueNonZero(i);
int bit = 1 << i;
int idx = intIndex(i);
checkBounds(idx);
while (true) {
int num = array.get(idx);
int num2 = num | bit;
if (num == num2) {
return false;
}
if (array.compareAndSet(idx, num, num2)) {
currentSize.incrementAndGet();
return true;
}
}
}
@Override
public void set(int i) {
// No real optimizations for this so we just invoke add
add(i);
}
@Override
public boolean remove(int i) {
valueNonZero(i);
int idx = intIndex(i);
checkBounds(idx);
int bit = 1 << i;
while (true) {
int num = array.get(idx);
int unsetNum = num & ~bit;
if (num == unsetNum) {
return false;
}
if (array.compareAndSet(idx, num, unsetNum)) {
currentSize.decrementAndGet();
return true;
}
}
}
@Override
public boolean contains(int i) {
valueNonZero(i);
int idx = intIndex(i);
if (idx >= array.length()) {
return false;
}
int num = array.get(idx);
int bit = 1 << i;
return (num & bit) != 0;
}
@Override
public boolean addAll(IntSet set) {
boolean changed = false;
for (PrimitiveIterator.OfInt iter = set.iterator(); iter.hasNext(); ) {
changed |= add(iter.nextInt());
}
return changed;
}
@Override
public boolean containsAll(IntSet set) {
for (PrimitiveIterator.OfInt iter = set.iterator(); iter.hasNext(); ) {
if (!contains(iter.nextInt())) {
return false;
}
}
return true;
}
@Override
public boolean removeAll(IntSet set) {
boolean modified = false;
for (PrimitiveIterator.OfInt iter = set.iterator(); iter.hasNext(); ) {
modified |= remove(iter.nextInt());
}
return modified;
}
@Override
public boolean retainAll(IntSet set) {
boolean modified = false;
for (int i = 0; i < array.length(); ++i) {
int posValue = array.get(i);
int offset = 1;
// We iterate through the current value by always checking the least significant bit and shifting right
// until the number finally reaches zero
while (posValue > 0) {
if ((posValue & 1) == 1) {
int ourValue = (i << ADDRESS_BITS_PER_INT) + offset - 1;
if (!set.contains(ourValue)) {
modified |= remove(ourValue);
}
}
posValue >>= 1;
offset += 1;
}
}
return modified;
}
@Override
public int size() {
return currentSize.get();
}
@Override
public boolean isEmpty() {
return currentSize.get() == 0;
}
@Override
public boolean contains(Object o) {
return (o instanceof Integer) && contains((int) o);
}
@Override
public PrimitiveIterator.OfInt iterator() {
return new ConcurrentIntIterator();
}
private class ConcurrentIntIterator implements PrimitiveIterator.OfInt {
private int currentValue;
private int prevValue = -1;
ConcurrentIntIterator() {
currentValue = nextSetBit(0);
}
@Override
public int nextInt() {
if (currentValue < 0) {
throw new NoSuchElementException();
}
prevValue = currentValue;
currentValue = nextSetBit(currentValue + 1);
return prevValue;
}
@Override
public boolean hasNext() {
return currentValue >= 0;
}
@Override
public void remove() {
if (prevValue < 0) {
throw new IllegalStateException();
}
ConcurrentSmallIntSet.this.remove(prevValue);
prevValue = -1;
}
}
@Override
public final Object[] toArray() {
int size = currentSize.get();
Object[] r = new Object[size];
int index = 0;
for (int i = 0; i < array.length(); ++i) {
int value = array.get(i);
int offset = 1;
while (value > 0) {
if ((value & 1) == 1) {
if (index == size) {
size += (size >>> 1) + 1;
r = Arrays.copyOf(r, size);
}
r[index++] = (i << ADDRESS_BITS_PER_INT) + offset - 1;
}
value >>= 1;
offset += 1;
}
}
return (index == size) ? r : Arrays.copyOf(r, size);
}
@SuppressWarnings("unchecked")
@Override
public final <T> T[] toArray(T[] a) {
int currentSize = this.currentSize.get();
T[] r = (a.length >= currentSize) ? a :
(T[])java.lang.reflect.Array
.newInstance(a.getClass().getComponentType(), currentSize);
int n = r.length;
int i = 0;
for (Integer e : this) {
if (i == n) {
n += (n >>> 1) + 1;
r = Arrays.copyOf(r, n);
}
r[i++] = (T) e;
}
if (a == r && i < n) {
r[i] = null; // null-terminate
return r;
}
return (i == n) ? r : Arrays.copyOf(r, i);
}
@Override
public boolean add(Integer integer) {
return add((int) integer);
}
@Override
public boolean remove(Object o) {
return (o instanceof Integer) && remove((int) o);
}
@Override
public boolean containsAll(Collection<?> c) {
if (c instanceof IntSet) {
return containsAll((IntSet) c);
}
for (Object obj: c) {
if (!contains(obj)) {
return false;
}
}
return true;
}
@Override
public boolean addAll(Collection<? extends Integer> c) {
if (c instanceof IntSet) {
return addAll((IntSet) c);
}
boolean changed = false;
for (Integer integer : c) {
changed |= add(integer);
}
return changed;
}
@Override
public boolean retainAll(Collection<?> c) {
boolean modified = false;
for (PrimitiveIterator.OfInt iter = iterator(); iter.hasNext(); ) {
int value = iter.nextInt();
if (!c.contains(value)) {
iter.remove();
modified = true;
}
}
return modified;
}
@Override
public boolean removeAll(Collection<?> c) {
boolean modified = false;
for (Object value : c) {
modified |= remove(value);
}
return modified;
}
@Override
public void clear() {
for (int i = 0; i < array.length(); ++i) {
int oldValue = array.getAndSet(i, 0);
int bitsSet = Integer.bitCount(oldValue);
if (bitsSet != 0) {
currentSize.addAndGet(-bitsSet);
}
}
}
@Override
public IntStream intStream() {
return StreamSupport.intStream(intSpliterator(), false);
}
@Override
public Spliterator.OfInt intSpliterator() {
// We just invoke default method as ints can be sparse in AtomicReferenceArray
return IntSet.super.intSpliterator();
}
@Override
public int[] toIntArray() {
int size = currentSize.get();
int[] r = new int[size];
int index = 0;
for (int i = 0; i < array.length(); ++i) {
int value = array.get(i);
int offset = 1;
while (value != 0) {
if ((value & 1) == 1) {
if (index == size) {
size += (size >>> 1) + 1;
r = Arrays.copyOf(r, size);
}
r[index++] = (i << ADDRESS_BITS_PER_INT) + offset - 1;
}
value >>>= 1;
offset += 1;
}
}
return (index == size) ? r : Arrays.copyOf(r, size);
}
@Override
public byte[] toBitSet() {
byte[] bytes = new byte[array.length() * 8];
ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
for (int i = 0; i < array.length(); ++i) {
int value = array.get(i);
bb.putInt(value);
}
return bb.array();
}
@Override
public void forEach(Consumer<? super Integer> action) {
if (action instanceof IntConsumer) {
forEach((IntConsumer) action);
} else {
forEach((IntConsumer) action::accept);
}
}
@Override
public void forEach(IntConsumer action) {
for (int i = 0; i < array.length(); ++i) {
int value = array.get(i);
int offset = 1;
while (value != 0) {
if ((value & 1) == 1) {
action.accept((i << ADDRESS_BITS_PER_INT) + offset - 1);
}
value >>>= 1;
offset += 1;
}
}
}
@Override
public boolean removeIf(Predicate<? super Integer> filter) {
if (filter instanceof IntPredicate) {
return removeIf((IntPredicate) filter);
} else {
return removeIf((IntPredicate) filter::test);
}
}
@Override
public boolean removeIf(IntPredicate filter) {
boolean modified = false;
for (int i = 0; i < array.length(); ++i) {
int value = array.get(i);
int offset = 1;
while (value != 0) {
if ((value & 1) == 1) {
int ourValue = (i << ADDRESS_BITS_PER_INT) + offset - 1;
if (filter.test(ourValue)) {
modified |= remove(ourValue);
}
}
value >>>= 1;
offset += 1;
}
}
return modified;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || !(o instanceof Set))
return false;
Set set = (Set) o;
// containsAll handles casting as necessary
return size() == set.size() && containsAll(set);
}
@Override
public int hashCode() {
int hashCode = 0;
for (int i = 0; i < array.length(); ++i) {
int value = array.get(i);
hashCode *= 37;
hashCode += value;
}
return hashCode;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) {
if (sb.length() > "{".length()) {
sb.append(' ');
}
int runStart = i;
while (contains(i + 1)) {
i++;
}
if (i == runStart) {
sb.append(i);
} else {
sb.append(runStart).append('-').append(i);
}
}
sb.append('}');
return sb.toString();
}
static void writeTo(ObjectOutput output, ConcurrentSmallIntSet intSet) throws IOException {
int arrayLength = intSet.array.length();
UnsignedNumeric.writeUnsignedInt(output, arrayLength);
for (int i = 0; i < arrayLength; ++i) {
output.writeInt(intSet.array.get(i));
}
}
static IntSet readFrom(ObjectInput input) throws IOException {
int arrayLength = UnsignedNumeric.readUnsignedInt(input);
ConcurrentSmallIntSet intSet = new ConcurrentSmallIntSet(arrayLength << ADDRESS_BITS_PER_INT);
int size = 0;
for (int i = 0; i < arrayLength - 1; ++i) {
int value = input.readInt();
// Use lazy set - we use set below on the last
intSet.array.lazySet(i, value);
size += Integer.bitCount(value);
}
int lastValue = input.readInt();
intSet.array.set(arrayLength - 1, lastValue);
size += Integer.bitCount(lastValue);
intSet.currentSize.addAndGet(size);
return intSet;
}
}
| 15,269
| 26.713249
| 140
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/CloseableIteratorSetAdapter.java
|
package org.infinispan.commons.util;
import java.util.Set;
/**
* Adapts {@link Set} to {@link CloseableIteratorSet}
*
* @author Radim Vansa <rvansa@redhat.com>
*/
public class CloseableIteratorSetAdapter<E> extends CloseableIteratorCollectionAdapter<E> implements CloseableIteratorSet<E> {
public CloseableIteratorSetAdapter(Set<E> delegate) {
super(delegate);
}
@Override
public CloseableSpliterator<E> spliterator() {
return Closeables.spliterator(delegate.spliterator());
}
}
| 519
| 25
| 126
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/Immutables.java
|
package org.infinispan.commons.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Reader;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import org.infinispan.commons.marshall.AbstractExternalizer;
import org.infinispan.commons.marshall.Ids;
import org.infinispan.commons.marshall.MarshallUtil;
/**
* Factory for generating immutable type wrappers.
*
* @author Jason T. Greene
* @author Galder Zamarreño
* @author Tristan Tarrant
* @since 4.0
*/
public class Immutables {
/**
* Whether or not this collection type is immutable
*
* @param o a Collection, Set, List, or Map
* @return true if immutable, false if not
*/
public static boolean isImmutable(Object o) {
return o instanceof Immutable;
}
/**
* Converts a Collection to an immutable List by copying it.
*
* @param source the collection to convert
* @return a copied/converted immutable list
*/
public static <T> List<T> immutableListConvert(Collection<? extends T> source) {
return new ImmutableListCopy<>(source);
}
/**
*
* Creates an immutable copy of the list.
*
* @param list the list to copy
* @return the immutable copy
*/
public static <T> List<T> immutableListCopy(List<T> list) {
if (list == null) return null;
if (list.isEmpty()) return Collections.emptyList();
if (list.size() == 1) return Collections.singletonList(list.get(0));
if (list instanceof ImmutableListCopy) return list;
return new ImmutableListCopy<>(list);
}
/**
* Creates an immutable copy of the properties.
*
* @param properties the TypedProperties to copy
* @return the immutable copy
*/
public static TypedProperties immutableTypedProperties(TypedProperties properties) {
if (properties == null) return null;
return new ImmutableTypedProperties(properties);
}
/**
* Wraps an array with an immutable list. There is no copying involved.
*
* @param array the array to wrap
* @return a list containing the array
*/
public static <T> List<T> immutableListWrap(T... array) {
return new ImmutableListCopy<>(array);
}
/**
* Creates a new immutable list containing the union (combined entries) of both lists.
*
* @param list1 contains the first elements of the new list
* @param list2 contains the successor elements of the new list
* @return a new immutable merged copy of list1 and list2
*/
public static <T> List<T> immutableListMerge(List<? extends T> list1, List<? extends T> list2) {
return new ImmutableListCopy<>(list1, list2);
}
public static <T> ImmutableListCopy<T> immutableListAdd(List<T> list, int position, T element) {
T[] copy = (T[]) new Object[list.size() + 1];
for (int i = 0; i < position; i++) {
copy[i] = list.get(i);
}
copy[position] = element;
for (int i = position; i < list.size(); i++) {
copy[i + 1] = list.get(i);
}
return new ImmutableListCopy<>(copy);
}
public static <T> ImmutableListCopy<T> immutableListReplace(List<T> list, int position, T element) {
T[] copy = (T[]) new Object[list.size()];
for (int i = 0; i < position; i++) {
copy[i] = list.get(i);
}
copy[position] = element;
for (int i = position + 1; i < list.size(); i++) {
copy[i] = list.get(i);
}
return new ImmutableListCopy<>(copy);
}
public static <T> List<T> immutableListRemove(List<T> list, int position) {
T[] copy = (T[]) new Object[list.size() - 1];
for (int i = 0; i < position; i++) {
copy[i] = list.get(i);
}
for (int i = position + 1; i < list.size(); i++) {
copy[i - 1] = list.get(i);
}
return new ImmutableListCopy<>(copy);
}
/**
* Converts a Collections into an immutable Set by copying it.
*
* @param collection the collection to convert/copy
* @return a new immutable set containing the elements in collection
*/
public static <T> Set<T> immutableSetConvert(Collection<? extends T> collection) {
return immutableSetWrap(new HashSet<T>(collection));
}
/**
* Wraps a set with an immutable set. There is no copying involved.
*
* @param set the set to wrap
* @return an immutable set wrapper that delegates to the original set
*/
public static <T> Set<T> immutableSetWrap(Set<? extends T> set) {
return new ImmutableSetWrapper<>(set);
}
/**
* Creates an immutable copy of the specified set.
*
* @param set the set to copy from
* @return an immutable set copy
*/
public static <T> Set<T> immutableSetCopy(Set<T> set) {
if (set == null) return null;
if (set.isEmpty()) return Collections.emptySet();
if (set.size() == 1) return Collections.singleton(set.iterator().next());
return new ImmutableSetWrapper<>(new HashSet<>(set));
}
/**
* Wraps a map with an immutable map. There is no copying involved.
*
* @param map the map to wrap
* @return an immutable map wrapper that delegates to the original map
*/
public static <K, V> Map<K, V> immutableMapWrap(Map<? extends K, ? extends V> map) {
return new ImmutableMapWrapper<>(map);
}
/**
* Creates an immutable copy of the specified map.
*
* @param map the map to copy from
* @return an immutable map copy
*/
public static <K, V> Map<K, V> immutableMapCopy(Map<K, V> map) {
if (map == null) return null;
if (map.isEmpty()) return Collections.emptyMap();
if (map.size() == 1) {
Map.Entry<K, V> me = map.entrySet().iterator().next();
return Collections.singletonMap(me.getKey(), me.getValue());
}
return new ImmutableMapWrapper<>(new HashMap<>(map));
}
/**
* Creates a new immutable copy of the specified Collection.
*
* @param collection the collection to copy
* @return an immutable copy
*/
public static <T> Collection<T> immutableCollectionCopy(Collection<T> collection) {
if (collection == null) return null;
if (collection.isEmpty()) return Collections.emptySet();
if (collection.size() == 1) return Collections.singleton(collection.iterator().next());
return new ImmutableCollectionWrapper<>(new ArrayList<>(collection));
}
/**
* Wraps a collection with an immutable collection. There is no copying involved.
*
* @param collection the collection to wrap
* @return an immutable collection wrapper that delegates to the original collection
*/
public static <T> Collection<T> immutableCollectionWrap(Collection<? extends T> collection) {
return new ImmutableCollectionWrapper<>(collection);
}
/**
* Wraps a {@link Map.Entry}} with an immutable {@link Map.Entry}}. There is no copying involved.
*
* @param entry the mapping to wrap.
* @return an immutable {@link Map.Entry}} wrapper that delegates to the original mapping.
*/
public static <K, V> Map.Entry<K, V> immutableEntry(Map.Entry<K, V> entry) {
return new ImmutableEntry<>(entry);
}
/**
* Wraps a key and value with an immutable {@link Map.Entry}}. There is no copying involved.
*
* @param key the key to wrap.
* @param value the value to wrap.
* @return an immutable {@link Map.Entry}} wrapper that delegates to the original mapping.
*/
public static <K, V> Map.Entry<K, V> immutableEntry(K key, V value) {
return new ImmutableEntry<>(key, value);
}
public interface Immutable {
}
/*
* Immutable wrapper types.
*
* We have to re-implement Collections.unmodifiableXXX, since it is not
* simple to detect them (the class names are JDK dependent).
*/
public static class ImmutableIteratorWrapper<E> implements Iterator<E> {
private final Iterator<? extends E> iterator;
public ImmutableIteratorWrapper(Iterator<? extends E> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public E next() {
return iterator.next();
}
// Use the default remove() implementation
@Override
public void forEachRemaining(Consumer<? super E> action) {
iterator.forEachRemaining(action);
}
}
private static class ImmutableCollectionWrapper<E> implements Collection<E>, Serializable, Immutable {
private static final long serialVersionUID = 6777564328198393535L;
Collection<? extends E> collection;
public ImmutableCollectionWrapper(Collection<? extends E> collection) {
this.collection = collection;
}
@Override
public boolean add(E o) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean contains(Object o) {
return collection.contains(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return collection.containsAll(c);
}
@Override
public boolean equals(Object o) {
return collection.equals(o);
}
@Override
public int hashCode() {
return collection.hashCode();
}
@Override
public boolean isEmpty() {
return collection.isEmpty();
}
@Override
public Iterator<E> iterator() {
return new ImmutableIteratorWrapper<>(collection.iterator());
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
return collection.size();
}
@Override
public Object[] toArray() {
return collection.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return collection.toArray(a);
}
@Override
public String toString() {
return collection.toString();
}
}
/**
* Immutable version of Map.Entry for traversing immutable collections.
*/
private static class ImmutableEntry<K, V> implements Entry<K, V>, Immutable {
private final K key;
private final V value;
private final int hash;
ImmutableEntry(Entry<? extends K, ? extends V> entry) {
this.key = entry.getKey();
this.value = entry.getValue();
this.hash = entry.hashCode();
}
ImmutableEntry(K key, V value) {
this.key = key;
this.value = value;
this.hash = Objects.hashCode(key) ^ Objects.hashCode(value);
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
throw new UnsupportedOperationException();
}
private static boolean eq(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@Override
@SuppressWarnings("unchecked")
public boolean equals(Object o) {
if (!(o instanceof Entry))
return false;
Entry<K, V> entry = (Entry<K, V>) o;
return eq(entry.getKey(), key) && eq(entry.getValue(), value);
}
@Override
public int hashCode() {
return hash;
}
@Override
public String toString() {
return getKey() + "=" + getValue();
}
}
private static class ImmutableSetWrapper<E> extends ImmutableCollectionWrapper<E> implements Set<E>, Serializable, Immutable {
private static final long serialVersionUID = 7991492805176142615L;
public ImmutableSetWrapper(Set<? extends E> set) {
super(set);
}
}
private static class ImmutableEntrySetWrapper<K, V> extends ImmutableSetWrapper<Entry<K, V>> {
private static final long serialVersionUID = 6378667653889667692L;
@SuppressWarnings("unchecked")
public ImmutableEntrySetWrapper(Set<? extends Entry<? extends K, ? extends V>> set) {
super((Set<Entry<K, V>>) set);
}
@Override
public Object[] toArray() {
Object[] array = new Object[collection.size()];
int i = 0;
for (Entry<K, V> entry : this)
array[i++] = entry;
return array;
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] array) {
int size = collection.size();
if (array.length < size)
array = (T[]) Array.newInstance(array.getClass().getComponentType(), size);
int i = 0;
Object[] result = array;
for (Entry<K, V> entry : this)
result[i++] = entry;
return array;
}
@Override
public Iterator<Entry<K, V>> iterator() {
return new ImmutableIteratorWrapper<Entry<K, V>>(collection.iterator()) {
@Override
public Entry<K, V> next() {
return new ImmutableEntry<>(super.next());
}
};
}
}
public static class ImmutableSetWrapperExternalizer extends AbstractExternalizer<Set> {
@Override
public void writeObject(ObjectOutput output, Set set) throws IOException {
MarshallUtil.marshallCollection(set, output);
}
@Override
public Set readObject(ObjectInput input) throws IOException, ClassNotFoundException {
Set<Object> set = MarshallUtil.unmarshallCollection(input, HashSet::new);
return Immutables.immutableSetWrap(set);
}
@Override
public Integer getId() {
return Ids.IMMUTABLE_SET;
}
@Override
public Set<Class<? extends Set>> getTypeClasses() {
return Util.asSet(ImmutableSetWrapper.class);
}
}
private static class ImmutableMapWrapper<K, V> implements Map<K, V>, Serializable, Immutable {
private static final long serialVersionUID = 708144227046742221L;
private final Map<? extends K, ? extends V> map;
public ImmutableMapWrapper(Map<? extends K, ? extends V> map) {
this.map = map;
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return map.containsValue(value);
}
@Override
public Set<Entry<K, V>> entrySet() {
return new ImmutableEntrySetWrapper<>(map.entrySet());
}
@Override
public boolean equals(Object o) {
return map.equals(o);
}
@Override
public V get(Object key) {
return map.get(key);
}
@Override
public int hashCode() {
return map.hashCode();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public Set<K> keySet() {
return new ImmutableSetWrapper<>(map.keySet());
}
@Override
public V put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends K, ? extends V> t) {
throw new UnsupportedOperationException();
}
@Override
public V remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
return map.size();
}
@Override
public Collection<V> values() {
return new ImmutableCollectionWrapper<>(map.values());
}
@Override
public String toString() {
return map.toString();
}
}
public static class ImmutableMapWrapperExternalizer extends AbstractExternalizer<Map> {
@Override
public void writeObject(ObjectOutput output, Map map) throws IOException {
MarshallUtil.marshallMap(map, output);
}
@Override
public Map readObject(ObjectInput input) throws IOException, ClassNotFoundException {
return Immutables.immutableMapWrap(MarshallUtil.unmarshallMap(input, HashMap::new));
}
@Override
public Integer getId() {
return Ids.IMMUTABLE_MAP;
}
@Override
public Set<Class<? extends Map>> getTypeClasses() {
return Util.asSet(ImmutableMapWrapper.class);
}
}
private static class ImmutableTypedProperties extends TypedProperties {
ImmutableTypedProperties(TypedProperties properties) {
super();
if (properties != null && !properties.isEmpty()) {
for (Map.Entry<Object, Object> e: properties.entrySet()) super.put(e.getKey(), e.getValue());
}
}
@Override
public synchronized void clear() {
throw new UnsupportedOperationException();
}
@Override
public Set<java.util.Map.Entry<Object, Object>> entrySet() {
return new ImmutableEntrySetWrapper<>(super.entrySet());
}
@Override
public Set<Object> keySet() {
return new ImmutableSetWrapper<>(super.keySet());
}
@Override
public synchronized void load(InputStream inStream) {
throw new UnsupportedOperationException();
}
@Override
public synchronized void load(Reader reader) {
throw new UnsupportedOperationException();
}
@Override
public synchronized void loadFromXML(InputStream in) {
throw new UnsupportedOperationException();
}
@Override
public synchronized Object put(Object key, Object value) {
throw new UnsupportedOperationException();
}
@Override
public synchronized void putAll(Map<?, ?> t) {
throw new UnsupportedOperationException();
}
@Override
public synchronized Object remove(Object key) {
throw new UnsupportedOperationException();
}
@Override
public synchronized TypedProperties setProperty(String key, String value) {
throw new UnsupportedOperationException();
}
@Override
public Set<String> stringPropertyNames() {
return new ImmutableSetWrapper<>(super.stringPropertyNames());
}
@Override
public Collection<Object> values() {
return new ImmutableCollectionWrapper<>(super.values());
}
}
}
| 19,350
| 27.290936
| 129
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/EmptyIntSet.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.PrimitiveIterator;
import java.util.Set;
import java.util.stream.IntStream;
/**
* Immutable empty IntSet
* @author wburns
* @since 9.3
*/
class EmptyIntSet extends AbstractImmutableIntSet {
// We just use default hashCode as we only have 1 instance
private final static EmptyIntSet INSTANCE = new EmptyIntSet();
public static IntSet getInstance() {
return INSTANCE;
}
@Override
public boolean contains(int i) {
return false;
}
@Override
public boolean containsAll(IntSet set) {
return set.isEmpty();
}
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public boolean contains(Object o) {
return false;
}
@Override
public PrimitiveIterator.OfInt iterator() {
return EmptyIntIterator.INSTANCE;
}
private static class EmptyIntIterator implements PrimitiveIterator.OfInt {
private static final EmptyIntIterator INSTANCE = new EmptyIntIterator();
@Override
public int nextInt() {
throw new NoSuchElementException();
}
@Override
public boolean hasNext() {
return false;
}
}
@Override
public Object[] toArray() {
return new Object[0];
}
@Override
public <T> T[] toArray(T[] a) {
return a;
}
@Override
public boolean containsAll(Collection<?> c) {
return c.isEmpty();
}
@Override
public IntStream intStream() {
return IntStream.empty();
}
@Override
public byte[] toBitSet() {
return Util.EMPTY_BYTE_ARRAY;
}
@Override
public int nextSetBit(int fromIndex) {
return -1;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Set) {
return ((Set) obj).size() == 0;
}
return false;
}
@Override
public String toString() {
return "{}";
}
}
| 2,055
| 17.862385
| 78
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ProcessorInfo.java
|
package org.infinispan.commons.util;
/**
* Provides general information about the processors on this host.
*
* @author Tristan Tarrant
*/
public class ProcessorInfo {
private ProcessorInfo() {
}
/**
* Returns the number of processors available to this process. On most operating systems this method
* simply delegates to {@link Runtime#availableProcessors()}. However, before Java 10, under Linux this strategy
* is insufficient, since the JVM does not take into consideration the process' CPU set affinity and the CGroups
* quota/period assignment. Therefore this method will analyze the Linux proc filesystem
* to make the determination. Since the CPU affinity of a process can be change at any time, this method does
* not cache the result. Calls should be limited accordingly.
* <br>
* The number of available processors can be overridden via the system property <tt>infinispan.activeprocessorcount</tt>,
* e.g. <tt>java -Dinfinispan.activeprocessorcount=4 ...</tt>. Note that this value cannot exceed the actual number
* of available processors.
* <br>
* Since Java 10, this can also be achieved via the VM flag <tt>-XX:ActiveProcessorCount=xx</tt>.
* <br>
* Note that on Linux, both SMT units (Hyper-Threading) and CPU cores are counted as a processor.
*
* @return the available processors on this system.
*/
public static int availableProcessors() {
return org.infinispan.commons.jdkspecific.ProcessorInfo.availableProcessors();
}
public static void main(String args[]) {
System.out.println(availableProcessors());
}
}
| 1,635
| 40.948718
| 124
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/AbstractDelegatingSet.java
|
package org.infinispan.commons.util;
import java.util.Set;
public abstract class AbstractDelegatingSet<E> extends AbstractDelegatingCollection<E> implements Set<E> {
protected abstract Set<E> delegate();
}
| 212
| 22.666667
| 106
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ObjectDuplicator.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* A helper that efficiently duplicates known object types.
*
* @author (various)
* @deprecated Since 12, will be removed in version 15.0
*/
@Deprecated
public class ObjectDuplicator {
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> duplicateMap(Map<K, V> original) {
if (original instanceof FastCopyHashMap)
return ((FastCopyHashMap<K, V>) original).clone();
if (original instanceof HashMap)
return (Map<K, V>) ((HashMap<K, V>) original).clone();
if (original instanceof TreeMap)
return (Map<K, V>) ((TreeMap<K, V>) original).clone();
if (original.getClass().equals(Collections.emptyMap().getClass()))
return Collections.emptyMap();
if (original.getClass().equals(Collections.singletonMap("", "").getClass())) {
Map.Entry<K, V> e = original.entrySet().iterator().next();
return Collections.singletonMap(e.getKey(), e.getValue());
}
return attemptClone(original);
}
@SuppressWarnings("unchecked")
public static <E> Set<E> duplicateSet(Set<E> original) {
if (original instanceof HashSet)
return (Set<E>) ((HashSet<E>) original).clone();
if (original instanceof TreeSet)
return (Set<E>) ((TreeSet<E>) original).clone();
if (original instanceof FastCopyHashMap.EntrySet || original instanceof FastCopyHashMap.KeySet)
return new HashSet<>(original);
if (original.getClass().equals(Collections.emptySet().getClass()))
return Collections.emptySet();
if (original.getClass().equals(Collections.singleton("").getClass()))
return Collections.singleton(original.iterator().next());
if (original.getClass().getSimpleName().contains("$"))
return new HashSet<>(original);
return attemptClone(original);
}
@SuppressWarnings("unchecked")
public static <E> Collection<E> duplicateCollection(Collection<E> original) {
if (original instanceof HashSet)
return (Set<E>) ((HashSet<E>) original).clone();
if (original instanceof TreeSet)
return (Set<E>) ((TreeSet<E>) original).clone();
return attemptClone(original);
}
@SuppressWarnings("unchecked")
private static <T> T attemptClone(T source) {
if (source instanceof Cloneable) {
try {
return (T) source.getClass().getMethod("clone").invoke(source);
}
catch (Exception e) {
// Will return null
}
}
return null;
}
}
| 2,762
| 33.5375
| 101
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/InstanceSupplier.java
|
package org.infinispan.commons.util;
import java.util.function.Supplier;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 13.0
**/
public class InstanceSupplier<T> implements Supplier<T> {
private final T instance;
public InstanceSupplier(T instance) {
this.instance = instance;
}
@Override
public T get() {
return instance;
}
}
| 387
| 17.47619
| 57
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/IteratorMapper.java
|
package org.infinispan.commons.util;
import java.util.Iterator;
import java.util.function.Function;
/**
* A iterator that maps each value to the output of the Function. Note that the remove is supported if the iterator
* originally supported remove. This iterator implements {@link CloseableIterator} and will close the provided iterator
* if it also implemented CloseableIterator.
* @author William Burns
* @since 8.0
*/
public class IteratorMapper<E, S> implements CloseableIterator<S> {
private final Iterator<? extends E> iterator;
private final Function<? super E, ? extends S> function;
public IteratorMapper(Iterator<? extends E> iterator, Function<? super E, ? extends S> function) {
if (iterator == null || function == null) {
throw new NullPointerException();
}
this.iterator = iterator;
this.function = function;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public S next() {
E value = iterator.next();
return function.apply(value);
}
@Override
public void remove() {
iterator.remove();
}
@Override
public void close() {
if (iterator instanceof CloseableIterator) {
((CloseableIterator) iterator).close();
}
}
}
| 1,296
| 26.020833
| 119
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/EnumerationList.java
|
package org.infinispan.commons.util;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
/**
* An Enumeration → List adaptor
*
* @author Pete Muir
*/
public class EnumerationList<T> extends ForwardingList<T>
{
// The enumeration as a list
private final List<T> list = new LinkedList<T>();
/**
* Constructor
*
* @param enumeration The enumeration
*/
public EnumerationList(Enumeration<T> enumeration)
{
while (enumeration.hasMoreElements())
{
list.add(enumeration.nextElement());
}
}
@Override
protected List<T> delegate()
{
return list;
}
}
| 664
| 16.972973
| 57
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/FlattenSpliterator.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.IntFunction;
/**
* Composes an array of Collections into a spliterator. This spliterator will only split up to the collection and will
* not split the spliterator from the collection itself.
* @author wburns
* @since 9.3
*/
public class FlattenSpliterator<E> implements Spliterator<E> {
private final IntFunction<Collection<E>> toCollection;
private final int length;
private int index; // current index, modified on advance/split
private final int fence; // one past last index
private final int characteristics;
private Spliterator<E> currentSpliterator;
public FlattenSpliterator(IntFunction<Collection<E>> toCollection, int length, int additionalCharacteristics) {
this(toCollection, length, 0, length, additionalCharacteristics);
}
private FlattenSpliterator(IntFunction<Collection<E>> toCollection, int length, int index, int fence, int characteristics) {
this.toCollection = toCollection;
this.length = length;
if (index < 0) {
throw new IllegalArgumentException("Index " + index + " was less than 0!");
}
this.index = index;
this.fence = fence;
this.characteristics = characteristics;
}
@Override
public boolean tryAdvance(Consumer<? super E> action) {
boolean advanced = false;
// If the current spliterator is null or can't advance the current action try the next one
while ((currentSpliterator == null || !(advanced = currentSpliterator.tryAdvance(action))) && index < fence) {
currentSpliterator = toCollection.apply(index++).spliterator();
}
return advanced;
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
for (; index < fence; ++index) {
toCollection.apply(index).spliterator().forEachRemaining(action);
}
}
@Override
public Spliterator<E> trySplit() {
int lo = index, mid = (lo + fence) >>> 1;
return (lo >= mid)
? null
: new FlattenSpliterator<>(toCollection, length, lo, index = mid, characteristics);
}
@Override
public long estimateSize() {
long estimate = 0;
if (currentSpliterator != null) {
estimate += currentSpliterator.estimateSize();
}
if (estimate == Long.MAX_VALUE) {
return estimate;
}
for (int i = index; i < fence; ++i) {
estimate += toCollection.apply(i).size();
if (estimate < 0) {
return Long.MAX_VALUE;
}
}
return estimate;
}
@Override
public int characteristics() {
return characteristics;
}
}
| 2,774
| 31.267442
| 127
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/AbstractFileLookup.java
|
package org.infinispan.commons.util;
import static org.infinispan.commons.logging.Log.CONTAINER;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Collection;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.util.FileLookupFactory.DefaultFileLookup;
public abstract class AbstractFileLookup implements FileLookup {
private static final Log log = LogFactory.getLog(AbstractFileLookup.class);
public AbstractFileLookup() {
super();
}
/**
* Looks up the file, see : {@link DefaultFileLookup}.
*
* @param filename might be the name of the file (too look it up in the class path) or an url to a file.
* @return an input stream to the file or null if nothing found through all lookup steps.
*/
@Override
public InputStream lookupFile(String filename, ClassLoader cl) {
try {
return lookupFileStrict( filename, cl );
}
catch (FileNotFoundException e) {
return null;
}
}
protected abstract InputStream getAsInputStreamFromClassLoader(String filename, ClassLoader cl);
/**
* Looks up the file, see : {@link DefaultFileLookup}.
*
* @param filename might be the name of the file (too look it up in the class path) or an url to a file.
* @return an input stream to the file or null if nothing found through all lookup steps.
* @throws FileNotFoundException if file cannot be found
*/
@Override
public InputStream lookupFileStrict(String filename, ClassLoader cl) throws FileNotFoundException {
InputStream is = filename == null || filename.length() == 0 ? null : getAsInputStreamFromClassLoader(filename, cl);
if (is == null) {
if (log.isDebugEnabled())
log.debugf("Unable to find file %s in classpath; searching for this file on the filesystem instead.", filename);
return new FileInputStream(filename);
}
return is;
}
@Override
public InputStream lookupFileStrict(URI uri, ClassLoader cl) throws FileNotFoundException {
String scheme = uri.getScheme();
switch (scheme) {
case "file":
return new FileInputStream(new File(uri.getPath()));
case "jar": {
String uriAsString = uri.toString();
String insideJarFilePath = uriAsString.substring(uriAsString.lastIndexOf("!") + 1);
InputStream streamToBeReturned = getAsInputStreamFromClassLoader(insideJarFilePath, cl);
if (streamToBeReturned == null) {
throw CONTAINER.unableToLoadFileUsingScheme(scheme);
}
return streamToBeReturned;
}
default:
InputStream streamToBeReturned = getAsInputStreamFromClassLoader(uri.toString(), cl);
if(streamToBeReturned == null) {
throw CONTAINER.unableToLoadFileUsingScheme(scheme);
}
return streamToBeReturned;
}
}
@Override
public URL lookupFileLocation(String filename, ClassLoader cl) {
URL u = getAsURLFromClassLoader(filename, cl);
if (u == null) {
File f = new File(filename);
if (f.exists()) try {
u = f.toURI().toURL();
}
catch (MalformedURLException e) {
// what do we do here?
}
}
return u;
}
protected abstract URL getAsURLFromClassLoader(String filename, ClassLoader cl);
@Override
public Collection<URL> lookupFileLocations(String filename, ClassLoader cl) throws IOException {
Collection<URL> u = getAsURLsFromClassLoader(filename, cl);
File f = new File(filename);
if (f.exists()) try {
u.add(f.toURI().toURL());
}
catch (MalformedURLException e) {
// what do we do here?
}
return u;
}
protected abstract Collection<URL> getAsURLsFromClassLoader(String filename, ClassLoader cl) throws IOException;
}
| 4,155
| 32.788618
| 124
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/SpliteratorMapper.java
|
package org.infinispan.commons.util;
import java.util.Objects;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* A spliterator that has been mapped from another spliterator. This is nice to only lazily convert these values, so
* that you can convert across multiple threads or if the entire spliterator is not consumed.
* <p>
* This spliterator will <b>always</b> throw an {@link IllegalStateException} upon invocation of
* {@link Spliterator#getComparator()} since there is no trivial way of converting this with a mapper.
* @author wburns
* @since 9.0
*/
public class SpliteratorMapper<E, S> implements CloseableSpliterator<S> {
protected final Spliterator<E> spliterator;
protected final Function<? super E, ? extends S> mapper;
public SpliteratorMapper(Spliterator<E> spliterator, Function<? super E, ? extends S> mapper) {
this.spliterator = Objects.requireNonNull(spliterator);
this.mapper = Objects.requireNonNull(mapper);
}
@Override
public boolean tryAdvance(Consumer<? super S> action) {
return spliterator.tryAdvance(e -> action.accept(mapper.apply(e)));
}
@Override
public Spliterator<S> trySplit() {
Spliterator<E> split = spliterator.trySplit();
if (split != null) {
return new SpliteratorMapper<>(split, mapper);
}
return null;
}
@Override
public long estimateSize() {
return spliterator.estimateSize();
}
@Override
public int characteristics() {
int characteristics = spliterator.characteristics();
if (mapper instanceof InjectiveFunction) {
return characteristics;
} else {
// Have to unset distinct if the function wasn't distinct
return characteristics & ~Spliterator.DISTINCT;
}
}
@Override
public void forEachRemaining(Consumer<? super S> action) {
spliterator.forEachRemaining(e -> action.accept(mapper.apply(e)));
}
@Override
public long getExactSizeIfKnown() {
return spliterator.getExactSizeIfKnown();
}
@Override
public boolean hasCharacteristics(int characteristics) {
return spliterator.hasCharacteristics(characteristics);
}
@Override
public void close() {
if (spliterator instanceof CloseableSpliterator) {
((CloseableSpliterator) spliterator).close();
}
}
}
| 2,398
| 29.75641
| 117
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/AbstractImmutableIntSet.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
/**
* Abstract IntSet that throws an {@link UnsupportedOperationException} for all write operations on an IntSet.
* <p>
* It is up to implementors to ensure that {@link java.util.PrimitiveIterator.OfInt#remove()} throws the same exception.
* @author wburns
* @since 9.3
*/
abstract class AbstractImmutableIntSet implements IntSet {
@Override
public boolean add(int i) {
throw new UnsupportedOperationException();
}
@Override
public void set(int i) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(int i) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(IntSet set) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(IntSet c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean add(Integer integer) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(IntSet set) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends Integer> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean removeIf(Predicate<? super Integer> filter) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeIf(IntPredicate filter) {
throw new UnsupportedOperationException();
}
}
| 2,021
| 22.788235
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/Proxies.java
|
package org.infinispan.commons.util;
import java.lang.reflect.Method;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* Proxies is a collection of useful dynamic profixes. Internal use only.
*
* @author vladimir
* @since 4.0
*/
public class Proxies {
public static Object newCatchThrowableProxy(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
getInterfaces(obj.getClass()), new CatchThrowableProxy(obj));
}
private static Class<?>[] getInterfaces(Class<?> clazz) {
Class<?>[] interfaces = clazz.getInterfaces();
if (interfaces.length > 0) {
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && superClass.getInterfaces().length > 0) {
Class<?>[] superInterfaces = superClass.getInterfaces();
Class<?>[] clazzes = new Class[interfaces.length + superInterfaces.length];
System.arraycopy(interfaces, 0, clazzes, 0, interfaces.length);
System.arraycopy(superInterfaces, 0, clazzes, interfaces.length, superInterfaces.length);
return clazzes;
} else {
return interfaces;
}
}
Class<?> superclass = clazz.getSuperclass();
if (!superclass.equals(Object.class))
return superclass.getInterfaces();
return ReflectionUtil.EMPTY_CLASS_ARRAY;
}
/**
* CatchThrowableProxy is a wrapper around interface that does not allow any exception to be
* thrown when invoking methods on that interface. All exceptions are logged but not propagated
* to the caller.
*
*
*/
static class CatchThrowableProxy implements java.lang.reflect.InvocationHandler {
private static final Log log = LogFactory.getLog(CatchThrowableProxy.class);
private Object obj;
public static Object newInstance(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(), new CatchThrowableProxy(obj));
}
private CatchThrowableProxy(Object obj) {
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Object result = null;
try {
result = m.invoke(obj, args);
} catch (Throwable t) {
log.ignoringException(m.getName(), t.getMessage(), t.getCause());
} finally {
}
return result;
}
}
}
| 2,639
| 34.2
| 101
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/MemoryUnit.java
|
package org.infinispan.commons.util;
/**
* @deprecated since 11.0, use {@link ByteQuantity} instead.
*/
@Deprecated
public enum MemoryUnit {
BYTES("B") {
@Override
public long convert(long sourceSize, MemoryUnit sourceUnit) {
return sourceUnit.toBytes(sourceSize);
}
@Override
public long toBytes(long size) {
return size;
}
@Override
public long toKiloBytes(long size) {
return size / KILO;
}
@Override
public long toKibiBytes(long size) {
return size / KIBI;
}
@Override
public long toMegaBytes(long size) {
return size / MEGA;
}
@Override
public long toMebiBytes(long size) {
return size / MEBI;
}
@Override
public long toGigaBytes(long size) {
return size / GIGA;
}
@Override
public long toGibiBytes(long size) {
return size / GIBI;
}
@Override
public long toTeraBytes(long size) {
return size / TERA;
}
@Override
public long toTebiBytes(long size) {
return size / TEBI;
}
},
KILOBYTES("K") {
@Override
public long convert(long sourceSize, MemoryUnit sourceUnit) {
return sourceUnit.toKiloBytes(sourceSize);
}
@Override
public long toBytes(long size) {
return x(size, KILO, MAX / KILO);
}
@Override
public long toKiloBytes(long size) {
return size;
}
@Override
public long toKibiBytes(long size) {
return f(size, KILO, KIBI);
}
@Override
public long toMegaBytes(long size) {
return size / KILO;
}
@Override
public long toMebiBytes(long size) {
return f(size, KILO, MEBI);
}
@Override
public long toGigaBytes(long size) {
return size / MEGA;
}
@Override
public long toGibiBytes(long size) {
return f(size, KILO, GIBI);
}
@Override
public long toTeraBytes(long size) {
return size / GIGA;
}
@Override
public long toTebiBytes(long size) {
return f(size, KILO, TEBI);
}
},
KIBIBYTES("Ki") {
@Override
public long convert(long sourceSize, MemoryUnit sourceUnit) {
return sourceUnit.toKibiBytes(sourceSize);
}
@Override
public long toBytes(long size) {
return x(size, KIBI, MAX / KIBI);
}
@Override
public long toKiloBytes(long size) {
return f(size, KIBI, KILO);
}
@Override
public long toKibiBytes(long size) {
return size;
}
@Override
public long toMegaBytes(long size) {
return f(size, KIBI, MEGA);
}
@Override
public long toMebiBytes(long size) {
return size / KIBI;
}
@Override
public long toGigaBytes(long size) {
return f(size, KIBI, GIGA);
}
@Override
public long toGibiBytes(long size) {
return size / MEBI;
}
@Override
public long toTeraBytes(long size) {
return f(size, KIBI, TERA);
}
@Override
public long toTebiBytes(long size) {
return size / GIBI;
}
},
MEGABYTES("M") {
@Override
public long convert(long sourceSize, MemoryUnit sourceUnit) {
return sourceUnit.toMegaBytes(sourceSize);
}
@Override
public long toBytes(long size) {
return x(size, MEGA, MAX / MEGA);
}
@Override
public long toKiloBytes(long size) {
return x(size, KILO, MAX / KILO);
}
@Override
public long toKibiBytes(long size) {
return f(size, MEGA, KIBI);
}
@Override
public long toMegaBytes(long size) {
return size;
}
@Override
public long toMebiBytes(long size) {
return f(size, MEGA, MEBI);
}
@Override
public long toGigaBytes(long size) {
return size / KILO;
}
@Override
public long toGibiBytes(long size) {
return f(size, MEGA, GIBI);
}
@Override
public long toTeraBytes(long size) {
return size / MEGA;
}
@Override
public long toTebiBytes(long size) {
return f(size, MEGA, TEBI);
}
},
MEBIBYTES("Mi") {
@Override
public long convert(long sourceSize, MemoryUnit sourceUnit) {
return sourceUnit.toMebiBytes(sourceSize);
}
@Override
public long toBytes(long size) {
return x(size, MEBI, MAX / MEBI);
}
@Override
public long toKiloBytes(long size) {
return f(size, MEBI, KILO);
}
@Override
public long toKibiBytes(long size) {
return x(size, KIBI, MAX / KIBI);
}
@Override
public long toMegaBytes(long size) {
return f(size, MEBI, MEGA);
}
@Override
public long toMebiBytes(long size) {
return size;
}
@Override
public long toGigaBytes(long size) {
return f(size, MEBI, GIGA);
}
@Override
public long toGibiBytes(long size) {
return size / KIBI;
}
@Override
public long toTeraBytes(long size) {
return f(size, MEBI, TERA);
}
@Override
public long toTebiBytes(long size) {
return size / MEBI;
}
},
GIGABYTES("G") {
@Override
public long convert(long sourceSize, MemoryUnit sourceUnit) {
return sourceUnit.toGigaBytes(sourceSize);
}
@Override
public long toBytes(long size) {
return x(size, GIGA, MAX / GIGA);
}
@Override
public long toKiloBytes(long size) {
return x(size, MEGA, MAX / MEGA);
}
@Override
public long toKibiBytes(long size) {
return f(size, GIGA, KIBI);
}
@Override
public long toMegaBytes(long size) {
return x(size, KILO, MAX / KILO);
}
@Override
public long toMebiBytes(long size) {
return f(size, GIGA, MEBI);
}
@Override
public long toGigaBytes(long size) {
return size;
}
@Override
public long toGibiBytes(long size) {
return f(size, GIGA, GIBI);
}
@Override
public long toTeraBytes(long size) {
return size / KILO;
}
@Override
public long toTebiBytes(long size) {
return f(size, GIGA, TEBI);
}
},
GIBIBYTES("Gi") {
@Override
public long convert(long sourceSize, MemoryUnit sourceUnit) {
return sourceUnit.toGibiBytes(sourceSize);
}
@Override
public long toBytes(long size) {
return x(size, GIBI, MAX / GIBI);
}
@Override
public long toKiloBytes(long size) {
return f(size, GIBI, KILO);
}
@Override
public long toKibiBytes(long size) {
return x(size, MEBI, MAX / MEBI);
}
@Override
public long toMegaBytes(long size) {
return f(size, GIBI, MEGA);
}
@Override
public long toMebiBytes(long size) {
return x(size, KIBI, MAX / KIBI);
}
@Override
public long toGigaBytes(long size) {
return f(size, GIBI, GIGA);
}
@Override
public long toGibiBytes(long size) {
return size;
}
@Override
public long toTeraBytes(long size) {
return f(size, GIBI, TERA);
}
@Override
public long toTebiBytes(long size) {
return size / KIBI;
}
},
TERABYTES("T") {
@Override
public long convert(long sourceSize, MemoryUnit sourceUnit) {
return sourceUnit.toTeraBytes(sourceSize);
}
@Override
public long toBytes(long size) {
return x(size, TERA, MAX / TERA);
}
@Override
public long toKiloBytes(long size) {
return x(size, GIGA, MAX / GIGA);
}
@Override
public long toKibiBytes(long size) {
return f(size, TERA, KIBI);
}
@Override
public long toMegaBytes(long size) {
return x(size, MEGA, MAX / MEGA);
}
@Override
public long toMebiBytes(long size) {
return f(size, TERA, MEBI);
}
@Override
public long toGigaBytes(long size) {
return x(size, KILO, MAX / KILO);
}
@Override
public long toGibiBytes(long size) {
return f(size, TERA, GIBI);
}
@Override
public long toTeraBytes(long size) {
return size;
}
@Override
public long toTebiBytes(long size) {
return f(size, TERA, TEBI);
}
},
TEBIBYTES("Ti") {
@Override
public long convert(long sourceSize, MemoryUnit sourceUnit) {
return sourceUnit.toTebiBytes(sourceSize);
}
@Override
public long toBytes(long size) {
return x(size, TEBI, MAX / TEBI);
}
@Override
public long toKiloBytes(long size) {
return f(size, TEBI, KILO);
}
@Override
public long toKibiBytes(long size) {
return x(size, GIBI, MAX / GIBI);
}
@Override
public long toMegaBytes(long size) {
return f(size, TEBI, MEGA);
}
@Override
public long toMebiBytes(long size) {
return x(size, MEBI, MAX / MEBI);
}
@Override
public long toGigaBytes(long size) {
return f(size, TEBI, GIGA);
}
@Override
public long toGibiBytes(long size) {
return x(size, KIBI, MAX / KIBI);
}
@Override
public long toTeraBytes(long size) {
return f(size, TEBI, TERA);
}
@Override
public long toTebiBytes(long size) {
return size;
}
};
private static final long KILO = 1000;
private static final long KIBI = 1024;
private static final long MEGA = KILO * KILO;
private static final long MEBI = KIBI * KIBI;
private static final long GIGA = KILO * MEGA;
private static final long GIBI = KIBI * MEBI;
private static final long TERA = KILO * GIGA;
private static final long TEBI = KIBI * GIBI;
static final long MAX = Long.MAX_VALUE;
private final String suffix;
MemoryUnit(String suffix) {
this.suffix = suffix;
}
public String getSuffix() {
return suffix;
}
static long f(long d, long numerator, long denominator) {
return (long) (((float)d) * ((float)numerator) / (denominator));
}
;
static long x(long d, long m, long over) {
if (d > over)
return Long.MAX_VALUE;
if (d < -over)
return Long.MIN_VALUE;
return d * m;
}
public long convert(long sourceSize, MemoryUnit sourceUnit) {
throw new AbstractMethodError();
}
public long toBytes(long size) {
throw new AbstractMethodError();
}
public long toKiloBytes(long size) {
throw new AbstractMethodError();
}
public long toKibiBytes(long size) {
throw new AbstractMethodError();
}
public long toMegaBytes(long size) {
throw new AbstractMethodError();
}
public long toMebiBytes(long size) {
throw new AbstractMethodError();
}
public long toGigaBytes(long size) {
throw new AbstractMethodError();
}
public long toGibiBytes(long size) {
throw new AbstractMethodError();
}
public long toTeraBytes(long size) {
throw new AbstractMethodError();
}
public long toTebiBytes(long size) {
throw new AbstractMethodError();
}
public static long parseBytes(String s) {
if (s == null)
throw new NullPointerException();
int us = s.length();
while (us > 0 && !Character.isDigit(s.charAt(us - 1))) {
us--;
}
if (us == s.length()) {
return Long.parseLong(s);
}
String suffix = s.substring(us);
for(MemoryUnit u : MemoryUnit.values()) {
if (u.suffix.equals(suffix)) {
long size = Long.parseLong(s.substring(0, us));
return u.toBytes(size);
}
}
throw new IllegalArgumentException(s);
}
}
| 12,344
| 20.102564
| 70
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/EnumUtil.java
|
package org.infinispan.commons.util;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.EnumSet;
/**
* Utilities method to Enums.
*
* @author Pedro Ruivo
* @since 8.2
*/
public class EnumUtil {
private EnumUtil() {
}
public static final long EMPTY_BIT_SET = 0L;
public static <E extends Enum<E>> long bitSetOf(Collection<E> enums) {
if (enums == null || enums.isEmpty()) {
return EMPTY_BIT_SET;
}
long flagBitSet = EMPTY_BIT_SET;
for (Enum<?> f : enums) {
flagBitSet |= bitSetOf(f);
}
return flagBitSet;
}
public static long bitSetOf(Enum<?> first) {
return 1L << first.ordinal();
}
public static long bitSetOf(Enum<?> first, Enum<?> second) {
return bitSetOf(first) | bitSetOf(second);
}
public static long bitSetOf(Enum<?> first, Enum<?> second, Enum<?>... remaining) {
long bitSet = bitSetOf(first, second);
for (Enum<?> f : remaining) {
bitSet |= bitSetOf(f);
}
return bitSet;
}
public static long bitSetOf(Enum<?>[] flags) {
long bitSet = EMPTY_BIT_SET;
for (Enum<?> flag : flags) {
bitSet |= bitSetOf(flag);
}
return bitSet;
}
public static <E extends Enum<E>> EnumSet<E> enumSetOf(long bitSet, Class<E> eClass) {
if (bitSet == EMPTY_BIT_SET) {
return EnumSet.noneOf(eClass);
}
EnumSet<E> flagSet = EnumSet.noneOf(eClass);
for (E f : eClass.getEnumConstants()) {
if (hasEnum(bitSet, f)) {
flagSet.add(f);
}
}
return flagSet;
}
public static boolean hasEnum(long bitSet, Enum<?> anEnum) {
return (bitSet & bitSetOf(anEnum)) != 0;
}
public static long setEnum(long bitSet, Enum<?> anEnum) {
return bitSet | bitSetOf(anEnum);
}
public static <E extends Enum<E>> long setEnums(long bitSet, Collection<E> enums) {
if (enums == null || enums.isEmpty()) {
return bitSet;
}
for (Enum<?> f : enums) {
bitSet |= bitSetOf(f);
}
return bitSet;
}
public static long unsetEnum(long bitSet, Enum<?> anEnum) {
return bitSet & ~bitSetOf(anEnum);
}
public static <E extends Enum<E>> String prettyPrintBitSet(long bitSet, Class<E> eClass) {
return enumSetOf(bitSet, eClass).toString();
}
public static long mergeBitSets(long bitSet1, long bitSet2) {
return bitSet1 | bitSet2;
}
public static long diffBitSets(long bitSet1, long bitSet2) {
return bitSet1 & ~bitSet2;
}
public static boolean containsAll(long bitSet, long testBitSet) {
return (bitSet & testBitSet) == testBitSet;
}
public static boolean containsAny(long bitSet, long testBitSet) {
return (bitSet & testBitSet) != 0;
}
public static int bitSetSize(long bitSet) {
return Long.bitCount(bitSet);
}
public static <E extends Enum<E>> E[] enumArrayOf(long bitSet, Class<E> eClass) {
if (bitSet == EMPTY_BIT_SET) {
return null;
}
E[] array = (E[]) Array.newInstance(eClass, bitSetSize(bitSet));
int i = 0;
for (E f : eClass.getEnumConstants()) {
if (hasEnum(bitSet, f)) {
array[i++] = f;
}
}
return array;
}
}
| 3,309
| 24.658915
| 93
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/SingletonIntSet.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.PrimitiveIterator;
import java.util.Set;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import java.util.stream.IntStream;
/**
* Immutable implementation of IntSet that contains a single value
* @author wburns
* @since 9.3
*/
class SingletonIntSet extends AbstractImmutableIntSet {
final int value;
SingletonIntSet(int value) {
if (value < 0) {
throw new IllegalArgumentException("Value must be 0 or greater");
}
this.value = value;
}
@Override
public boolean contains(int i) {
return value == i;
}
@Override
public boolean containsAll(IntSet set) {
int size = set.size();
return size == 0 || size == 1 && set.contains(value);
}
@Override
public int size() {
return 1;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean contains(Object o) {
return o instanceof Integer && ((Integer) o) == value;
}
@Override
public PrimitiveIterator.OfInt iterator() {
return new SingleIntIterator();
}
@Override
public byte[] toBitSet() {
int offset = (value >>> 3);
byte[] array = new byte[offset + 1];
int lastBitOffset = value > 8 ? value % 8 : value;
// Need to use logical right shift to ensure other bits aren't set
array[offset] = (byte) (0x80 >>> (7 - lastBitOffset));
return array;
}
@Override
public int nextSetBit(int fromIndex) {
return contains(fromIndex) ? fromIndex : -1;
}
private class SingleIntIterator implements PrimitiveIterator.OfInt {
boolean available = true;
@Override
public int nextInt() {
if (!available) {
throw new NoSuchElementException();
}
available = false;
return value;
}
@Override
public boolean hasNext() {
return available;
}
}
@Override
public Object[] toArray() {
Object[] array = new Object[1];
array[0] = value;
return array;
}
@Override
public <T> T[] toArray(T[] a) {
if (!(a instanceof Integer[])) {
throw new IllegalArgumentException("Only Integer arrays are supported");
}
T[] r = (a.length >= 1) ? a :
(T[])java.lang.reflect.Array
.newInstance(a.getClass().getComponentType(), 1);
r[0] = (T) Integer.valueOf(value);
if (r.length > 1) {
r[1] = null;
}
return r;
}
@Override
public int[] toIntArray() {
int[] array = new int[1];
array[0] = value;
return array;
}
@Override
public boolean containsAll(Collection<?> c) {
if (c instanceof IntSet) {
return containsAll((IntSet) c);
}
return c.size() == 1 && c.contains(value);
}
@Override
public IntStream intStream() {
return IntStream.of(value);
}
@Override
public void forEach(IntConsumer action) {
action.accept(value);
}
@Override
public void forEach(Consumer<? super Integer> action) {
if (action instanceof IntConsumer) {
forEach((IntConsumer) action);
}
action.accept(value);
}
@Override
public Spliterator.OfInt intSpliterator() {
return new SingletonSpliterator();
}
@Override
public Spliterator<Integer> spliterator() {
return new SingletonSpliterator();
}
private class SingletonSpliterator implements Spliterator.OfInt {
boolean consumed = false;
@Override
public OfInt trySplit() {
return null;
}
@Override
public long estimateSize() {
return 1;
}
@Override
public int characteristics() {
return SIZED | NONNULL | IMMUTABLE | DISTINCT | ORDERED;
}
@Override
public boolean tryAdvance(IntConsumer action) {
if (!consumed) {
consumed = true;
action.accept(value);
return true;
}
return false;
}
@Override
public Comparator<? super Integer> getComparator() {
return null;
}
}
@Override
public int hashCode() {
return value;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o == null || !(o instanceof Set))
return false;
if (o instanceof IntSet) {
IntSet intSet = (IntSet) o;
return intSet.size() == 1 && intSet.contains(value);
} else {
Set set = (Set) o;
return set.size() == 1 && set.contains(value);
}
}
@Override
public String toString() {
return "{" + value + "}";
}
}
| 4,886
| 21.315068
| 81
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/FastCopyHashMap.java
|
package org.infinispan.commons.util;
import java.io.IOException;
import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* A HashMap that is optimized for fast shallow copies.
* <p/>
* Null keys are <i>not</i> supported.
*
* @author Jason T. Greene
* @since 4.0
*/
public class FastCopyHashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable {
private static final Log log = LogFactory.getLog(FastCopyHashMap.class);
/**
* Serialization ID
*/
private static final long serialVersionUID = 10929568968762L;
/**
* Same default as HashMap, must be a power of 2
*/
private static final int DEFAULT_CAPACITY = 8;
/**
* MAX_INT - 1
*/
private static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 67%, just like IdentityHashMap
*/
private static final float DEFAULT_LOAD_FACTOR = 0.67f;
/**
* The open-addressed table
*/
private transient Entry<K, V>[] table;
/**
* The current number of key-value pairs
*/
private transient int size;
/**
* The next resize
*/
private transient int threshold;
/**
* The user defined load factor which defines when to resize
*/
private final float loadFactor;
/**
* Counter used to detect changes made outside of an iterator
*/
private transient int modCount;
public FastCopyHashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Can not have a negative size table!");
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (!(loadFactor > 0F && loadFactor <= 1F))
throw new IllegalArgumentException("Load factor must be greater than 0 and less than or equal to 1");
this.loadFactor = loadFactor;
init(initialCapacity, loadFactor);
}
@SuppressWarnings("unchecked")
public FastCopyHashMap(Map<? extends K, ? extends V> map) {
if (map instanceof FastCopyHashMap) {
FastCopyHashMap<? extends K, ? extends V> fast = (FastCopyHashMap<? extends K, ? extends V>) map;
this.table = (Entry<K, V>[]) fast.table.clone();
this.loadFactor = fast.loadFactor;
this.size = fast.size;
this.threshold = fast.threshold;
} else {
this.loadFactor = DEFAULT_LOAD_FACTOR;
init(map.size(), this.loadFactor);
putAll(map);
}
}
@SuppressWarnings("unchecked")
private void init(int initialCapacity, float loadFactor) {
int c = 1;
while (c < initialCapacity) c <<= 1;
this.table = new Entry[c];
threshold = (int) (c * loadFactor);
}
public FastCopyHashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public FastCopyHashMap() {
this(DEFAULT_CAPACITY);
}
private int nextIndex(int index, int length) {
index = (index >= length - 1) ? 0 : index + 1;
return index;
}
private static int index(int hashCode, int length) {
return hashCode & (length - 1);
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public V get(Object key) {
assertKeyNotNull(key);
int hash = hash(key);
int length = table.length;
int index = index(hash, length);
for (; ;) {
Entry<K, V> e = table[index];
if (e == null)
return null;
if (e.hash == hash && eq(key, e.key))
return e.value;
index = nextIndex(index, length);
}
}
@Override
public boolean containsKey(Object key) {
assertKeyNotNull(key);
int hash = hash(key);
int length = table.length;
int index = index(hash, length);
for (; ;) {
Entry<K, V> e = table[index];
if (e == null)
return false;
if (e.hash == hash && eq(key, e.key))
return true;
index = nextIndex(index, length);
}
}
/**
* Returns a string representation of this map. The string representation
* consists of a list of key-value mappings in the order returned by the
* map's <tt>entrySet</tt> view's iterator, enclosed in braces
* (<tt>"{}"</tt>). Adjacent mappings are separated by the characters
* <tt>", "</tt> (comma and space). Each key-value mapping is rendered as
* the key followed by an equals sign (<tt>"="</tt>) followed by the
* associated value. Keys and values are converted to strings as by
* {@link String#valueOf(Object)}.
*
* @return a string representation of this map
*/
public String toString() {
Iterator<java.util.Map.Entry<K, V>> i = entrySet().iterator();
if (! i.hasNext())
return "{}";
StringBuilder sb = new StringBuilder();
sb.append('{');
for (;;) {
java.util.Map.Entry<K, V> e = i.next();
K key = e.getKey();
V value = e.getValue();
sb.append(key == this ? "(this Map)" : key);
sb.append('=');
sb.append(value == this ? "(this Map)" : value);
if (! i.hasNext())
return sb.append('}').toString();
sb.append(", ");
}
}
@Override
public boolean containsValue(Object value) {
for (Entry<K, V> e : table)
if (e != null && eq(value, e.value))
return true;
return false;
}
@Override
public V put(K key, V value) {
assertKeyNotNull(key);
Entry<K, V>[] table = this.table;
int hash = hash(key);
int length = table.length;
int start = index(hash, length);
int index = start;
for (; ;) {
Entry<K, V> e = table[index];
if (e == null)
break;
if (e.hash == hash && eq(key, e.key)) {
table[index] = new Entry<K, V>(e.key, e.hash, value);
return e.value;
}
index = nextIndex(index, length);
if (index == start)
throw new IllegalStateException("Table is full!");
}
modCount++;
table[index] = new Entry<K, V>(key, hash, value);
if (++size >= threshold)
resize(length);
return null;
}
@SuppressWarnings("unchecked")
private void resize(int from) {
int newLength = from << 1;
// Can't get any bigger
if (newLength > MAXIMUM_CAPACITY || newLength <= from)
return;
Entry<K, V>[] newTable = new Entry[newLength];
Entry<K, V>[] old = table;
for (Entry<K, V> e : old) {
if (e == null)
continue;
int index = index(e.hash, newLength);
while (newTable[index] != null)
index = nextIndex(index, newLength);
newTable[index] = e;
}
threshold = (int) (loadFactor * newLength);
table = newTable;
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
int size = map.size();
if (size == 0)
return;
if (size > threshold) {
if (size > MAXIMUM_CAPACITY)
size = MAXIMUM_CAPACITY;
int length = table.length;
while (length < size) length <<= 1;
resize(length);
}
for (Map.Entry<? extends K, ? extends V> e : map.entrySet())
put(e.getKey(), e.getValue());
}
@Override
public V remove(Object key) {
assertKeyNotNull(key);
Entry<K, V>[] table = this.table;
int length = table.length;
int hash = hash(key);
int start = index(hash, length);
for (int index = start; ;) {
Entry<K, V> e = table[index];
if (e == null)
return null;
if (e.hash == hash && eq(key, e.key)) {
table[index] = null;
relocate(index);
modCount++;
size--;
return e.value;
}
index = nextIndex(index, length);
if (index == start)
return null;
}
}
private void relocate(int start) {
Entry<K, V>[] table = this.table;
int length = table.length;
int current = nextIndex(start, length);
for (; ;) {
Entry<K, V> e = table[current];
if (e == null)
return;
// A Doug Lea variant of Knuth's Section 6.4 Algorithm R.
// This provides a non-recursive method of relocating
// entries to their optimal positions once a gap is created.
int prefer = index(e.hash, length);
if ((current < prefer && (prefer <= start || start <= current))
|| (prefer <= start && start <= current)) {
table[start] = e;
table[current] = null;
start = current;
}
current = nextIndex(current, length);
}
}
@Override
public void clear() {
modCount++;
Entry<K, V>[] table = this.table;
for (int i = 0; i < table.length; i++)
table[i] = null;
size = 0;
}
@Override
@SuppressWarnings("unchecked")
public FastCopyHashMap<K, V> clone() {
try {
FastCopyHashMap<K, V> clone = (FastCopyHashMap<K, V>) super.clone();
clone.table = table.clone();
clone.entrySet = null;
clone.values = null;
clone.keySet = null;
return clone;
}
catch (CloneNotSupportedException e) {
// should never happen
throw new IllegalStateException(e);
}
}
public void printDebugStats() {
int optimal = 0;
int total = 0;
int totalSkew = 0;
int maxSkew = 0;
for (int i = 0; i < table.length; i++) {
Entry<K, V> e = table[i];
if (e != null) {
total++;
int target = index(e.hash, table.length);
if (i == target)
optimal++;
else {
int skew = Math.abs(i - target);
if (skew > maxSkew) maxSkew = skew;
totalSkew += skew;
}
}
}
System.out.println(" Size: " + size);
System.out.println(" Real Size: " + total);
System.out.println(" Optimal: " + optimal + " (" + (float) optimal * 100 / total + "%)");
System.out.println(" Average Distnce: " + ((float) totalSkew / (total - optimal)));
System.out.println(" Max Distance: " + maxSkew);
}
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
int size = s.readInt();
init(size, loadFactor);
for (int i = 0; i < size; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
putForCreate(key, value);
}
}
@SuppressWarnings("unchecked")
private void putForCreate(K key, V value) {
Entry<K, V>[] table = this.table;
int hash = hash(key);
int length = table.length;
int index = index(hash, length);
Entry<K, V> e = table[index];
while (e != null) {
index = nextIndex(index, length);
e = table[index];
}
table[index] = new Entry<K, V>(key, hash, value);
}
private void writeObject(java.io.ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeInt(size);
for (Entry<K, V> e : table) {
if (e != null) {
s.writeObject(e.key);
s.writeObject(e.value);
}
}
}
private abstract class FasyCopyHashMapIterator<E> implements Iterator<E> {
private int next = 0;
private int expectedCount = modCount;
private int current = -1;
private boolean hasNext;
Entry<K, V> table[] = FastCopyHashMap.this.table;
@Override
public boolean hasNext() {
if (hasNext)
return true;
Entry<K, V> table[] = this.table;
for (int i = next; i < table.length; i++) {
if (table[i] != null) {
next = i;
return hasNext = true;
}
}
next = table.length;
return false;
}
protected Entry<K, V> nextEntry() {
if (modCount != expectedCount)
throw new ConcurrentModificationException();
if (!hasNext && !hasNext())
throw new NoSuchElementException();
current = next++;
hasNext = false;
return table[current];
}
@Override
@SuppressWarnings("unchecked")
public void remove() {
if (modCount != expectedCount)
throw new ConcurrentModificationException();
int current = this.current;
int delete = current;
if (current == -1)
throw new IllegalStateException();
// Invalidate current (prevents multiple remove)
this.current = -1;
// Start were we relocate
next = delete;
Entry<K, V>[] table = this.table;
if (table != FastCopyHashMap.this.table) {
FastCopyHashMap.this.remove(table[delete].key);
table[delete] = null;
expectedCount = modCount;
return;
}
int length = table.length;
int i = delete;
table[delete] = null;
size--;
for (; ;) {
i = nextIndex(i, length);
Entry<K, V> e = table[i];
if (e == null)
break;
int prefer = index(e.hash, length);
if ((i < prefer && (prefer <= delete || delete <= i))
|| (prefer <= delete && delete <= i)) {
// Snapshot the unseen portion of the table if we have
// to relocate an entry that was already seen by this iterator
if (i < current && current <= delete && table == FastCopyHashMap.this.table) {
int remaining = length - current;
Entry<K, V>[] newTable = new Entry[remaining];
System.arraycopy(table, current, newTable, 0, remaining);
// Replace iterator's table.
// Leave table local var pointing to the real table
this.table = newTable;
next = 0;
}
// Do the swap on the real table
table[delete] = e;
table[i] = null;
delete = i;
}
}
}
}
private class KeyIterator extends FasyCopyHashMapIterator<K> {
@Override
public K next() {
return nextEntry().key;
}
}
private class ValueIterator extends FasyCopyHashMapIterator<V> {
@Override
public V next() {
return nextEntry().value;
}
}
private class EntryIterator extends FasyCopyHashMapIterator<Map.Entry<K, V>> {
private class WriteThroughEntry extends AbstractMap.SimpleEntry<K, V> {
WriteThroughEntry(K key, V value) {
super(key, value);
}
@Override
public V setValue(V value) {
if (table != FastCopyHashMap.this.table)
FastCopyHashMap.this.put(getKey(), value);
return super.setValue(value);
}
}
@Override
public Map.Entry<K, V> next() {
Entry<K, V> e = nextEntry();
return new WriteThroughEntry(e.key, e.value);
}
}
@Override
public Collection<V> values() {
if (values == null) values = new Values();
return values;
}
public final class Values extends AbstractCollection<V> {
@Override
public Iterator<V> iterator() {
return new ValueIterator();
}
@Override
public int size() {
return FastCopyHashMap.this.size();
}
@Override
public boolean contains(Object o) {
return containsValue(o);
}
@Override
public void clear() {
FastCopyHashMap.this.clear();
}
}
@Override
public Set<K> keySet() {
if (keySet == null) keySet = new KeySet();
return keySet;
}
public class KeySet extends AbstractSet<K> {
@Override
public Iterator<K> iterator() {
return new KeyIterator();
}
@Override
public void clear() {
FastCopyHashMap.this.clear();
}
@Override
public boolean contains(Object o) {
return containsKey(o);
}
@Override
public boolean remove(Object o) {
int size = size();
FastCopyHashMap.this.remove(o);
return size() < size;
}
@Override
public int size() {
return FastCopyHashMap.this.size();
}
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
if (entrySet == null) entrySet = new EntrySet();
return entrySet;
}
public class EntrySet extends AbstractSet<Map.Entry<K, V>> {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new EntryIterator();
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
Object value = get(entry.getKey());
return eq(entry.getValue(), value);
}
@Override
public void clear() {
FastCopyHashMap.this.clear();
}
@Override
public boolean isEmpty() {
return FastCopyHashMap.this.isEmpty();
}
@Override
public int size() {
return FastCopyHashMap.this.size();
}
}
private static final class Entry<K, V> {
final K key;
final int hash;
final V value;
Entry(K key, int hash, V value) {
this.key = key;
this.hash = hash;
this.value = value;
}
}
}
| 18,196
| 24.921652
| 110
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ImmutableListCopy.java
|
package org.infinispan.commons.util;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.Set;
import org.infinispan.commons.marshall.AdvancedExternalizer;
import org.infinispan.commons.marshall.Ids;
import org.infinispan.commons.marshall.MarshallUtil;
import net.jcip.annotations.Immutable;
/**
* A lightweight, read-only copy of a List. Typically used in place of the common idiom: <code> return
* Collections.unmodifiableList(new ArrayList( myInternalList )); </code>
* <p/>
* a it is far more efficient than making a defensive copy and then wrapping the defensive copy in a read-only wrapper.
* <p/>
* Also used whenever a read-only reference List is needed.
* <p/>
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @since 4.0
*/
@Immutable
public class ImmutableListCopy<E> extends AbstractList<E> implements Immutables.Immutable {
public static final Object[] EMPTY_ARRAY = new Object[0];
private final Object[] elements;
/**
* Constructs an empty ImmutableListCopy.
*/
public ImmutableListCopy() {
elements = EMPTY_ARRAY;
}
/**
* Only one copy constructor since the list is immutable.
*
* @param c collection to copy from
*/
@SuppressWarnings("unchecked")
public ImmutableListCopy(Collection<? extends E> c) {
if (c instanceof ImmutableListCopy) {
elements = ((ImmutableListCopy<? extends E>) c).elements;
} else {
elements = c.toArray();
}
}
/**
* Assumes that the array passed in is "safe", i.e., is not referenced from elsewhere. Use with care!
*
* @param array to reference
*/
public ImmutableListCopy(E[] array) {
elements = array;
}
/**
* Utility constructors to allow combining collections
*
* @param collection1 collection to copy from
* @param collection2 collection to copy from
*/
@SuppressWarnings("unchecked")
public ImmutableListCopy(Collection<? extends E> collection1, Collection<? extends E> collection2) {
if (collection2.isEmpty()) {
if (collection1 instanceof ImmutableListCopy) {
elements = ((ImmutableListCopy<? extends E>) collection1).elements;
} else {
elements = collection1.toArray();
}
} else if (collection1.isEmpty()) {
if (collection2 instanceof ImmutableListCopy) {
elements = ((ImmutableListCopy<? extends E>) collection2).elements;
} else {
elements = collection2.toArray();
}
} else {
int c1Size = collection1.size();
int c2Size = collection2.size();
int size = c1Size + c2Size;
elements = new Object[size]; // no room for growth;
collection1.toArray(elements);
Object[] c2 = collection2.toArray();
System.arraycopy(c2, 0, elements, c1Size, c2Size);
}
}
@Override
public final int size() {
return elements.length;
}
@Override
public final boolean isEmpty() {
return elements.length == 0;
}
@Override
public final boolean contains(Object o) {
return indexOf(o) >= 0;
}
@Override
public final Iterator<E> iterator() {
return new ImmutableIterator();
}
@Override
public final Object[] toArray() {
return Arrays.copyOf(elements, elements.length);
}
@Override
@SuppressWarnings("unchecked")
public final <T> T[] toArray(T[] a) {
int size = elements.length;
if (a.length < size) {
return (T[]) Arrays.copyOf(elements, size, a.getClass());
}
System.arraycopy(elements, 0, a, 0, size);
if (a.length > size) {
a[size] = null;
}
return a;
}
@Override
public final boolean add(E o) {
throw new UnsupportedOperationException();
}
@Override
public final boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public final boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public final boolean addAll(int index, Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public final boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public final boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@SuppressWarnings("unchecked")
@Override
public final E get(int index) {
return (E) elements[index];
}
@Override
public final int indexOf(Object o) {
int size = elements.length;
if (o == null) {
for (int i = 0; i < size; i++) {
if (elements[i] == null) return i;
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(elements[i])) return i;
}
}
return -1;
}
@Override
public final int lastIndexOf(Object o) {
int size = elements.length;
if (o == null) {
for (int i = size - 1; i >= 0; i--) {
if (elements[i] == null) return i;
}
} else {
for (int i = size - 1; i >= 0; i--) {
if (o.equals(elements[i])) return i;
}
}
return -1;
}
@Override
public final ListIterator<E> listIterator() {
return new ImmutableIterator();
}
@Override
public final ListIterator<E> listIterator(int index) {
return new ImmutableIterator(index);
}
@Override
public final List<E> subList(int fromIndex, int toIndex) {
return new ImmutableSubList(fromIndex, toIndex);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImmutableListCopy))
return super.equals(o);
ImmutableListCopy<?> that = (ImmutableListCopy<?>) o;
return Arrays.equals(elements, that.elements);
}
@Override
public int hashCode() {
return Arrays.hashCode(elements);
}
@SuppressWarnings("rawtypes")
public static class Externalizer implements AdvancedExternalizer<ImmutableListCopy> {
@Override
public Integer getId() {
return Ids.IMMUTABLE_LIST_COPY;
}
@Override
public Set<Class<? extends ImmutableListCopy>> getTypeClasses() {
return Util.asSet(ImmutableListCopy.class);
}
@Override
public void writeObject(ObjectOutput output, ImmutableListCopy object) throws IOException {
MarshallUtil.marshallArray(object.elements, output);
}
@Override
public ImmutableListCopy readObject(ObjectInput input) throws IOException, ClassNotFoundException {
Object[] elements = MarshallUtil.unmarshallArray(input, Util::objectArray);
return new ImmutableListCopy<>(elements);
}
}
private class ImmutableIterator implements ListIterator<E> {
int cursor = 0;
ImmutableIterator(int index) {
if (index < 0 || index > size()) throw new IndexOutOfBoundsException("Index: " + index);
cursor = index;
}
ImmutableIterator() {
}
@Override
public boolean hasNext() {
return cursor != elements.length;
}
@Override
public E next() {
try {
return get(cursor++);
}
catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasPrevious() {
return cursor != 0;
}
@Override
public E previous() {
try {
return get(--cursor);
}
catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException();
}
}
@Override
public int nextIndex() {
return cursor;
}
@Override
public int previousIndex() {
return cursor - 1;
}
@Override
public void set(E o) {
throw new UnsupportedOperationException();
}
@Override
public void add(E o) {
throw new UnsupportedOperationException();
}
}
public class ImmutableSubList extends AbstractList<E> {
private final int offset;
private final int size;
ImmutableSubList(int fromIndex, int toIndex) {
int size = ImmutableListCopy.this.elements.length;
if (fromIndex < 0 || toIndex > size || fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex + "), toIndex(" + toIndex + "), size (" + size + "), List=" + ImmutableListCopy.this.toString());
offset = fromIndex;
this.size = toIndex - fromIndex;
}
@Override
public final E get(int index) {
if (index < 0 || index >= size) throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
return ImmutableListCopy.this.get(index + offset);
}
@Override
public final int size() {
return size;
}
@Override
protected final void removeRange(int fromIndex, int toIndex) {
throw new UnsupportedOperationException();
}
@Override
public final boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public final boolean addAll(int index, Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public final Iterator<E> iterator() {
return super.listIterator();
}
@Override
public final ListIterator<E> listIterator(final int index) {
if (index < 0 || (index != 0 && index >= size))
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
return new ListIterator<E>() {
private final ListIterator<?> i = ImmutableListCopy.this.listIterator(index + offset);
@Override
public boolean hasNext() {
return nextIndex() < size;
}
@Override
@SuppressWarnings("unchecked")
public E next() {
if (hasNext())
return (E) i.next();
else
throw new NoSuchElementException();
}
@Override
public boolean hasPrevious() {
return previousIndex() >= 0;
}
@Override
@SuppressWarnings("unchecked")
public E previous() {
if (hasPrevious())
return (E) i.previous();
else
throw new NoSuchElementException();
}
@Override
public int nextIndex() {
return i.nextIndex() - offset;
}
@Override
public int previousIndex() {
return i.previousIndex() - offset;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void set(E o) {
throw new UnsupportedOperationException();
}
@Override
public void add(E o) {
throw new UnsupportedOperationException();
}
};
}
@Override
public final List<E> subList(int fromIndex, int toIndex) {
return new ImmutableSubList(offset + fromIndex, offset + toIndex);
}
}
}
| 11,914
| 25.835586
| 169
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ConcatIterator.java
|
package org.infinispan.commons.util;
import java.util.Iterator;
/**
* Iterator that concatenates a bunch of iterables into 1 big iterator. Each iterable is retrieved lazily as requested.
* Note that if any of the produced iterators from the iterable implement {@link CloseableIterator} they will be closed
* when iterated upon fully or the last used iterator will be close when this iterator this closed.
* <p>
* Removal is implemented and will invoke remove on the last used iterator
* @author wburns
* @since 9.3
*/
public class ConcatIterator<E> extends AbstractIterator<E> implements CloseableIterator<E> {
private final Iterator<? extends Iterable<E>> iterables;
private Iterator<E> currentIterator;
public ConcatIterator(Iterable<? extends Iterable<E>> iterableIterables) {
this.iterables = iterableIterables.iterator();
if (iterables.hasNext()) {
// Always initialize current iterator
currentIterator = iterables.next().iterator();
}
}
@Override
protected E getNext() {
E next = null;
if (currentIterator != null) {
while (next == null) {
if (currentIterator.hasNext()) {
next = currentIterator.next();
} else {
closeIterator(currentIterator);
if (iterables.hasNext()) {
currentIterator = iterables.next().iterator();
} else {
// None more left
currentIterator = null;
break;
}
}
}
}
return next;
}
@Override
public void close() {
closeIterator(currentIterator);
}
@Override
public void remove() {
if (currentIterator != null) {
currentIterator.remove();
}
}
private static void closeIterator(Iterator<?> iter) {
if (iter instanceof CloseableIterator) {
((CloseableIterator) iter).close();
}
}
}
| 1,973
| 28.462687
| 119
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/AbstractDelegatingConcurrentMap.java
|
package org.infinispan.commons.util;
import java.util.concurrent.ConcurrentMap;
public abstract class AbstractDelegatingConcurrentMap<K, V> extends AbstractDelegatingMap<K, V> implements ConcurrentMap<K, V> {
protected abstract ConcurrentMap<K, V> delegate();
}
| 268
| 28.888889
| 128
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/CloseableIteratorCollectionAdapter.java
|
package org.infinispan.commons.util;
import java.util.Collection;
/**
* Adapts {@link java.util.Collection} to {@link CloseableIteratorCollection}
*
* @author Radim Vansa <rvansa@redhat.com>
*/
public class CloseableIteratorCollectionAdapter<E> implements CloseableIteratorCollection<E> {
protected final Collection<E> delegate;
public CloseableIteratorCollectionAdapter(Collection<E> delegate) {
this.delegate = delegate;
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public boolean contains(Object o) {
return delegate.contains(o);
}
@Override
public CloseableIterator<E> iterator() {
return Closeables.iterator(delegate.iterator());
}
@Override
public CloseableSpliterator<E> spliterator() {
return Closeables.spliterator(delegate.spliterator());
}
@Override
public Object[] toArray() {
return delegate.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return delegate.toArray(a);
}
@Override
public boolean add(E e) {
return delegate.add(e);
}
@Override
public boolean remove(Object o) {
return delegate.remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return delegate.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
return delegate.addAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return delegate.retainAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return delegate.removeAll(c);
}
@Override
public void clear() {
delegate.clear();
}
}
| 1,772
| 19.37931
| 94
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/GlobUtils.java
|
package org.infinispan.commons.util;
/**
* Utility functions for globs
*
* @author Tristan Tarrant
* @since 9.2
*/
public final class GlobUtils {
public static boolean isGlob(String s) {
if (s == null) {
return false;
}
for(int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '*' || ch == '?') {
return true;
}
}
return false;
}
public static String globToRegex(String glob) {
StringBuilder s = new StringBuilder();
for(int i = 0; i < glob.length(); i++) {
final char c = glob.charAt(i);
switch(c) {
case '*':
s.append(".*");
break;
case '?':
s.append('.');
break;
case '.':
s.append("\\.");
break;
case '\\':
s.append("\\\\");
break;
default:
s.append(c);
}
}
return s.toString();
}
}
| 1,047
| 19.96
| 50
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/InfinispanCollections.java
|
package org.infinispan.commons.util;
import static java.util.Collections.singletonMap;
import static java.util.Collections.unmodifiableMap;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Static helpers for Infinispan-specific collections
*
* @author Manik Surtani
* @since 4.0
*/
public final class InfinispanCollections {
private InfinispanCollections() {
// ensuring non-instantiability
}
/**
* A function that converts a type into another one.
*
* @param <E> Input type.
* @param <T> Output type.
*/
public interface Function<E, T> {
/**
* Transforms an instance of the given input into an instace of the
* type to be returned.
*
* @param input Instance of the input type.
* @return Instance of the output type.
*/
T transform(E input);
}
/**
* A function that converts an entry into a key/value pair for use in a map.
* @param <K> generated key
* @param <V> generated value
* @param <E> entry input
*/
public interface MapMakerFunction<K, V, E> {
/**
* Transforms the given input into a key/value pair for use in a map
* @param input instance of the input type
* @return a Map.Entry parameterized with K and V
*/
Map.Entry<K, V> transform(E input);
}
/**
* Given a map of well known key/value types, it makes a shallow copy of it
* while at the same time transforming it's value type to a desired output
* type. The transformation of the value type is done using a given a
* function.
*
* @param input contains the input key/value pair map
* @param f function instance to use to transform the value part of the map
* @param <K> input map's key type
* @param <V> desired output type of the map's value
* @param <E> input map's value type
* @return a shallow copy of the input Map with all its values transformed.
*/
public static <K, V, E> Map<K, V> transformMapValue(Map<K, E> input, Function<E, V> f) {
// This screams for a map function! Gimme functional programming pleasee...
if (input.isEmpty()) return Collections.emptyMap();
if (input.size() == 1) {
Map.Entry<K, E> single = input.entrySet().iterator().next();
return singletonMap(single.getKey(), f.transform(single.getValue()));
} else {
Map<K, V> copy = new HashMap<>(input.size());
for (Map.Entry<K, E> entry : input.entrySet())
copy.put(entry.getKey(), f.transform(entry.getValue()));
return unmodifiableMap(copy);
}
}
/**
* Given a collection, transforms the collection to a map given a {@link MapMakerFunction}
*
* @param input contains a collection of type E
* @param f MapMakerFunction instance to use to transform the collection to a key/value pair
* @param <K> output map's key type
* @param <V> output type of the map's value
* @param <E> input collection's entry type
* @return a Map with keys and values generated from the input collection
*/
public static <K, V, E> Map<K, V> transformCollectionToMap(Collection<? extends E> input, MapMakerFunction<K, V, ? super E> f) {
// This screams for a map function! Gimme functional programming pleasee...
if (input.isEmpty()) return Collections.emptyMap();
if (input.size() == 1) {
E single = input.iterator().next();
Map.Entry<K, V> entry = f.transform(single);
return singletonMap(entry.getKey(), entry.getValue());
} else {
Map<K, V> map = new HashMap<>(input.size());
for (E e : input) {
Map.Entry<K, V> entry = f.transform(e);
map.put(entry.getKey(), entry.getValue());
}
return unmodifiableMap(map);
}
}
/**
* Returns the elements that are present in s1 but which are not present
* in s2, without changing the contents of neither s1, nor s2.
*
* @param s1 first set
* @param s2 second set
* @param <E> type of objects in Set
* @return the elements in s1 that are not in s2
*/
public static <E> Set<E> difference(Set<? extends E> s1, Set<? extends E> s2) {
Set<E> copy1 = new HashSet<>(s1);
copy1.removeAll(new HashSet<>(s2));
return copy1;
}
public static <T> boolean containsAny(Collection<T> haystack, Collection<T> needles) {
for (T element : needles) {
if (haystack.contains(element))
return true;
}
return false;
}
public static <T> void forEach(T[] array, Consumer<T> consumer) {
final int size = Objects.requireNonNull(array, "Array must be non-null.").length;
for (int i = 0; i < size; ++i) {
consumer.accept(array[i]);
}
}
public static void assertNotNullEntries(Map<?, ?> map, String name) {
Objects.requireNonNull(map, () -> "Map '" + name + "' must be non null.");
Supplier<String> keySupplier = () -> "Map '" + name + "' contains null key.";
Supplier<String> valueSupplier = () -> "Map '" + name + "' contains null value.";
map.forEach((k, v) -> {
Objects.requireNonNull(k, keySupplier);
Objects.requireNonNull(v, valueSupplier);
});
}
public static void assertNotNullEntries(Collection<?> collection, String name) {
Objects.requireNonNull(collection, () -> "Collection '" + name + "' must be non null.");
Supplier<String> entrySupplier = () -> "Collection '" + name + "' contains null entry.";
collection.forEach(k -> Objects.requireNonNull(k, entrySupplier));
}
public static <K, V> Map<K, V> mergeMaps(Map<K, V> one, Map<K, V> second) {
if (one == null) {
return second;
} else if (second == null) {
return one;
} else {
one.putAll(second);
return one;
}
}
public static <T> List<T> mergeLists(List<T> one, List<T> second) {
if (one == null) {
return second;
} else if (second == null) {
return one;
} else {
one.addAll(second);
return one;
}
}
public static Set<Object> toObjectSet(Collection<?> collection) {
//noinspection unchecked
return collection instanceof Set ?
(Set<Object>) collection :
new HashSet<>(collection);
}
}
| 6,585
| 33.481675
| 131
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/AbstractIterator.java
|
package org.infinispan.commons.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
/**
* Abstract iterator that allows overriding just the {@link AbstractIterator#getNext()} method to implement it.
* This iterator works on the premise that a null value returned from {@link AbstractIterator#getNext()} means
* that this iterator is complete.
* Note this iterator does not implement {@link Iterator#remove()} and is up to implementors to do so.
* @author wburns
* @since 9.2
*/
public abstract class AbstractIterator<E> implements Iterator<E> {
E next;
/**
* Method to implement to provide an iterator implementation. When this method returns null, the iterator is complete.
* @return the next value for the iterator to return or null for it to be complete.
*/
protected abstract E getNext();
@Override
public boolean hasNext() {
return next != null || (next = getNext()) != null;
}
@Override
public E next() {
if (hasNext()) {
E returnValue = next;
next = null;
return returnValue;
}
throw new NoSuchElementException();
}
@Override
public void forEachRemaining(Consumer<? super E> action) {
if (next != null) {
action.accept(next);
}
E next;
while ((next = getNext()) != null) {
action.accept(next);
}
}
}
| 1,424
| 27.5
| 121
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/FileLookupFactory.java
|
package org.infinispan.commons.util;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
public class FileLookupFactory {
public static FileLookup newInstance() {
return new DefaultFileLookup();
}
public static class DefaultFileLookup extends AbstractFileLookup implements FileLookup {
protected DefaultFileLookup() {
}
@Override
protected InputStream getAsInputStreamFromClassLoader(String filename, ClassLoader appClassLoader) {
for (ClassLoader cl : Util.getClassLoaders(appClassLoader)) {
if (cl == null)
continue;
try {
InputStream is = cl.getResourceAsStream(filename);
if (is != null) {
return is;
}
} catch (RuntimeException e) {
// Ignore this as the classloader may throw exceptions for a valid path on Windows
}
}
return null;
}
@Override
protected URL getAsURLFromClassLoader(String filename, ClassLoader userClassLoader) {
for (ClassLoader cl : Util.getClassLoaders(userClassLoader)) {
if (cl == null)
continue;
try {
URL url = cl.getResource(filename);
if (url != null) {
return url;
}
} catch (RuntimeException e) {
// Ignore this as the classloader may throw exceptions for a valid path on Windows
}
}
return null;
}
@Override
protected Collection<URL> getAsURLsFromClassLoader(String filename, ClassLoader userClassLoader) throws IOException {
Collection<URL> urls = new HashSet<URL>(4);
for (ClassLoader cl : Util.getClassLoaders(userClassLoader)) {
if (cl == null)
continue;
try {
urls.addAll(new EnumerationList<URL>(cl.getResources(filename)));
} catch (RuntimeException e) {
// Ignore this as the classloader may throw exceptions for a valid path on Windows
}
}
return urls;
}
}
}
| 2,244
| 30.619718
| 123
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ImmutableHopscotchHashSet.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* Wrap a {@link HopscotchHashMap} and allow using it as a {@link Set}.
*
* @param <E> The element type
* @since 9.3
* @author Dan Berindei
*/
public class ImmutableHopscotchHashSet<E> implements Set<E> {
private static final Object PRESENT = new Object();
private final HopscotchHashMap<E, Object> map;
public ImmutableHopscotchHashSet(Collection<E> collection) {
map = new HopscotchHashMap<>(collection.size());
for (E e : collection) {
map.put(e, PRESENT);
}
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public boolean contains(Object o) {
return map.containsKey(o);
}
@Override
public Iterator<E> iterator() {
return new Immutables.ImmutableIteratorWrapper<>(map.keySet().iterator());
}
@Override
public void forEach(Consumer<? super E> action) {
map.keySet().forEach(action);
}
@Override
public Object[] toArray() {
return map.keySet().toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return map.keySet().toArray(a);
}
@Override
public boolean add(E e) {
throw new UnsupportedOperationException("add");
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("remove");
}
@Override
public boolean containsAll(Collection<?> c) {
return map.keySet().containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException("addAll");
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException("retainAll");
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException("removeAll");
}
@Override
public boolean removeIf(Predicate<? super E> filter) {
throw new UnsupportedOperationException("removeIf");
}
@Override
public void clear() {
throw new UnsupportedOperationException("clear");
}
// Use the default implementation of spliterator(), stream(), and parallelStream()
}
| 2,393
| 21.8
| 85
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/StringPropertyReplacer.java
|
package org.infinispan.commons.util;
import java.io.File;
import java.util.Map;
import java.util.Properties;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* A utility class for replacing properties in strings.
*
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
* @author <a href="Scott.Stark@jboss.org">Scott Stark</a>
* @author <a href="claudio.vesco@previnet.it">Claudio Vesco</a>
* @author <a href="mailto:adrian@jboss.com">Adrian Brock</a>
* @author <a href="mailto:dimitris@jboss.org">Dimitris Andreadis</a>
* @since 4.2
*/
public class StringPropertyReplacer {
private static final Log log = LogFactory.getLog(StringPropertyReplacer.class);
/**
* New line string constant
*/
public static final String NEWLINE = System.getProperty("line.separator", "\n");
/**
* File separator value
*/
private static final String FILE_SEPARATOR = File.separator;
/**
* Path separator value
*/
private static final String PATH_SEPARATOR = File.pathSeparator;
/**
* File separator alias
*/
private static final String FILE_SEPARATOR_ALIAS = "/";
/**
* Path separator alias
*/
private static final String PATH_SEPARATOR_ALIAS = ":";
// States used in property parsing
private static final int NORMAL = 0;
private static final int SEEN_DOLLAR = 1;
private static final int IN_BRACKET = 2;
/**
* Go through the input string and replace any occurance of ${p} with the
* System.getProperty(p) value. If there is no such property p defined, then
* the ${p} reference will remain unchanged.
* <p/>
* If the property reference is of the form ${p:v} and there is no such
* property p, then the default value v will be returned.
* <p/>
* If the property reference is of the form ${p1,p2} or ${p1,p2:v} then the
* primary and the secondary properties will be tried in turn, before
* returning either the unchanged input, or the default value.
* <p/>
* The property ${/} is replaced with System.getProperty("file.separator")
* value and the property ${:} is replaced with System.getProperty("path.separator").
* <p/>
* Environment variables are referenced by the <code>env.</code> prefix, for example ${env.PATH}
*
* @param string - the string with possible ${} references
* @return the input string with all property references replaced if any. If
* there are no valid references the input string will be returned.
*/
public static String replaceProperties(final String string) {
return replaceProperties(string, null);
}
/**
* Go through the input string and replace any occurance of ${p} with the
* props.getProperty(p) value. If there is no such property p defined, then
* the ${p} reference will remain unchanged.
* <p/>
* If the property reference is of the form ${p:v} and there is no such
* property p, then the default value v will be returned.
* <p/>
* If the property reference is of the form ${p1,p2} or ${p1,p2:v} then the
* primary and the secondary properties will be tried in turn, before
* returning either the unchanged input, or the default value.
* <p/>
* The property ${/} is replaced with System.getProperty("file.separator")
* value and the property ${:} is replaced with System.getProperty("path.separator").
*
* @param string - the string with possible ${} references
* @param props - the source for ${x} property ref values, null means use
* System.getProperty()
* @return the input string with all property references replaced if any. If
* there are no valid references the input string will be returned.
*/
public static String replaceProperties(final String string, final Properties props) {
if (string == null)
return null;
final char[] chars = string.toCharArray();
StringBuilder buffer = new StringBuilder();
boolean properties = false;
int state = NORMAL;
int start = 0;
for (int i = 0; i < chars.length; ++i) {
char c = chars[i];
// Dollar sign outside brackets
if (c == '$' && state != IN_BRACKET)
state = SEEN_DOLLAR;
// Open bracket immediatley after dollar
else if (c == '{' && state == SEEN_DOLLAR) {
buffer.append(string, start, i - 1);
state = IN_BRACKET;
start = i - 1;
}
// No open bracket after dollar
else if (state == SEEN_DOLLAR)
state = NORMAL;
// Closed bracket after open bracket
else if (c == '}' && state == IN_BRACKET) {
// No content
if (start + 2 == i) {
buffer.append("${}"); // REVIEW: Correct?
} else // Collect the system property
{
String value;
String key = string.substring(start + 2, i);
// check for alias
if (FILE_SEPARATOR_ALIAS.equals(key)) {
value = FILE_SEPARATOR;
} else if (PATH_SEPARATOR_ALIAS.equals(key)) {
value = PATH_SEPARATOR;
} else {
// check from the properties
value = resolveKey(key, props);
if (value == null) {
// Check for a default value ${key:default}
int colon = key.indexOf(':');
if (colon > 0) {
String realKey = key.substring(0, colon);
value = resolveKey(realKey, props);
if (value == null) {
// Check for a composite key, "key1,key2"
value = resolveCompositeKey(realKey, props);
// Not a composite key either, use the specified default
if (value == null)
value = key.substring(colon + 1);
}
} else {
// No default, check for a composite key, "key1,key2"
value = resolveCompositeKey(key, props);
}
}
}
if (value != null) {
properties = true;
buffer.append(value);
} else {
buffer.append("${");
buffer.append(key);
buffer.append('}');
log.propertyCouldNotBeReplaced(key);
}
}
start = i + 1;
state = NORMAL;
}
}
// No properties
if (!properties)
return string;
// Collect the trailing characters
if (start != chars.length)
buffer.append(string, start, chars.length);
// Done
return buffer.toString();
}
public static void replaceProperties(Map<String, String> map, Properties properties) {
map.replaceAll((k, v) -> replaceProperties(v, properties));
}
/**
* Try to resolve a "key" from the provided properties by checking if it is
* actually a "key1,key2", in which case try first "key1", then "key2". If
* all fails, return null.
* <p/>
* It also accepts "key1," and ",key2".
*
* @param key the key to resolve
* @param props the properties to use
* @return the resolved key or null
*/
private static String resolveCompositeKey(String key, Properties props) {
String value = null;
// Look for the comma
int comma = key.indexOf(',');
if (comma > -1) {
// If we have a first part, try resolve it
if (comma > 0) {
// Check the first part
String key1 = key.substring(0, comma);
value = resolveKey(key1, props);
}
// Check the second part, if there is one and first lookup failed
if (value == null && comma < key.length() - 1) {
String key2 = key.substring(comma + 1);
value = resolveKey(key2, props);
}
}
// Return whatever we've found or null
return value;
}
private static String resolveKey(String key, Properties props) {
if (key.startsWith("env.")) {
return System.getenv(key.substring(4));
} else if (props != null) {
return props.getProperty(key);
} else {
return System.getProperty(key);
}
}
}
| 8,570
| 34.564315
| 99
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/WeakValueHashMap.java
|
package org.infinispan.commons.util;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.AbstractSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* This Map will remove entries when the value in the map has been cleaned from
* garbage collection
*
* @param <K> the key type
* @param <V> the value type
* @author <a href="mailto:bill@jboss.org">Bill Burke</a>
* @author <a href="mailto:adrian@jboss.org">Adrian Brock</a>
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
* @see <a href="http://anonsvn.jboss.org/repos/common/common-core/trunk/src/main/java/org/jboss/util/collection/">
* JBoss Common Core source code for origins of this class</a>
*/
public final class WeakValueHashMap<K, V> extends java.util.AbstractMap<K, V> {
/**
* Hash table mapping keys to ref values
*/
private Map<K, ValueRef<K, V>> map;
/**
* Reference queue for cleared RefKeys
*/
private ReferenceQueue<V> queue = new ReferenceQueue<V>();
/**
* Constructs a new, empty <code>WeakValueHashMap</code> with the given
* initial capacity and the given load factor.
*
* @param initialCapacity The initial capacity of the <code>WeakValueHashMap</code>
* @param loadFactor The load factor of the <code>WeakValueHashMap</code>
* @throws IllegalArgumentException If the initial capacity is less than
* zero, or if the load factor is
* nonpositive
*/
public WeakValueHashMap(int initialCapacity, float loadFactor) {
map = createMap(initialCapacity, loadFactor);
}
/**
* Constructs a new, empty <code>WeakValueHashMap</code> with the given
* initial capacity and the default load factor, which is
* <code>0.75</code>.
*
* @param initialCapacity The initial capacity of the <code>WeakValueHashMap</code>
* @throws IllegalArgumentException If the initial capacity is less than
* zero
*/
public WeakValueHashMap(int initialCapacity) {
map = createMap(initialCapacity);
}
/**
* Constructs a new, empty <code>WeakValueHashMap</code> with the default
* initial capacity and the default load factor, which is
* <code>0.75</code>.
*/
public WeakValueHashMap() {
map = createMap();
}
/**
* Constructs a new <code>WeakValueHashMap</code> with the same mappings as
* the specified <tt>Map</tt>. The <code>WeakValueHashMap</code> is created
* with an initial capacity of twice the number of mappings in the specified
* map or 11 (whichever is greater), and a default load factor, which is
* <tt>0.75</tt>.
*
* @param t the map whose mappings are to be placed in this map.
* @since 1.3
*/
public WeakValueHashMap(Map<K, V> t) {
this(Math.max(2 * t.size(), 11), 0.75f);
putAll(t);
}
/**
* Create new value ref instance.
*
* @param key the key
* @param value the value
* @param q the ref queue
* @return new value ref instance
*/
private ValueRef<K, V> create(K key, V value, ReferenceQueue<V> q) {
return WeakValueRef.create(key, value, q);
}
/**
* Create map.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @return new map instance
*/
private Map<K, ValueRef<K, V>> createMap(int initialCapacity, float loadFactor) {
return new HashMap<K, ValueRef<K, V>>(initialCapacity, loadFactor);
}
/**
* Create map.
*
* @param initialCapacity the initial capacity
* @return new map instance
*/
private Map<K, ValueRef<K, V>> createMap(int initialCapacity) {
return new HashMap<K, ValueRef<K, V>>(initialCapacity);
}
/**
* Create map.
*
* @return new map instance
*/
protected Map<K, ValueRef<K, V>> createMap() {
return new HashMap<K, ValueRef<K, V>>();
}
@Override
public int size() {
processQueue();
return map.size();
}
@Override
public boolean containsKey(Object key) {
processQueue();
return map.containsKey(key);
}
@Override
public V get(Object key) {
processQueue();
ValueRef<K, V> ref = map.get(key);
if (ref != null)
return ref.get();
return null;
}
@Override
public V put(K key, V value) {
processQueue();
ValueRef<K, V> ref = create(key, value, queue);
ValueRef<K, V> result = map.put(key, ref);
if (result != null)
return result.get();
return null;
}
@Override
public V remove(Object key) {
processQueue();
ValueRef<K, V> result = map.remove(key);
if (result != null)
return result.get();
return null;
}
@Override
public Set<Entry<K, V>> entrySet() {
processQueue();
return new EntrySet();
}
@Override
public void clear() {
processQueue();
map.clear();
}
@Override
public String toString() {
return map.toString();
}
/**
* Remove all entries whose values have been discarded.
*/
@SuppressWarnings("unchecked")
private void processQueue() {
ValueRef<K, V> ref = (ValueRef<K, V>) queue.poll();
while (ref != null) {
// only remove if it is the *exact* same WeakValueRef
if (ref == map.get(ref.getKey()))
map.remove(ref.getKey());
ref = (ValueRef<K, V>) queue.poll();
}
}
/**
* EntrySet.
*/
private class EntrySet extends AbstractSet<Entry<K, V>> {
@Override
public Iterator<Entry<K, V>> iterator() {
return new EntrySetIterator(map.entrySet().iterator());
}
@Override
public int size() {
return WeakValueHashMap.this.size();
}
}
/**
* EntrySet iterator
*/
private class EntrySetIterator implements Iterator<Entry<K, V>> {
/**
* The delegate
*/
private Iterator<Entry<K, ValueRef<K, V>>> delegate;
/**
* Create a new EntrySetIterator.
*
* @param delegate the delegate
*/
public EntrySetIterator(Iterator<Entry<K, ValueRef<K, V>>> delegate) {
this.delegate = delegate;
}
public boolean hasNext() {
return delegate.hasNext();
}
public Entry<K, V> next() {
Entry<K, ValueRef<K, V>> next = delegate.next();
return next.getValue();
}
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
/**
* Weak value ref.
*
* @param <K> the key type
* @param <V> the value type
* @author <a href="mailto:bill@jboss.org">Bill Burke</a>
* @author <a href="mailto:adrian@jboss.org">Adrian Brock</a>
* @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a>
*/
private static class WeakValueRef<K, V>
extends WeakReference<V> implements ValueRef<K, V> {
/**
* The key
*/
public K key;
/**
* Safely create a new WeakValueRef
*
* @param <K> the key type
* @param <V> the value type
* @param key the key
* @param val the value
* @param q the reference queue
* @return the reference or null if the value is null
*/
static <K, V> WeakValueRef<K, V> create(K key, V val, ReferenceQueue<V> q) {
if (val == null)
return null;
else
return new WeakValueRef<K, V>(key, val, q);
}
/**
* Create a new WeakValueRef.
*
* @param key the key
* @param val the value
* @param q the reference queue
*/
private WeakValueRef(K key, V val, ReferenceQueue<V> q) {
super(val, q);
this.key = key;
}
public K getKey() {
return key;
}
public V getValue() {
return get();
}
public V setValue(V value) {
throw new UnsupportedOperationException("setValue");
}
@Override
public String toString() {
return String.valueOf(get());
}
}
public interface ValueRef<K, V> extends Map.Entry<K, V> {
/**
* Get underlying value.
*
* @return the value
*/
V get();
}
}
| 8,434
| 25.033951
| 115
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/AbstractMap.java
|
package org.infinispan.commons.util;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Similar to the JDK's AbstractMap, this provides common functionality for custom map implementations. Unlike JDK's
* AbstractMap, there is no support for null keys.
*
* @author Manik Surtani
* @since 4.0
*/
public abstract class AbstractMap<K, V> implements Map<K, V> {
// views
protected transient Set<Map.Entry<K, V>> entrySet = null;
protected transient Set<K> keySet = null;
protected transient Collection<V> values = null;
@Override
public int hashCode() {
int h = 0;
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext())
h += i.next().hashCode();
return h;
}
// The normal bit spreader...
protected static int hash(Object key) {
int h = key.hashCode();
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
protected static boolean eq(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
protected static void assertKeyNotNull(Object key) {
if (key == null) throw new NullPointerException("Null keys are not supported!");
}
protected static class SimpleEntry<K, V> implements Map.Entry<K, V> {
private K key;
private V value;
SimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
SimpleEntry(Map.Entry<K, V> entry) {
this.key = entry.getKey();
this.value = entry.getValue();
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
V old = this.value;
this.value = value;
return old;
}
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
return eq(key, e.getKey()) && eq(value, e.getValue());
}
public int hashCode() {
return hash(key) ^
(value == null ? 0 : hash(value));
}
public String toString() {
return getKey() + "=" + getValue();
}
}
}
| 2,361
| 23.604167
| 117
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ArrayCollector.java
|
package org.infinispan.commons.util;
import java.util.EnumSet;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
public class ArrayCollector implements java.util.stream.Collector<Object, ArrayCollector, ArrayCollector>, Supplier<ArrayCollector> {
private final Object[] array;
private int pos = 0;
public ArrayCollector(Object[] array) {
this.array = array;
}
public void add(Object item) {
array[pos] = item;
++pos;
}
@Override
public Supplier<ArrayCollector> supplier() {
return this;
}
@Override
public ArrayCollector get() {
return this;
}
@Override
public BiConsumer<ArrayCollector, Object> accumulator() {
return ArrayCollector::add;
}
@Override
public BinaryOperator<ArrayCollector> combiner() {
return (a1, a2) -> {
throw new UnsupportedOperationException("The stream is not supposed to be parallel");
};
}
@Override
public Function<ArrayCollector, ArrayCollector> finisher() {
return Function.identity();
}
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of(Characteristics.IDENTITY_FINISH);
}
}
| 1,305
| 22.745455
| 133
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/RangeSet.java
|
package org.infinispan.commons.util;
import java.util.Arrays;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.PrimitiveIterator;
import java.util.Set;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
/**
* Read-only set representing all the integers from {@code 0} to {@code size - 1} (inclusive).
*
* @author Dan Berindei
* @since 9.0
* @deprecated since 9.3 This class will no longer be public. Please use {@link IntSets#immutableRangeSet(int)} instead.
*/
@Deprecated
public class RangeSet implements IntSet {
final int size;
public RangeSet(int size) {
this.size = size;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size <= 0;
}
@Override
public boolean contains(Object o) {
if (!(o instanceof Integer))
return false;
int i = (int) o;
return contains(i);
}
@Override
public boolean contains(int i) {
return 0 <= i && i < size;
}
@Override
public PrimitiveIterator.OfInt iterator() {
return new RangeSetIterator(size);
}
@Override
public int[] toIntArray() {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = i;
}
return array;
}
@Override
public byte[] toBitSet() {
if (size == 0) {
return Util.EMPTY_BYTE_ARRAY;
}
int offset = (size >>> 3);
if ((size & 0xf) == 0) {
byte[] array = new byte[offset];
Arrays.fill(array, (byte) 0xff);
return array;
}
byte[] array = new byte[offset + 1];
if (offset > 0) {
Arrays.fill(array, 0, offset, (byte) 0xff);
}
int lastBitOffset = size > 8 ? size % 8 : size;
array[offset] = (byte) (0xff >> (8 - lastBitOffset));
return array;
}
@Override
public int nextSetBit(int fromIndex) {
return contains(fromIndex) ? fromIndex : -1;
}
@Override
public Object[] toArray() {
Object[] array = new Object[size];
for (int i = 0; i < size; i++) {
array[i] = i;
}
return array;
}
@Override
public <T> T[] toArray(T[] a) {
T[] array = a.length >= size ? a :
(T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
for (int i = 0; i < size; i++) {
array[i] = (T) Integer.valueOf(i);
}
return array;
}
@Override
public boolean add(Integer integer) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public boolean remove(int i) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public boolean containsAll(Collection<?> c) {
if (c instanceof IntSet) {
return containsAll((IntSet) c);
}
for (Object o : c) {
if (!contains(o))
return false;
}
return true;
}
@Override
public boolean containsAll(IntSet set) {
if (set instanceof RangeSet) {
return size >= ((RangeSet) set).size;
}
PrimitiveIterator.OfInt iter = set.iterator();
while (iter.hasNext()) {
if (!contains(iter.nextInt())) {
return false;
}
}
return true;
}
@Override
public boolean add(int i) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
public void set(int i) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public boolean addAll(IntSet set) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public boolean addAll(Collection<? extends Integer> c) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public boolean retainAll(IntSet c) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public boolean removeAll(IntSet set) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public void clear() {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || !(o instanceof Set))
return false;
if (o instanceof RangeSet) {
RangeSet integers = (RangeSet) o;
return size == integers.size;
} else {
Set set = (Set) o;
return size == set.size() && containsAll(set);
}
}
@Override
public IntStream intStream() {
return IntStream.range(0, size);
}
@Override
public void forEach(IntConsumer action) {
for (int i = 0; i < size; ++i) {
action.accept(i);
}
}
@Override
public void forEach(Consumer<? super Integer> action) {
for (int i = 0; i < size; ++i) {
// Has cost of auto boxing, oh well
action.accept(i);
}
}
@Override
public Spliterator.OfInt intSpliterator() {
return new RangeSetSpliterator(size);
}
@Override
public boolean removeIf(IntPredicate filter) {
throw new UnsupportedOperationException("RangeSet is immutable");
}
@Override
public int hashCode() {
return size;
}
@Override
public String toString() {
return "RangeSet(" + size + ")";
}
private static class RangeSetSpliterator implements Spliterator.OfInt {
private int next;
private final int size;
public RangeSetSpliterator(int size) {
this.next = 0;
this.size = size;
}
RangeSetSpliterator(int next, int size) {
this.next = next;
this.size = size;
}
@Override
public OfInt trySplit() {
int lo = next, mid = (lo + size) >>> 1;
return (lo >= mid)
? null
: new RangeSetSpliterator(lo, next = mid);
}
@Override
public void forEachRemaining(IntConsumer action) {
for (; next < size; ++next) {
action.accept(next);
}
}
@Override
public long estimateSize() {
return size - next;
}
@Override
public int characteristics() {
return SIZED | SUBSIZED | DISTINCT | SORTED | ORDERED | NONNULL | IMMUTABLE;
}
@Override
public boolean tryAdvance(IntConsumer action) {
if (next < size) {
action.accept(next++);
return true;
}
return false;
}
}
private static class RangeSetIterator implements PrimitiveIterator.OfInt {
private int size;
private int next;
public RangeSetIterator(int size) {
this.size = size;
this.next = 0;
}
@Override
public boolean hasNext() {
return next < size;
}
@Override
public int nextInt() {
if (next >= size) {
throw new NoSuchElementException();
}
return next++;
}
@Override
public Integer next() {
return nextInt();
}
@Override
public void remove() {
throw new UnsupportedOperationException("RangeSet is read-only");
}
}
}
| 7,842
| 22.482036
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ClassFinder.java
|
package org.infinispan.commons.util;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* Find infinispan classes utility
*/
public class ClassFinder {
private static final Log log = LogFactory.getLog(ClassFinder.class);
public static final String PATH = System.getProperty("java.class.path") + File.pathSeparator
+ System.getProperty("surefire.test.class.path");
public static List<Class<?>> withAnnotationPresent(List<Class<?>> classes, Class<? extends Annotation> c) {
List<Class<?>> clazzes = new ArrayList<>(classes.size());
for (Class<?> clazz : classes) {
if (clazz.isAnnotationPresent(c)) {
clazzes.add(clazz);
}
}
return clazzes;
}
public static List<Class<?>> withAnnotationDeclared(List<Class<?>> classes, Class<? extends Annotation> c) {
List<Class<?>> clazzes = new ArrayList<>(classes.size());
for (Class<?> clazz : classes) {
if (clazz.isAnnotationPresent(c)) {
Annotation[] declaredAnnots = clazz.getDeclaredAnnotations();
for (Annotation declaredAnnot : declaredAnnots) {
if (declaredAnnot.annotationType().isAssignableFrom(c)) {
clazzes.add(clazz);
}
}
}
}
return clazzes;
}
public static List<Class<?>> isAssignableFrom(List<Class<?>> classes, Class<?> clazz) {
List<Class<?>> clazzes = new ArrayList<>(classes.size());
for (Class<?> c : classes) {
if (clazz.isAssignableFrom(c)) {
clazzes.add(c);
}
}
return clazzes;
}
public static List<Class<?>> isAssignableFrom(Class<?> clazz) throws Exception {
return isAssignableFrom(infinispanClasses(), clazz);
}
public static List<Class<?>> infinispanClasses() throws Exception {
return infinispanClasses(PATH);
}
public static List<Class<?>> infinispanClasses(String javaClassPath) throws Exception {
List<File> files = new ArrayList<>();
// either infinispan jar or a directory of output classes contains infinispan classes
for (String path : javaClassPath.split(File.pathSeparator)) {
File file = new File(path);
boolean isInfinispanJar = file.isFile() && file.getName().contains("infinispan");
// Exclude the test utility classes in the commons-test module
boolean isTargetDirectory = file.isDirectory() &&
new File(file, "org/infinispan").isDirectory() &&
!new File(file, "org/infinispan/commons/test").isDirectory();
if (isInfinispanJar || isTargetDirectory) {
files.add(file);
}
}
log.debugf("Looking for infinispan classes in %s", files);
if (files.isEmpty()) {
return Collections.emptyList();
} else {
Set<Class<?>> classFiles = new HashSet<>();
for (File file : files) {
classFiles.addAll(findClassesOnPath(file));
}
return new ArrayList<>(classFiles);
}
}
private static List<Class<?>> findClassesOnPath(File path) {
List<Class<?>> classes = new ArrayList<>();
Class<?> claz;
if (path.isDirectory()) {
List<File> classFiles = new ArrayList<>();
dir(classFiles, path);
for (File cf : classFiles) {
String clazz = null;
try {
clazz = toClassName(path.toPath().relativize(cf.toPath()).toString());
claz = Util.loadClassStrict(clazz, null);
classes.add(claz);
} catch (NoClassDefFoundError ncdfe) {
log.warnf("%s has reference to a class %s that could not be loaded from classpath",
cf.getAbsolutePath(), ncdfe.getMessage());
} catch (Throwable e) {
// Catch all since we do not want skip iteration
log.warn("On path " + cf.getAbsolutePath() + " could not load class "+ clazz, e);
}
}
} else {
if (path.isFile() && path.getName().endsWith("jar") && path.canRead()) {
JarFile jar;
try {
jar = new JarFile(path);
} catch (Exception ex) {
log.warnf("Could not create jar file on path %s", path);
return classes;
}
try {
Enumeration<JarEntry> en = jar.entries();
while (en.hasMoreElements()) {
JarEntry entry = en.nextElement();
if (entry.getName().endsWith("class")) {
String clazz = null;
try {
clazz = toClassName(entry.getName());
claz = Util.loadClassStrict(clazz, null);
classes.add(claz);
} catch (NoClassDefFoundError ncdfe) {
log.warnf("%s has reference to a class %s that could not be loaded from classpath",
entry.getName(), ncdfe.getMessage());
} catch (Throwable e) {
// Catch all since we do not want skip iteration
log.warn("From jar path " + entry.getName() + " could not load class "+ clazz, e);
}
}
}
}
finally {
try {
jar.close();
} catch (IOException e) {
log.debugf(e, "error closing jar file %s", jar);
}
}
}
}
return classes;
}
private static void dir(List<File> files, File dir) {
File[] entries = dir.listFiles();
if (entries != null) {
for (File entry : entries) {
if (entry.isDirectory()) {
dir(files, entry);
} else if (entry.getName().endsWith("class")) {
files.add(entry);
}
}
}
}
private static String toClassName(String classFileName) {
// Remove the .class suffix and replace / with .
return classFileName.substring(0, classFileName.length() - 6)
.replace(File.separator, ".");
}
}
| 6,582
| 35.776536
| 111
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ByteQuantity.java
|
package org.infinispan.commons.util;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* Parser human-readable quantity of bytes.
*
* @since 11.0
*/
public final class ByteQuantity {
private static final Pattern REGEX_PATTERN = Pattern.compile("^(\\d*\\.?\\d+)\\s*((?:(?:[KMGT]i?)B)|B)?$");
private static final BigDecimal KILO = new BigDecimal(1000);
private static final BigDecimal KIBI = new BigDecimal(1024);
private static final Log log = LogFactory.getLog(ByteQuantity.class);
/**
* Parses the byte quantity representation composed of a number plus a unit.
* When the unit is omitted, it is assumed as bytes (B).
*
* The supported units are:
* <ul>
* <li><b>kilobyte (KB)</b>: 1000 bytes</li>
* <li><b>megabyte (MB)</b>: 1000<sup>2</sup> bytes</li>
* <li><b>gigabyte (GB)</b>: 1000<sup>3</sup> bytes</li>
* <li><b>terabyte (TB)</b>: 1000<sup>4</sup> bytes</li>
* <li><b>kibibyte (KiB)</b>: 1024 bytes</li>
* <li><b>mebibyte (MiB)</b>: 1024<sup>2</sup> bytes</li>
* <li><b>gibibyte (GiB)</b>: 1024<sup>3</sup> bytes</li>
* <li><b>tebibyte (TiB)</b>: 1024<sup>4</sup> bytes</li>
* </ul>
* <p>
* Examples: <code>1000</code>, <code>10 GB</code>, <code>1.5TB</code>, <code>100 GiB</code>
* </p>
*
* @param str The String representing a quantity (can have decimals) plus the optional unit.
* @return long number of bytes
* @throws IllegalArgumentException if the string cannot be parsed.
*
*/
public static long parse(String str) throws IllegalArgumentException {
Matcher matcher = REGEX_PATTERN.matcher(str);
if (!matcher.find()) throw log.cannotParseQuantity(str);
try {
String numberPart = matcher.group(1);
String unit = matcher.group(2);
BigDecimal number = new BigDecimal(numberPart);
if (unit == null) {
if (numberPart.contains(".")) throw log.cannotParseQuantity(str);
return number.longValueExact();
}
return Unit.valueOf(unit).toBytes(number);
} catch (ArithmeticException e) {
throw log.cannotParseQuantity(str);
}
}
private enum Unit {
B(KILO, 0),
KB(KILO, 1),
MB(KILO, 2),
GB(KILO, 3),
TB(KILO, 4),
KiB(KIBI, 1),
MiB(KIBI, 2),
GiB(KIBI, 3),
TiB(KIBI, 4);
BigDecimal base;
int exp;
Unit(BigDecimal base, int exp) {
this.base = base;
this.exp = exp;
}
long toBytes(BigDecimal quantity) {
return quantity.multiply(base.pow(exp)).longValueExact();
}
}
}
| 2,804
| 30.516854
| 110
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/FilterSpliterator.java
|
package org.infinispan.commons.util;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Predicate;
/**
* Spliterator that only returns entries that pass the given predicate. This spliterator will inherit all of the
* characteristics of the underlying spliterator, except that it won't return {@link Spliterator#SIZED} or
* {@link Spliterator#SUBSIZED}.
* <p>
* The {@link #forEachRemaining(Consumer)} method should provide better performance than calling
* {@link #tryAdvance(Consumer)} until it returns false. This is due to having to capture the argument before testing
* it and finally invoking the provided {@link Consumer}.
* @author wburns
* @since 9.3
*/
public class FilterSpliterator<T> implements CloseableSpliterator<T> {
private final Spliterator<T> spliterator;
private final Predicate<? super T> predicate;
// We assume that spliterator is not used concurrently - normally it is split so we can use these variables safely
private final Consumer<? super T> consumer = t -> current = t;
private T current;
public FilterSpliterator(Spliterator<T> spliterator, Predicate<? super T> predicate) {
this.spliterator = spliterator;
this.predicate = predicate;
}
@Override
public void close() {
if (spliterator instanceof CloseableSpliterator) {
((CloseableSpliterator) spliterator).close();
}
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
while (spliterator.tryAdvance(consumer)) {
T objectToUse = current;
// If object passes then accept it and return
if (predicate.test(objectToUse)) {
action.accept(objectToUse);
return true;
}
}
return false;
}
@Override
public void forEachRemaining(Consumer<? super T> action) {
spliterator.forEachRemaining(e -> {
if (predicate.test(e)) {
action.accept(e);
}
});
}
@Override
public Spliterator<T> trySplit() {
Spliterator<T> split = spliterator.trySplit();
if (split != null) {
return new FilterSpliterator<>(split, predicate);
}
return null;
}
@Override
public long estimateSize() {
return spliterator.estimateSize();
}
@Override
public int characteristics() {
// Unset the SIZED and SUBSIZED as we don't have an exact amount
return spliterator.characteristics() & ~(Spliterator.SIZED | Spliterator.SUBSIZED);
}
}
| 2,524
| 29.792683
| 117
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/FileLookup.java
|
package org.infinispan.commons.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.Collection;
public interface FileLookup {
/**
* Looks up the file, see : {@link FileLookupFactory.DefaultFileLookup}.
*
* @param filename might be the name of the file (too look it up in the class path) or an url to a file.
* @return an input stream to the file or null if nothing found through all lookup steps.
*/
InputStream lookupFile(String filename, ClassLoader cl);
/**
* Looks up the file, see : {@link FileLookupFactory.DefaultFileLookup}.
*
* @param filename might be the name of the file (too look it up in the class path) or an url to a file.
* @return an input stream to the file or null if nothing found through all lookup steps.
* @throws FileNotFoundException if file cannot be found
*/
InputStream lookupFileStrict(String filename, ClassLoader cl) throws FileNotFoundException;
/**
* Looks up the file, see : {@link FileLookupFactory.DefaultFileLookup}.
*
*
* @param uri An absolute, hierarchical URI with a scheme equal to
* <tt>"file"</tt> that represents the file to lookup
* @return an input stream to the file or null if nothing found through all lookup steps.
* @throws FileNotFoundException if file cannot be found
*/
InputStream lookupFileStrict(URI uri, ClassLoader cl) throws FileNotFoundException;
URL lookupFileLocation(String filename, ClassLoader cl);
Collection<URL> lookupFileLocations(String filename, ClassLoader cl) throws IOException;
}
| 1,680
| 36.355556
| 107
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/ByRef.java
|
package org.infinispan.commons.util;
/**
* This class can be used to pass an argument by reference.
* @param <T> The wrapped type.
*
* @author Dan Berindei
* @since 5.1
*/
public class ByRef<T> {
private T ref;
public ByRef(T t) {
ref = t;
}
public static <T> ByRef<T> create(T t) {
return new ByRef<T>(t);
}
public T get() {
return ref;
}
public void set(T t) {
ref = t;
}
/**
* Implementation for primitive type
*/
public static class Boolean {
boolean ref;
public Boolean(boolean b) {
ref = b;
}
public boolean get() {
return ref;
}
public void set(boolean b) {
this.ref = b;
}
}
public static class Integer {
int ref;
public Integer(int i) {
ref = i;
}
public int get() {
return ref;
}
public void set(int i) {
ref = i;
}
public void inc() {
ref++;
}
public void dec() {
ref--;
}
}
public static class Long {
long ref;
public Long(long i) {
ref = i;
}
public long get() {
return ref;
}
public void set(long i) {
ref = i;
}
public long getAndAdd(long i) {
long ret = ref;
ref += i;
return ret;
}
public void inc() {
ref++;
}
public void dec() {
ref--;
}
}
}
| 1,499
| 13.705882
| 59
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/Experimental.java
|
package org.infinispan.commons.util;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PACKAGE;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.CLASS;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* An experimental user-facing API. Elements annotated with this annotation
* are experimental and may get removed from the distribution at any time.
*
* @since 8.0
*/
@Retention(CLASS)
@Target({PACKAGE, TYPE, ANNOTATION_TYPE, METHOD, CONSTRUCTOR, FIELD})
@Documented
public @interface Experimental {
String value() default "";
}
| 896
| 32.222222
| 75
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/CloseableIterable.java
|
package org.infinispan.commons.util;
/**
* Interface that provides semantics of a {@link Iterable} and {@link AutoCloseable} interfaces. This is
* useful when you have data that must be iterated on and may hold resources in the underlying implementation that
* must be closed.
* <p>The close method will close any existing iterators that may be open to free resources</p>
*
* @author wburns
* @since 7.0
*/
public interface CloseableIterable<E> extends AutoCloseable, Iterable<E> {
@Override
void close();
@Override
CloseableIterator<E> iterator();
}
| 574
| 29.263158
| 114
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/RemovableIterator.java
|
package org.infinispan.commons.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
/**
* An Iterator implementation that allows for a Iterator that doesn't allow remove operations to
* implement remove by delegating the call to the provided consumer to remove the previously read value.
*
* @author wburns
* @since 9.1
*/
public class RemovableIterator<C> implements Iterator<C> {
protected final Iterator<C> realIterator;
protected final Consumer<? super C> consumer;
protected C previousValue;
protected C currentValue;
public RemovableIterator(Iterator<C> realIterator, Consumer<? super C> consumer) {
this.realIterator = realIterator;
this.consumer = consumer;
}
protected C getNextFromIterator() {
if (realIterator.hasNext()) {
return realIterator.next();
} else {
return null;
}
}
@Override
public boolean hasNext() {
return currentValue != null || (currentValue = getNextFromIterator()) != null;
}
@Override
public C next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
previousValue = currentValue;
currentValue = null;
return previousValue;
}
@Override
public void remove() {
if (previousValue == null) {
throw new IllegalStateException();
}
consumer.accept(previousValue);
previousValue = null;
}
}
| 1,470
| 24.362069
| 104
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/SslContextFactory.java
|
package org.infinispan.commons.util;
import static org.infinispan.commons.logging.Log.SECURITY;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.wildfly.openssl.OpenSSLProvider;
import org.wildfly.openssl.SSL;
/**
* SslContextFactory.
*
* @author Tristan Tarrant
* @since 5.3
*/
public class SslContextFactory {
private static final String DEFAULT_KEYSTORE_TYPE = "JKS";
private static final String DEFAULT_SSL_PROTOCOL = "TLSv1.2";
private static final String CLASSPATH_RESOURCE = "classpath:";
private static final String SSL_PROVIDER;
private static final ConcurrentHashMap<ClassLoader, Provider[]> PER_CLASSLOADER_PROVIDERS = new ConcurrentHashMap<>(2);
static {
String sslProvider = null;
if (Boolean.parseBoolean(System.getProperty("org.infinispan.openssl", "true"))) {
try {
OpenSSLProvider.register();
SSL.getInstance();
sslProvider = "openssl";
SECURITY.openSSLAvailable();
} catch (Throwable e) {
SECURITY.openSSLNotAvailable();
}
}
SSL_PROVIDER = sslProvider;
}
private String keyStoreFileName;
private char[] keyStorePassword;
private char[] keyStoreCertificatePassword;
private String keyStoreType = DEFAULT_KEYSTORE_TYPE;
private String keyAlias;
private String trustStoreFileName;
private char[] trustStorePassword;
private String trustStoreType = DEFAULT_KEYSTORE_TYPE;
private String sslProtocol = DEFAULT_SSL_PROTOCOL;
private boolean useNativeIfAvailable = true;
private ClassLoader classLoader;
private String provider;
public SslContextFactory() {
}
public SslContextFactory keyStoreFileName(String keyStoreFileName) {
this.keyStoreFileName = keyStoreFileName;
return this;
}
public SslContextFactory keyStorePassword(char[] keyStorePassword) {
this.keyStorePassword = keyStorePassword;
return this;
}
public SslContextFactory keyStoreCertificatePassword(char[] keyStoreCertificatePassword) {
this.keyStoreCertificatePassword = keyStoreCertificatePassword;
return this;
}
public SslContextFactory keyStoreType(String keyStoreType) {
if (keyStoreType != null) {
this.keyStoreType = keyStoreType;
}
return this;
}
public SslContextFactory keyAlias(String keyAlias) {
this.keyAlias = keyAlias;
return this;
}
public SslContextFactory trustStoreFileName(String trustStoreFileName) {
this.trustStoreFileName = trustStoreFileName;
return this;
}
public SslContextFactory trustStorePassword(char[] trustStorePassword) {
this.trustStorePassword = trustStorePassword;
return this;
}
public SslContextFactory trustStoreType(String trustStoreType) {
if (trustStoreType != null) {
this.trustStoreType = trustStoreType;
}
return this;
}
public SslContextFactory sslProtocol(String sslProtocol) {
if (sslProtocol != null) {
this.sslProtocol = sslProtocol;
}
return this;
}
public SslContextFactory provider(String provider) {
if (provider != null) {
this.provider = provider;
}
return this;
}
public SslContextFactory useNativeIfAvailable(boolean useNativeIfAvailable) {
this.useNativeIfAvailable = useNativeIfAvailable;
return this;
}
public SslContextFactory classLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
return this;
}
public SSLContext getContext() {
try {
KeyManager[] keyManagers = null;
if (keyStoreFileName != null) {
KeyManagerFactory kmf = getKeyManagerFactory();
keyManagers = kmf.getKeyManagers();
}
TrustManager[] trustManagers = null;
if (trustStoreFileName != null) {
TrustManagerFactory tmf = getTrustManagerFactory();
trustManagers = tmf.getTrustManagers();
}
SSLContext sslContext;
Provider provider = null;
if (this.provider != null) {
// If the user has supplied a provider, try to use it
provider = findProvider(this.provider, SSLContext.class.getSimpleName(), sslProtocol);
}
if (provider == null && useNativeIfAvailable && SSL_PROVIDER != null) {
// Try to use the native provider if possible
provider = findProvider(SSL_PROVIDER, SSLContext.class.getSimpleName(), sslProtocol);
}
sslContext = provider != null ? SSLContext.getInstance(sslProtocol, provider) : SSLContext.getInstance(sslProtocol);
sslContext.init(keyManagers, trustManagers, null);
return sslContext;
} catch (Exception e) {
throw SECURITY.sslInitializationException(e);
}
}
public KeyManagerFactory getKeyManagerFactory() throws IOException, GeneralSecurityException {
String type = keyStoreType != null ? keyStoreType : DEFAULT_KEYSTORE_TYPE;
Provider provider = findProvider(this.provider, KeyManagerFactory.class.getSimpleName(), type);
KeyStore ks = provider != null ? KeyStore.getInstance(type, provider) : KeyStore.getInstance(type);
loadKeyStore(ks, keyStoreFileName, keyStorePassword, classLoader);
char[] keyPassword = keyStoreCertificatePassword == null ? keyStorePassword : keyStoreCertificatePassword;
if (keyAlias != null) {
if (ks.containsAlias(keyAlias) && ks.isKeyEntry(keyAlias)) {
KeyStore.PasswordProtection passParam = new KeyStore.PasswordProtection(keyPassword);
KeyStore.Entry entry = ks.getEntry(keyAlias, passParam);
// Recreate the keystore with just one key
ks = provider != null ? KeyStore.getInstance(type, provider) : KeyStore.getInstance(type);
ks.load(null, null);
ks.setEntry(keyAlias, entry, passParam);
} else {
throw SECURITY.noSuchAliasInKeyStore(keyAlias, keyStoreFileName);
}
}
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
provider = findProvider(this.provider, KeyManagerFactory.class.getSimpleName(), algorithm);
KeyManagerFactory kmf = provider != null ? KeyManagerFactory.getInstance(algorithm, provider) : KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, keyPassword);
return kmf;
}
public TrustManagerFactory getTrustManagerFactory() throws IOException, GeneralSecurityException {
String type = trustStoreType != null ? trustStoreType : DEFAULT_KEYSTORE_TYPE;
Provider provider = findProvider(this.provider, KeyStore.class.getSimpleName(), trustStoreType);
KeyStore ks = provider != null ? KeyStore.getInstance(type, provider) : KeyStore.getInstance(type);
loadKeyStore(ks, trustStoreFileName, trustStorePassword, classLoader);
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
provider = findProvider(this.provider, TrustManagerFactory.class.getSimpleName(), algorithm);
TrustManagerFactory tmf = provider != null ? TrustManagerFactory.getInstance(algorithm, provider) : TrustManagerFactory.getInstance(algorithm);
tmf.init(ks);
return tmf;
}
public static String getSslProvider() {
return SSL_PROVIDER;
}
public static SSLEngine getEngine(SSLContext sslContext, boolean useClientMode, boolean needClientAuth) {
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(useClientMode);
sslEngine.setNeedClientAuth(needClientAuth);
return sslEngine;
}
private static void loadKeyStore(KeyStore ks, String keyStoreFileName, char[] keyStorePassword, ClassLoader classLoader) throws IOException, GeneralSecurityException {
InputStream is = null;
try {
if (keyStoreFileName.startsWith(CLASSPATH_RESOURCE)) {
String fileName = keyStoreFileName.substring(keyStoreFileName.indexOf(":") + 1);
is = Util.getResourceAsStream(fileName, classLoader);
if (is == null) {
throw SECURITY.cannotFindResource(keyStoreFileName);
}
} else {
is = new BufferedInputStream(new FileInputStream(keyStoreFileName));
}
ks.load(is, keyStorePassword);
} finally {
Util.close(is);
}
}
public static Provider findProvider(String providerName, String serviceType, String algorithm) {
Provider[] providers = discoverSecurityProviders(Thread.currentThread().getContextClassLoader());
for (Provider provider : providers) {
if (providerName == null || providerName.equals(provider.getName())) {
Provider.Service providerService = provider.getService(serviceType, algorithm);
if (providerService != null) {
return provider;
}
}
}
return null;
}
public static Provider[] discoverSecurityProviders(ClassLoader classLoader) {
return PER_CLASSLOADER_PROVIDERS.computeIfAbsent(classLoader, cl -> {
// We need to keep them sorted by insertion order, since we want system providers first
Map<Class<? extends Provider>, Provider> providers = new LinkedHashMap<>();
for (Provider provider : Security.getProviders()) {
providers.put(provider.getClass(), provider);
}
for (Provider provider : ServiceFinder.load(Provider.class, classLoader)) {
providers.putIfAbsent(provider.getClass(), provider);
}
return providers.values().toArray(new Provider[0]);
}
);
}
}
| 10,233
| 37.912548
| 170
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/SimpleImmutableEntry.java
|
package org.infinispan.commons.util;
import java.io.Serializable;
import java.util.Map;
import java.util.Map.Entry;
/**
* Where is Java 1.6?
*
* @author (various)
* @since 4.0
*/
public class SimpleImmutableEntry<K, V> implements Map.Entry<K, V>, Serializable {
private static final long serialVersionUID = -6092752114794052323L;
private final K key;
private final V value;
public SimpleImmutableEntry(Entry<K, V> me) {
key = me.getKey();
value = me.getValue();
}
public SimpleImmutableEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V arg0) {
throw new UnsupportedOperationException();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?, ?> e2 = (Map.Entry<?, ?>) o;
return (getKey() == null ? e2.getKey() == null : getKey().equals(e2.getKey()))
&& (getValue() == null ? e2.getValue() == null : getValue().equals(e2.getValue()));
}
@Override
public int hashCode() {
return (getKey() == null ? 0 : getKey().hashCode()) ^
(getValue() == null ? 0 : getValue().hashCode());
}
@Override
public String toString() {
return key + "=" + value;
}
}
| 1,423
| 20.907692
| 95
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/EntrySizeCalculator.java
|
package org.infinispan.commons.util;
/**
*
* @param <K> The key type for this entry size calculator
* @param <V> The value type for this entry size calculator
*/
@FunctionalInterface
public interface EntrySizeCalculator<K, V> {
/**
* Method used to calculate how much memory in size the key and value use.
* @param key The key for this entry to be used in size calculation
* @param value The value for this entry to be used in size calculation
* @return The size approximately in memory the key and value use
*/
long calculateSize(K key, V value);
}
| 581
| 31.333333
| 77
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/Util.java
|
package org.infinispan.commons.util;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import javax.naming.Context;
import javax.security.auth.Subject;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.hash.Hash;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
import org.infinispan.commons.marshall.Marshaller;
/**
* General utility methods used throughout the Infinispan code base.
*
* @author <a href="brian.stansberry@jboss.com">Brian Stansberry</a>
* @author Galder Zamarreño
* @since 4.0
*/
public final class Util {
private static final boolean IS_ARRAYS_DEBUG = Boolean.getBoolean("infinispan.arrays.debug");
private static final int COLLECTIONS_LIMIT = Integer.getInteger("infinispan.collections.limit", 8);
public static final int HEX_DUMP_LIMIT = Integer.getInteger("infinispan.hexdump.limit", 64);
public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
public static final String[] EMPTY_STRING_ARRAY = new String[0];
public static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
public static final byte[][] EMPTY_BYTE_ARRAY_ARRAY = new byte[0][];
public static final String GENERIC_JBOSS_MARSHALLING_CLASS = "org.infinispan.jboss.marshalling.commons.GenericJBossMarshaller";
public static final String JBOSS_USER_MARSHALLER_CLASS = "org.infinispan.jboss.marshalling.core.JBossUserMarshaller";
private static final Log log = LogFactory.getLog(Util.class);
private static final Set<Class<?>> BASIC_TYPES;
private static final String HEX_VALUES = "0123456789ABCDEF";
private static final char[] HEX_DUMP_CHARS = new char[256 * 2];
static {
BASIC_TYPES = new HashSet<>();
BASIC_TYPES.add(Boolean.class);
BASIC_TYPES.add(Byte.class);
BASIC_TYPES.add(Character.class);
BASIC_TYPES.add(Double.class);
BASIC_TYPES.add(Float.class);
BASIC_TYPES.add(Integer.class);
BASIC_TYPES.add(Long.class);
BASIC_TYPES.add(Short.class);
BASIC_TYPES.add(String.class);
BASIC_TYPES.add(char[].class);
for (char b = 0; b < 256; b++) {
if (0x20 <= b && b <= 0x7e) {
HEX_DUMP_CHARS[b * 2] = '\\';
HEX_DUMP_CHARS[b * 2 + 1] = b;
} else {
HEX_DUMP_CHARS[b * 2] = HEX_VALUES.charAt((b & 0xF0) >> 4);
HEX_DUMP_CHARS[b * 2 + 1] = HEX_VALUES.charAt((b & 0x0F));
}
}
}
/**
* <p>
* Loads the specified class using the passed classloader, or, if it is <code>null</code> the Infinispan classes'
* classloader.
* </p>
*
* <p>
* If loadtime instrumentation via GenerateInstrumentedClassLoader is used, this class may be loaded by the bootstrap
* classloader.
* </p>
* <p>
* If the class is not found, the {@link ClassNotFoundException} or {@link NoClassDefFoundError} is wrapped as a
* {@link CacheConfigurationException} and is re-thrown.
* </p>
*
* @param classname name of the class to load
* @param cl the application classloader which should be used to load the class, or null if the class is
* always packaged with Infinispan
* @return the class
* @throws CacheConfigurationException if the class cannot be loaded
*/
public static <T> Class<T> loadClass(String classname, ClassLoader cl) {
try {
return loadClassStrict(classname, cl);
} catch (ClassNotFoundException e) {
throw Log.CONTAINER.cannotInstantiateClass(classname, e);
}
}
public static ClassLoader[] getClassLoaders(ClassLoader appClassLoader) {
return new ClassLoader[]{
appClassLoader, // User defined classes
Util.class.getClassLoader(), // Infinispan classes (not always on TCCL [modular env])
ClassLoader.getSystemClassLoader(), // Used when load time instrumentation is in effect
Thread.currentThread().getContextClassLoader() //Used by jboss-as stuff
};
}
/**
* <p>
* Loads the specified class using the passed classloader, or, if it is <code>null</code> the Infinispan classes'
* classloader.
* </p>
*
* <p>
* If loadtime instrumentation via GenerateInstrumentedClassLoader is used, this class may be loaded by the bootstrap
* classloader.
* </p>
*
* @param classname name of the class to load
* @param userClassLoader the application classloader which should be used to load the class, or null if the class is
* always packaged with Infinispan
* @return the class
* @throws ClassNotFoundException if the class cannot be loaded
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> loadClassStrict(String classname, ClassLoader userClassLoader) throws ClassNotFoundException {
ClassLoader[] cls = getClassLoaders(userClassLoader);
ClassNotFoundException e = null;
NoClassDefFoundError ne = null;
for (ClassLoader cl : cls) {
if (cl == null)
continue;
try {
return (Class<T>) Class.forName(classname, true, cl);
} catch (ClassNotFoundException ce) {
e = ce;
} catch (NoClassDefFoundError ce) {
ne = ce;
}
}
if (ne != null) {
//Always log the NoClassDefFoundError errors first:
//if one happened they will contain critically useful details.
log.unableToLoadClass(classname, Arrays.toString(cls), ne);
}
if (e != null)
throw e;
else if (ne != null) {
throw new ClassNotFoundException(classname, ne);
} else
throw new IllegalStateException();
}
public static InputStream getResourceAsStream(String resourcePath, ClassLoader userClassLoader) {
if (resourcePath.startsWith("/")) {
resourcePath = resourcePath.substring(1);
}
InputStream is = null;
for (ClassLoader cl : getClassLoaders(userClassLoader)) {
if (cl != null) {
is = cl.getResourceAsStream(resourcePath);
if (is != null) {
break;
}
}
}
return is;
}
public static String getResourceAsString(String resourcePath, ClassLoader userClassLoader) throws IOException {
return read(getResourceAsStream(resourcePath, userClassLoader));
}
private static Method getFactoryMethod(Class<?> c) {
for (Method m : c.getMethods()) {
if (m.getName().equals("getInstance") && m.getParameterCount() == 0 && Modifier.isStatic(m.getModifiers()))
return m;
}
return null;
}
/**
* Instantiates a class by invoking the constructor that matches the provided parameter types passing the given
* arguments. If no matching constructor is found this will return null. Note that the constructor must be public.
* <p/>
* Any exceptions encountered are wrapped in a {@link CacheConfigurationException} and rethrown.
*
* @param clazz class to instantiate
* @param <T> the instance type
* @return the new instance if a matching constructor was found otherwise null
*/
public static <T> T newInstanceOrNull(Class<T> clazz, Class[] parameterTypes, Object... arguments) {
if (parameterTypes.length != arguments.length) {
throw new IllegalArgumentException("Parameter type count: " + parameterTypes.length +
" does not match parameter arguments count: " + arguments.length);
}
try {
Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes);
if (constructor != null) {
return constructor.newInstance(arguments);
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new CacheConfigurationException("Unable to instantiate class '" + clazz.getName() + "' with constructor " +
"taking parameters " + Arrays.toString(arguments), e);
}
return null;
}
/**
* Instantiates a class by first attempting a static <i>factory method</i> named <tt>getInstance()</tt> on the class
* and then falling back to an empty constructor.
* <p/>
* Any exceptions encountered are wrapped in a {@link CacheConfigurationException} and rethrown.
*
* @param clazz class to instantiate
* @return an instance of the class
*/
public static <T> T getInstance(Class<T> clazz) {
try {
return getInstanceStrict(clazz);
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException |
InvocationTargetException iae) {
throw new CacheConfigurationException("Unable to instantiate class '" + clazz.getName() + "'", iae);
}
}
/**
* Similar to {@link #getInstance(Class)} except that exceptions are propagated to the caller.
*
* @param clazz class to instantiate
* @return an instance of the class
* @throws IllegalAccessException
* @throws InstantiationException
*/
@SuppressWarnings("unchecked")
public static <T> T getInstanceStrict(Class<T> clazz) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
// first look for a getInstance() constructor
T instance = null;
try {
Method factoryMethod = getFactoryMethod(clazz);
if (factoryMethod != null) instance = (T) factoryMethod.invoke(null);
} catch (Exception e) {
// no factory method or factory method failed. Try a constructor.
instance = null;
}
if (instance == null) {
instance = clazz.getDeclaredConstructor().newInstance();
}
return instance;
}
/**
* Instantiates a class based on the class name provided. Instantiation is attempted via an appropriate, static
* factory method named <tt>getInstance()</tt> first, and failing the existence of an appropriate factory, falls back
* to an empty constructor.
* <p/>
* Any exceptions encountered loading and instantiating the class is wrapped in a
* {@link CacheConfigurationException}.
*
* @param classname class to instantiate
* @return an instance of classname
*/
public static <T> T getInstance(String classname, ClassLoader cl) {
if (classname == null) throw new IllegalArgumentException("Cannot load null class!");
Class<T> clazz = loadClass(classname, cl);
return getInstance(clazz);
}
/**
* Similar to {@link #getInstance(String, ClassLoader)} except that exceptions are propagated to the caller.
*
* @param classname class to instantiate
* @return an instance of classname
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
public static <T> T getInstanceStrict(String classname, ClassLoader cl) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
if (classname == null) throw new IllegalArgumentException("Cannot load null class!");
Class<T> clazz = loadClassStrict(classname, cl);
return getInstanceStrict(clazz);
}
/**
* Given two Runnables, return a Runnable that executes both in sequence, even if the first throws an exception, and
* if both throw exceptions, add any exceptions thrown by the second as suppressed exceptions of the first.
*/
public static Runnable composeWithExceptions(Runnable a, Runnable b) {
return () -> {
try {
a.run();
} catch (Throwable e1) {
try {
b.run();
} catch (Throwable e2) {
try {
e1.addSuppressed(e2);
} catch (Throwable ignore) {
}
}
throw e1;
}
b.run();
};
}
/**
* Prevent instantiation
*/
private Util() {
}
/**
* Null-safe equality test.
*
* @param a first object to compare
* @param b second object to compare
* @return true if the objects are equals or both null, false otherwise.
*/
public static boolean safeEquals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
public static String prettyPrintTime(long time, TimeUnit unit) {
return prettyPrintTime(unit.toMillis(time));
}
/**
* {@link System#nanoTime()} is less expensive than {@link System#currentTimeMillis()} and better suited to measure
* time intervals. It's NOT suited to know the current time, for example to be compared with the time of other
* nodes.
*
* @return the value of {@link System#nanoTime()}, but converted in Milliseconds.
*/
public static long currentMillisFromNanotime() {
return TimeUnit.MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS);
}
/**
* Prints a time for display
*
* @param millis time in millis
* @return the time, represented as millis, seconds, minutes or hours as appropriate, with suffix
*/
public static String prettyPrintTime(long millis) {
if (millis < 1000) return millis + " milliseconds";
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
double toPrint = ((double) millis) / 1000;
if (toPrint < 300) {
return nf.format(toPrint) + " seconds";
}
toPrint = toPrint / 60;
if (toPrint < 120) {
return nf.format(toPrint) + " minutes";
}
toPrint = toPrint / 60;
return nf.format(toPrint) + " hours";
}
/**
* Reads the given InputStream fully, closes the stream and returns the result as a String.
*
* @param is the stream to read
* @return the UTF-8 string
* @throws java.io.IOException in case of stream read errors
*/
public static String read(InputStream is) throws IOException {
try {
final Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
StringWriter writer = new StringWriter();
char[] buf = new char[1024];
int len;
while ((len = reader.read(buf)) != -1) {
writer.write(buf, 0, len);
}
return writer.toString();
} finally {
is.close();
}
}
public static void close(AutoCloseable cl) {
if (cl == null) return;
try {
cl.close();
} catch (Exception e) {
}
}
public static void close(Socket s) {
if (s == null) return;
try {
s.close();
} catch (Exception e) {
}
}
public static void close(AutoCloseable... cls) {
for (AutoCloseable cl : cls) {
close(cl);
}
}
public static void close(Context ctx) {
if (ctx == null) return;
try {
ctx.close();
} catch (Exception e) {
}
}
public static String formatString(Object message, Object... params) {
if (params.length == 0) return message == null ? "null" : message.toString();
return String.format(message.toString(), params);
}
public static String toStr(Object o) {
if (o == null) {
return "null";
} else if (o.getClass().isArray()) {
// as Java arrays are covariant, this cast is safe unless it's primitive
if (o.getClass().getComponentType().isPrimitive()) {
if (o instanceof byte[]) {
return printArray((byte[]) o, false);
} else if (o instanceof int[]) {
return Arrays.toString((int[]) o);
} else if (o instanceof long[]) {
return Arrays.toString((long[]) o);
} else if (o instanceof short[]) {
return Arrays.toString((short[]) o);
} else if (o instanceof double[]) {
return Arrays.toString((double[]) o);
} else if (o instanceof float[]) {
return Arrays.toString((float[]) o);
} else if (o instanceof char[]) {
return Arrays.toString((char[]) o);
} else if (o instanceof boolean[]) {
return Arrays.toString((boolean[]) o);
}
}
return Arrays.toString((Object[]) o);
} else {
return o.toString();
}
}
public static <E> String toStr(Collection<E> collection) {
if (collection == null)
return "[]";
Iterator<E> i = collection.iterator();
if (!i.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (int counter = 0; ; ) {
E e = i.next();
sb.append(e == collection ? "(this Collection)" : toStr(e));
if (!i.hasNext())
return sb.append(']').toString();
if (++counter >= COLLECTIONS_LIMIT) {
return sb.append("...<")
.append(collection.size() - COLLECTIONS_LIMIT)
.append(" other elements>]").toString();
}
sb.append(", ");
}
}
public static String printArray(byte[] array) {
return printArray(array, false);
}
public static String printArray(byte[] array, boolean withHash) {
if (array == null) return "null";
int limit = 16;
StringBuilder sb = new StringBuilder();
sb.append("[B0x");
if (array.length <= limit || IS_ARRAYS_DEBUG) {
// Convert the entire byte array
sb.append(toHexString(array));
if (withHash) {
sb.append(",h=");
sb.append(Integer.toHexString(Arrays.hashCode(array)));
sb.append(']');
}
} else {
// Pick the first limit characters and convert that part
sb.append(toHexString(array, limit));
sb.append("..[");
sb.append(array.length);
if (withHash) {
sb.append("],h=");
sb.append(Integer.toHexString(Arrays.hashCode(array)));
}
sb.append(']');
}
return sb.toString();
}
public static String toHexString(byte[] input) {
return toHexString(input, input != null ? input.length : 0);
}
public static String toHexString(byte[] input, int limit) {
return toHexString(input, 0, limit);
}
public static String toHexString(byte[] input, int offset, int limit) {
if (input == null)
return "null";
int length = Math.min(limit - offset, input.length - offset);
char[] result = new char[length * 2];
for (int i = 0; i < length; ++i) {
result[2 * i] = HEX_VALUES.charAt((input[i + offset] >> 4) & 0x0F);
result[2 * i + 1] = HEX_VALUES.charAt((input[i + offset] & 0x0F));
}
return String.valueOf(result);
}
public static String padString(String s, int minWidth) {
if (s.length() < minWidth) {
StringBuilder sb = new StringBuilder(s);
while (sb.length() < minWidth) sb.append(" ");
return sb.toString();
}
return s;
}
private final static String INDENT = " ";
public static String threadDump() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timestamp = dateFormat.format(new Date());
StringBuilder threadDump = new StringBuilder();
threadDump.append(timestamp);
threadDump.append("\nFull thread dump ");
threadDump.append("\n");
Thread.getAllStackTraces().forEach((thread, elements) -> {
threadDump.append("\"").append(thread.getName())
.append("\" nid=").append(thread.getId())
.append(" state=").append(thread.getState())
.append("\n");
for (StackTraceElement e : elements) {
threadDump.append(INDENT).append("at ").append(e.toString()).append("\n");
}
});
return threadDump.toString();
}
public static CacheException rewrapAsCacheException(Throwable t) {
if (t instanceof CompletionException)
throw new IllegalArgumentException("CompletionException should never be wrapped");
if (t instanceof CacheException)
return (CacheException) t;
else
return new CacheException(t);
}
@SafeVarargs
public static <T> Set<T> asSet(T... a) {
if (a.length > 1)
return new HashSet<>(Arrays.asList(a));
else
return Collections.singleton(a[0]);
}
/**
* Prints the identity hash code of the object passed as parameter in an hexadecimal format in order to safe space.
*/
public static String hexIdHashCode(Object o) {
return Integer.toHexString(System.identityHashCode(o));
}
public static String hexDump(byte[] data) {
return hexDump(data, 0, data.length);
}
public static String hexDump(ByteBuffer buffer) {
return hexDump(buffer::get, buffer.position(), buffer.remaining());
}
public static String hexDump(byte[] buffer, int offset, int actualLength) {
assert actualLength + offset <= buffer.length;
int dumpLength = Math.min(actualLength, HEX_DUMP_LIMIT);
StringBuilder sb = new StringBuilder(dumpLength * 2 + 30);
for (int i = 0; i < dumpLength; ++i) {
addHexByte(sb, buffer[offset + i]);
}
if (dumpLength < actualLength) {
sb.append("...");
}
sb.append(" (").append(actualLength).append(" bytes)");
return sb.toString();
}
public static String hexDump(ByteGetter byteGetter, int offset, int actualLength) {
int dumpLength = Math.min(actualLength, HEX_DUMP_LIMIT);
StringBuilder sb = new StringBuilder(dumpLength * 2 + 30);
for (int i = 0; i < dumpLength; ++i) {
addHexByte(sb, byteGetter.get(offset + i));
}
if (dumpLength < actualLength) {
sb.append("...");
}
sb.append(" (").append(actualLength).append(" bytes)");
return sb.toString();
}
public static void addHexByte(StringBuilder buf, byte b) {
int offset = (b & 0xFF) * 2;
buf.append(HEX_DUMP_CHARS, offset, 2);
}
private static void addSingleHexChar(StringBuilder buf, byte b) {
buf.append(HEX_VALUES.charAt(b & 0x0F));
}
/**
* Applies the given hash function to the hash code of a given object, and then normalizes it to ensure a positive
* value is always returned.
*
* @param object to hash
* @param hashFct hash function to apply
* @return a non-null, non-negative normalized hash code for a given object
*/
public static int getNormalizedHash(Object object, Hash hashFct) {
// make sure no negative numbers are involved.
return hashFct.hash(object) & Integer.MAX_VALUE;
}
/**
* Returns the size of each segment, given a number of segments.
*
* @param numSegments number of segments required
* @return the size of each segment
*/
public static int getSegmentSize(int numSegments) {
return (int) Math.ceil((double) (1L << 31) / numSegments);
}
public static String join(List<String> strings, String separator) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String string : strings) {
if (!first) {
sb.append(separator);
} else {
first = false;
}
sb.append(string);
}
return sb.toString();
}
/**
* Returns a number such that the number is a power of two that is equal to, or greater than, the number passed in as
* an argument. The smallest number returned will be 1. Due to having to be a power of two, the highest int this can
* return is 2<sup>31 since int is signed.
*/
public static int findNextHighestPowerOfTwo(int num) {
if (num <= 1) {
return 1;
} else if (num >= 0x40000000) {
return 0x40000000;
}
int highestBit = Integer.highestOneBit(num);
return num <= highestBit ? highestBit : highestBit << 1;
}
/**
* A function that calculates hash code of a byte array based on its contents but using the given size parameter as
* deliminator for the content.
*/
public static int hashCode(byte[] bytes, int size) {
int contentLimit = size;
if (size > bytes.length)
contentLimit = bytes.length;
int hashCode = 1;
for (int i = 0; i < contentLimit; i++)
hashCode = 31 * hashCode + bytes[i];
return hashCode;
}
/**
* Prints {@link Subject}'s principals as a one-liner (as opposed to default Subject's <code>toString()</code>
* method, which prints every principal on separate line).
*/
public static String prettyPrintSubject(Subject subject) {
return (subject == null) ? "null" : "Subject with principal(s): " + toStr(subject.getPrincipals());
}
/**
* Uses a {@link ThreadLocalRandom} to generate a UUID. Faster, but not secure
*/
public static UUID threadLocalRandomUUID() {
byte[] data = new byte[16];
ThreadLocalRandom.current().nextBytes(data);
data[6] &= 0x0f; /* clear version */
data[6] |= 0x40; /* set to version 4 */
data[8] &= 0x3f; /* clear variant */
data[8] |= 0x80; /* set to IETF variant */
long msb = 0;
long lsb = 0;
for (int i = 0; i < 8; i++)
msb = (msb << 8) | (data[i] & 0xff);
for (int i = 8; i < 16; i++)
lsb = (lsb << 8) | (data[i] & 0xff);
return new UUID(msb, lsb);
}
public static String unicodeEscapeString(String s) {
int len = s.length();
StringBuilder out = new StringBuilder(len * 2);
for (int x = 0; x < len; x++) {
char aChar = s.charAt(x);
if ((aChar > 61) && (aChar < 127)) {
if (aChar == '\\') {
out.append('\\');
out.append('\\');
continue;
}
out.append(aChar);
continue;
}
switch (aChar) {
case ' ':
if (x == 0)
out.append('\\');
out.append(' ');
break;
case '\t':
out.append('\\');
out.append('t');
break;
case '\n':
out.append('\\');
out.append('n');
break;
case '\r':
out.append('\\');
out.append('r');
break;
case '\f':
out.append('\\');
out.append('f');
break;
case '=':
case ':':
case '#':
case '!':
out.append('\\');
out.append(aChar);
break;
default:
if ((aChar < 0x0020) || (aChar > 0x007e)) {
out.append('\\');
out.append('u');
addSingleHexChar(out, (byte) ((aChar >> 12) & 0xF));
addSingleHexChar(out, (byte) ((aChar >> 8) & 0xF));
addSingleHexChar(out, (byte) ((aChar >> 4) & 0xF));
addSingleHexChar(out, (byte) (aChar & 0xF));
} else {
out.append(aChar);
}
}
}
return out.toString();
}
public static String unicodeUnescapeString(String s) {
int len = s.length();
StringBuilder out = new StringBuilder(len);
for (int x = 0; x < len; x++) {
char ch = s.charAt(x);
if (ch == '\\') {
ch = s.charAt(++x);
if (ch == 'u') {
int value = 0;
for (int i = 0; i < 4; i++) {
ch = s.charAt(++x);
if (ch >= '0' && ch <= '9') {
value = (value << 4) + ch - '0';
} else if (ch >= 'a' && ch <= 'f') {
value = (value << 4) + 10 + ch - 'a';
} else if (ch >= 'A' && ch <= 'F') {
value = (value << 4) + 10 + ch - 'A';
} else throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
}
out.append((char) value);
} else {
if (ch == 't')
ch = '\t';
else if (ch == 'r')
ch = '\r';
else if (ch == 'n')
ch = '\n';
else if (ch == 'f')
ch = '\f';
out.append(ch);
}
} else {
out.append(ch);
}
}
return out.toString();
}
public static <T> Supplier<T> getInstanceSupplier(String className, ClassLoader classLoader) {
return () -> getInstance(className, classLoader);
}
/**
* Deletes directory recursively.
*
* @param directoryName Directory to be deleted
*/
public static void recursiveFileRemove(String directoryName) {
File file = new File(directoryName);
recursiveFileRemove(file);
}
public static void recursiveFileRemove(Path path) {
recursiveFileRemove(path.toFile());
}
/**
* Deletes directory recursively.
*
* @param directory Directory to be deleted
*/
public static void recursiveFileRemove(File directory) {
if (directory.exists()) {
log.tracef("Deleting file %s", directory);
recursiveDelete(directory);
}
}
private static void recursiveDelete(File f) {
try {
Files.walkFileTree(f.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (e == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
throw e;
}
}
});
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static void recursiveDirectoryCopy(Path source, Path target) throws IOException {
Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
try {
if (!source.equals(dir)) {
String relativize = source.relativize(dir).toString();
Path resolve = target.resolve(relativize);
Files.copy(dir, resolve);
}
} catch (FileAlreadyExistsException x) {
// do nothing
} catch (IOException x) {
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.copy(file, target.resolve(source.relativize(file).toString()));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
return FileVisitResult.CONTINUE;
}
});
}
public static char[] toCharArray(String s) {
return s == null ? null : s.toCharArray();
}
public static Object[] objectArray(int length) {
return length == 0 ? EMPTY_OBJECT_ARRAY : new Object[length];
}
public static String[] stringArray(int length) {
return length == 0 ? EMPTY_STRING_ARRAY : new String[length];
}
public static Throwable[] throwableArray(int length) {
return length == 0 ? EMPTY_THROWABLE_ARRAY : new Throwable[length];
}
public static void renameTempFile(File tempFile, File lockFile, File dstFile)
throws IOException {
FileLock lock = null;
try (FileOutputStream lockFileOS = new FileOutputStream(lockFile)) {
lock = lockFileOS.getChannel().lock();
Files.move(tempFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} finally {
if (lock != null && lock.isValid()) {
lock.release();
}
if (!lockFile.delete()) {
log.debugf("Unable to delete lock file %s", lockFile);
}
}
}
public static Throwable getRootCause(Throwable re) {
if (re == null) return null;
Throwable cause = re.getCause();
if (cause != null)
return getRootCause(cause);
else
return re;
}
public static Marshaller getJBossMarshaller(ClassLoader classLoader, ClassAllowList classAllowList) {
try {
Class<?> marshallerClass = classLoader.loadClass(GENERIC_JBOSS_MARSHALLING_CLASS);
return Util.newInstanceOrNull(marshallerClass.asSubclass(Marshaller.class),
new Class[]{ClassLoader.class, ClassAllowList.class}, classLoader, classAllowList);
} catch (ClassNotFoundException e) {
return null;
}
}
// TODO: Replace with Objects.requireNonNullElse(T obj, T defaultObj) when upgrading to JDK 9+
public static <T> T requireNonNullElse(T obj, T defaultObj) {
return (obj != null) ? obj : Objects.requireNonNull(defaultObj, "defaultObj");
}
public static void longToBytes(long val, byte[] array, int offset) {
for (int i = 7; i > 0; i--) {
array[offset + i] = (byte) val;
val >>>= 8;
}
array[offset] = (byte) val;
}
public static String unquote(String s) {
if (s.charAt(0) == '"' || s.charAt(0) == '\'') {
return s.substring(1, s.length() - 1);
} else {
return s;
}
}
public static Object fromString(Class klass, String value) {
if (klass == Character.class) {
if (value.length() == 1) {
return value.charAt(0);
} else {
throw new IllegalArgumentException("Expected a single character, got '" + value + "'");
}
} else if (klass == Byte.class) {
return Byte.valueOf(value);
} else if (klass == Short.class) {
return Short.valueOf(value);
} else if (klass == Integer.class) {
return Integer.valueOf(value);
} else if (klass == Long.class) {
return Long.valueOf(value);
} else if (klass == Boolean.class) {
return parseBoolean(value);
} else if (klass == String.class) {
return value;
} else if (klass == String[].class) {
return value != null ? value.split(" ") : null;
} else if (klass == Set.class) {
return value != null ? new HashSet<>(Arrays.asList(value.split(" "))) : null;
} else if (klass == char[].class) {
return value.toCharArray();
} else if (klass == Float.class) {
return Float.valueOf(value);
} else if (klass == Double.class) {
return Double.valueOf(value);
} else if (klass == BigDecimal.class) {
return new BigDecimal(value);
} else if (klass == BigInteger.class) {
return new BigInteger(value);
} else if (klass == File.class) {
return new File(value);
} else if (klass.isEnum()) {
return parseEnum(klass, value);
} else if (klass == Properties.class) {
try {
Properties props = new Properties();
props.load(new ByteArrayInputStream(value.getBytes()));
return props;
} catch (IOException e) {
throw new CacheConfigurationException("Failed to load Properties from: " + value, e);
}
}
throw new CacheConfigurationException("Cannot convert " + value + " to type " + klass.getName());
}
public static boolean parseBoolean(String value) {
switch (value.toLowerCase()) {
case "true":
case "yes":
case "y":
case "on":
return true;
case "false":
case "no":
case "n":
case "off":
return false;
default:
throw Log.CONFIG.illegalBooleanValue(value);
}
}
public static <T extends Enum<T>> T parseEnum(Class<T> enumClass, String value) {
try {
return Enum.valueOf(enumClass, value);
} catch (IllegalArgumentException e) {
throw Log.CONFIG.illegalEnumValue(value, EnumSet.allOf(enumClass));
}
}
public static void unwrapSuppressed(Throwable t, Throwable t1) {
if (t1.getSuppressed().length > 0) {
for (Throwable suppressed : t1.getSuppressed()) {
t.addSuppressed(suppressed);
}
} else {
t.addSuppressed(t1);
}
}
public static String unwrapExceptionMessage(Throwable t) {
// Avoid duplicate messages
LinkedHashSet<String> messages = new LinkedHashSet<>();
String rootMessage = t.getMessage();
if (rootMessage != null) {
messages.add(rootMessage);
}
for(Throwable suppressed : t.getSuppressed()) {
messages.add(suppressed.getMessage());
}
return String.join("\n ", messages);
}
/**
* Returns the byte at {@code index}.
*/
public interface ByteGetter {
byte get(int index);
}
/**
* This method is to be replaced by Java 9 Arrays#equals with the same arguments.
*
* @param a first array to test contents
* @param aFromIndex the offset into the first array to start comparison
* @param aToIndex the last element (exclusive) of the first array to compare
* @param b second array to test contents
* @param bFromIndex the offset into the second array to start comparison
* @param bToIndex the last element (exclusive) of the second array to compare
* @return if the bytes in the two array ranges are equal
*/
public static boolean arraysEqual(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex) {
int totalAmount = aToIndex - aFromIndex;
if (totalAmount != bToIndex - bFromIndex) {
return false;
}
for (int i = 0; i < totalAmount; ++i) {
if (a[aFromIndex + i] != b[bFromIndex + i]) {
return false;
}
}
return true;
}
public static byte[] concat(byte[] a, byte[] b) {
int aLen = a.length;
int bLen = b.length;
byte[] ret = new byte[aLen + bLen];
System.arraycopy(a, 0, ret, 0, aLen);
System.arraycopy(b, 0, ret, aLen, bLen);
return ret;
}
public static <T> T[] concat(T[] a, T b) {
int aLen = a.length;
T[] ret = Arrays.copyOf(a, aLen + 1);
ret[aLen] = b;
return ret;
}
public static RuntimeException unchecked(Throwable t) {
if (t instanceof RuntimeException) {
return (RuntimeException) t;
} else {
return new RuntimeException(t);
}
}
}
| 41,011
| 33.319665
| 204
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/IntSetsExternalization.java
|
package org.infinispan.commons.util;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.infinispan.commons.io.UnsignedNumeric;
/**
* IntSets externalization mechanism
* @author wburns
* @since 9.3
*/
public class IntSetsExternalization {
private IntSetsExternalization() { }
private static final int RANGESET = 0;
private static final int SMALLINTSET = 1;
private static final int EMPTYSET = 2;
private static final int SINGLETONSET = 3;
private static final int CONCURRENTSET = 4;
private final static Map<Class<?>, Integer> numbers = new HashMap<>(5);
static {
numbers.put(RangeSet.class, RANGESET);
numbers.put(org.infinispan.commons.util.RangeSet.class, RANGESET);
numbers.put(SmallIntSet.class, SMALLINTSET);
numbers.put(EmptyIntSet.class, EMPTYSET);
numbers.put(SingletonIntSet.class, SINGLETONSET);
numbers.put(ConcurrentSmallIntSet.class, CONCURRENTSET);
}
public static void writeTo(ObjectOutput output, IntSet intSet) throws IOException {
int number = numbers.getOrDefault(intSet.getClass(), -1);
output.write(number);
switch (number) {
case RANGESET:
UnsignedNumeric.writeUnsignedInt(output, intSet.size());
break;
case SMALLINTSET:
SmallIntSet.writeTo(output, (SmallIntSet) intSet);
break;
case EMPTYSET:
break;
case SINGLETONSET:
UnsignedNumeric.writeUnsignedInt(output, ((SingletonIntSet) intSet).value);
break;
case CONCURRENTSET:
ConcurrentSmallIntSet.writeTo(output, (ConcurrentSmallIntSet) intSet);
break;
default:
throw new UnsupportedOperationException("Unsupported number: " + number);
}
}
public static IntSet readFrom(ObjectInput input) throws IOException, ClassNotFoundException {
int magicNumber = input.readUnsignedByte();
switch (magicNumber) {
case RANGESET:
return new org.infinispan.commons.util.RangeSet(UnsignedNumeric.readUnsignedInt(input));
case SMALLINTSET:
return SmallIntSet.readFrom(input);
case EMPTYSET:
return EmptyIntSet.getInstance();
case SINGLETONSET:
return new SingletonIntSet(UnsignedNumeric.readUnsignedInt(input));
case CONCURRENTSET:
return ConcurrentSmallIntSet.readFrom(input);
default:
throw new UnsupportedOperationException("Unsupported number: " + magicNumber);
}
}
public static Set<Class<? extends IntSet>> getTypeClasses() {
return Util.asSet(SmallIntSet.class, RangeSet.class, org.infinispan.commons.util.RangeSet.class, EmptyIntSet.class,
SingletonIntSet.class, ConcurrentSmallIntSet.class);
}
}
| 2,928
| 34.289157
| 121
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/concurrent/package-info.java
|
/**
* Provides commons interfaces and classes related to concurrency
*
* @api.public
*/
package org.infinispan.commons.util.concurrent;
| 140
| 19.142857
| 65
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/concurrent/CallerRunsRejectOnShutdownPolicy.java
|
package org.infinispan.commons.util.concurrent;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import org.infinispan.commons.IllegalLifecycleStateException;
/**
* A handler for rejected tasks that runs the rejected task
* directly in the calling thread of the {@code execute} method. If
* the executor was shutdown, it will instead throw a {@link RejectedExecutionException}.
* @author wburns
* @since 10.0
*/
public class CallerRunsRejectOnShutdownPolicy extends ThreadPoolExecutor.AbortPolicy {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
throw new IllegalLifecycleStateException();
}
r.run();
}
}
| 770
| 31.125
| 89
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/concurrent/CacheBackpressureFullException.java
|
package org.infinispan.commons.util.concurrent;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.util.TimedThreadDump;
/**
* A {@link CacheException} that is thrown when the backpressure has been filled an unable to process the request. This
* can be thrown during periods where too much concurrency was requested or the load from an external source is too
* high. This can be remedied by reducing the load or increasing the backpressure handling (usually buffering of some sort).
*/
public class CacheBackpressureFullException extends CacheException {
public CacheBackpressureFullException() {
TimedThreadDump.generateThreadDump();
}
}
| 683
| 39.235294
| 124
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/concurrent/NonReentrantLock.java
|
package org.infinispan.commons.util.concurrent;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* A simplistic non-reentrant lock that does not use ownership by thread.
*/
public final class NonReentrantLock implements Lock {
private final Lock inner = new ReentrantLock();
private Condition condition;
@Override
public synchronized void lock() {
inner.lock();
try {
if (condition == null) {
condition = inner.newCondition();
} else {
condition.awaitUninterruptibly();
}
} finally {
inner.unlock();
}
}
@Override
public void lockInterruptibly() throws InterruptedException {
inner.lockInterruptibly();
try {
if (condition == null) {
condition = inner.newCondition();
} else {
condition.await();
}
} finally {
inner.unlock();
}
}
@Override
public boolean tryLock() {
if (inner.tryLock()) {
try {
if (condition == null) {
condition = inner.newCondition();
return true;
}
} finally {
inner.unlock();
}
}
return false;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
long deadline = System.currentTimeMillis() + unit.toMillis(time);
if (inner.tryLock(time, unit)) {
try {
while (condition != null) {
long now = System.currentTimeMillis();
if (now >= deadline) {
return false;
}
condition.await(deadline - now, TimeUnit.MILLISECONDS);
return true;
}
condition = inner.newCondition();
} finally {
inner.unlock();
}
}
return false;
}
@Override
public void unlock() {
inner.lock();
try {
condition.signalAll();
condition = null;
} finally {
inner.unlock();
}
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException();
}
}
| 2,313
| 23.357895
| 81
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/concurrent/CompletableFutures.java
|
package org.infinispan.commons.util.concurrent;
import static java.util.Objects.requireNonNull;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.infinispan.commons.CacheException;
/**
* Utility methods connecting {@link CompletableFuture} futures.
*
* @author Dan Berindei
* @since 8.0
*/
public final class CompletableFutures {
public static final CompletableFuture[] EMPTY_ARRAY = new CompletableFuture[0];
private static final CompletableFuture<Boolean> completedTrueFuture = CompletableFuture.completedFuture(Boolean.TRUE);
private static final CompletableFuture<Boolean> completedFalseFuture = CompletableFuture.completedFuture(Boolean.FALSE);
private static final CompletableFuture<?> completedEmptyMapFuture = CompletableFuture.completedFuture(Collections.emptyMap());
private static final CompletableFuture<?> completedNullFuture = CompletableFuture.completedFuture(null);
private static final long BIG_DELAY_NANOS = TimeUnit.DAYS.toNanos(1);
private static final Function<?, ?> TO_NULL = o -> null;
private static final Function<?, Boolean> TO_TRUE_FUNCTION = o -> Boolean.TRUE;
private static final Function<?, ?> identity = t -> t;
private CompletableFutures() {
}
@SuppressWarnings("unchecked")
public static <K, V> CompletableFuture<Map<K, V>> completedEmptyMap() {
return (CompletableFuture<Map<K, V>>) completedEmptyMapFuture;
}
@SuppressWarnings("unchecked")
public static <T> CompletableFuture<T> completedNull() {
return (CompletableFuture<T>) completedNullFuture;
}
public static CompletableFuture<Boolean> completedTrue() {
return completedTrueFuture;
}
public static CompletableFuture<Boolean> completedFalse() {
return completedFalseFuture;
}
public static CompletionStage<Boolean> booleanStage(boolean trueOrFalse) {
return trueOrFalse ? completedTrueFuture : completedFalseFuture;
}
public static <T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> futures) {
CompletableFuture<Void> all = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
return all.thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList()));
}
/**
* It waits until the {@link CompletableFuture} is completed.
* <p>
* It ignore if the {@link CompletableFuture} is completed normally or exceptionally.
*
* @param future the {@link CompletableFuture} to test.
* @param time the timeout.
* @param unit the timeout unit.
* @return {@code true} if completed, {@code false} if timed out.
* @throws InterruptedException if interrupted while waiting.
* @throws NullPointerException if {@code future} or {@code unit} is {@code null}.
*/
public static boolean await(CompletableFuture<?> future, long time, TimeUnit unit) throws InterruptedException {
try {
requireNonNull(future, "Completable Future must be non-null.").get(time, requireNonNull(unit, "Time Unit must be non-null"));
return true;
} catch (ExecutionException e) {
return true;
} catch (java.util.concurrent.TimeoutException e) {
return false;
}
}
/**
* Same as {@link #await(CompletableFuture, long, TimeUnit)} but wraps checked exceptions in {@link CacheException}
*
* @param future the {@link CompletableFuture} to test.
* @param time the timeout.
* @param unit the timeout unit.
* @return {@code true} if completed, {@code false} if timed out.
* @throws NullPointerException if {@code future} or {@code unit} is {@code null}.
*/
public static boolean uncheckedAwait(CompletableFuture<?> future, long time, TimeUnit unit) {
try {
requireNonNull(future, "Completable Future must be non-null.").get(time, requireNonNull(unit, "Time Unit must be non-null"));
return true;
} catch (ExecutionException e) {
return true;
} catch (java.util.concurrent.TimeoutException e) {
return false;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CacheException(e);
}
}
/**
* Wait for a long time until the {@link CompletableFuture} is completed.
*
* @param future the {@link CompletableFuture}.
* @param <T> the return type.
* @return the result value.
* @throws ExecutionException if the {@link CompletableFuture} completed exceptionally.
* @throws InterruptedException if the current thread was interrupted while waiting.
*/
public static <T> T await(CompletableFuture<T> future) throws ExecutionException, InterruptedException {
try {
return Objects.requireNonNull(future, "Completable Future must be non-null.").get(BIG_DELAY_NANOS, TimeUnit.NANOSECONDS);
} catch (java.util.concurrent.TimeoutException e) {
throw new IllegalStateException("This should never happen!", e);
}
}
/**
* Same as {@link #await(CompletableFuture)} but wraps checked exceptions in {@link CacheException}
*
* @param future the {@link CompletableFuture}.
* @param <T> the return type.
* @return the result value.
*/
public static <T> T uncheckedAwait(CompletableFuture<T> future) {
try {
return Objects.requireNonNull(future, "Completable Future must be non-null.").get(BIG_DELAY_NANOS, TimeUnit.NANOSECONDS);
} catch (java.util.concurrent.TimeoutException e) {
throw new IllegalStateException("This should never happen!", e);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CacheException(e);
} catch (ExecutionException e) {
throw new CacheException(e);
}
}
public static CompletionException asCompletionException(Throwable t) {
if (t instanceof CompletionException) {
return ((CompletionException) t);
} else {
return new CompletionException(t);
}
}
public static void rethrowExceptionIfPresent(Throwable t) {
if (t != null) {
throw asCompletionException(t);
}
}
public static Throwable extractException(Throwable t) {
Throwable cause = t.getCause();
if (cause != null && t instanceof CompletionException) {
return cause;
}
return t;
}
public static <T, R> Function<T, R> toNullFunction() {
//noinspection unchecked
return (Function<T, R>) TO_NULL;
}
public static <T> Function<T, Boolean> toTrueFunction() {
//noinspection unchecked
return (Function<T, Boolean>) TO_TRUE_FUNCTION;
}
public static <T> Function<T, T> identity() {
//noinspection unchecked
return (Function<T, T>) identity;
}
}
| 7,144
| 37.208556
| 134
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/concurrent/NonBlockingRejectedExecutionHandler.java
|
package org.infinispan.commons.util.concurrent;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.commons.executors.NonBlockingResource;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* A handler for rejected tasks that runs the task if the current thread is a non blocking thread otherwise it
* blocks until the task can be added to the underlying queue
* @author wburns
* @since 10.1
*/
public class NonBlockingRejectedExecutionHandler implements RejectedExecutionHandler {
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private NonBlockingRejectedExecutionHandler() { }
private static final NonBlockingRejectedExecutionHandler INSTANCE = new NonBlockingRejectedExecutionHandler();
public static RejectedExecutionHandler getInstance() {
return INSTANCE;
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
throw new IllegalLifecycleStateException();
}
Thread currentThread = Thread.currentThread();
if (currentThread.getThreadGroup() instanceof NonBlockingResource) {
r.run();
} else {
if (log.isTraceEnabled()) {
log.tracef("Current thread will wait until task %s is placed into the queue of %s", r, executor);
}
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
currentThread.interrupt();
throw new CacheException(e);
}
}
}
}
| 1,812
| 34.54902
| 113
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/concurrent/BlockingRejectedExecutionHandler.java
|
package org.infinispan.commons.util.concurrent;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.commons.executors.NonBlockingResource;
import org.infinispan.commons.logging.Log;
import org.infinispan.commons.logging.LogFactory;
/**
* A handler for rejected tasks that runs the task if the current thread is a blocking thread otherwise it
* rejects the task.
* @author wburns
* @since 10.1
*/
public class BlockingRejectedExecutionHandler implements RejectedExecutionHandler {
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private BlockingRejectedExecutionHandler() { }
private static final BlockingRejectedExecutionHandler INSTANCE = new BlockingRejectedExecutionHandler();
public static BlockingRejectedExecutionHandler getInstance() {
return INSTANCE;
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
rejectedExecution(r, (ExecutorService) executor);
}
public void rejectedExecution(Runnable r, ExecutorService executor) {
if (executor.isShutdown()) {
throw new IllegalLifecycleStateException();
}
if (Thread.currentThread().getThreadGroup() instanceof NonBlockingResource) {
if (log.isTraceEnabled()) {
log.tracef("Task %s was rejected from %s when submitted from non blocking thread", r, executor);
}
throw new CacheBackpressureFullException();
} else {
r.run();
}
}
}
| 1,715
| 34.020408
| 108
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/concurrent/StripedCounters.java
|
package org.infinispan.commons.util.concurrent;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
import java.util.function.Supplier;
import org.infinispan.commons.util.ProcessorInfo;
/**
* Duplicates a set of counters in a set of stripes, so that multiple threads can increment those counters without too
* much contention.
* <p>
* Callers must first obtain a stripe for the current thread with {@link #stripeForCurrentThread()}, then use {@link
* #increment(AtomicLongFieldUpdater, Object)} or {@link #add(AtomicLongFieldUpdater, Object, long)} to update one or
* more counters in that stripe. They must also provide a {@link AtomicLongFieldUpdater} to access a specific counter in
* the stripe - it should be defined as {@code static final} so that it can be inlined by the JIT.
*
* @author Dan Berindei
* @since 9.0
*/
public final class StripedCounters<T> {
private static final int STRIPE_COUNT = (int) (Long.highestOneBit(ProcessorInfo.availableProcessors()) << 1);
private static final int STRIPE_MASK = STRIPE_COUNT - 1;
@SuppressWarnings("unchecked")
private final T[] stripes = (T[]) new Object[STRIPE_COUNT];
public StripedCounters(Supplier<T> stripeSupplier) {
for (int i = 0; i < stripes.length; i++) {
stripes[i] = stripeSupplier.get();
}
}
public void increment(AtomicLongFieldUpdater<T> updater, T stripe) {
updater.getAndIncrement(stripe);
}
public void add(AtomicLongFieldUpdater<T> updater, T stripe, long delta) {
updater.getAndAdd(stripe, delta);
}
public long get(AtomicLongFieldUpdater<T> updater) {
long sum = 0;
for (T stripe : stripes) {
sum += updater.get(stripe);
}
return sum;
}
public void reset(AtomicLongFieldUpdater<T> updater) {
for (T stripe : stripes) {
updater.set(stripe, 0);
}
}
public T stripeForCurrentThread() {
return stripes[threadIndex()];
}
private int threadIndex() {
// Spread the thread id a bit, in case it's always a multiple of 16
long id = Thread.currentThread().getId();
id ^= id >>> 7 ^ id >>> 4;
return (int) (id & STRIPE_MASK);
}
}
| 2,192
| 32.227273
| 120
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/concurrent/LifecycleRejectedExecutionHandler.java
|
package org.infinispan.commons.util.concurrent;
import java.util.concurrent.ThreadPoolExecutor;
import org.infinispan.commons.IllegalLifecycleStateException;
/**
* A handler for rejected tasks that always throws a {@link IllegalLifecycleStateException}.
* @author wburns
* @since 11.0
*/
public class LifecycleRejectedExecutionHandler extends ThreadPoolExecutor.AbortPolicy {
private LifecycleRejectedExecutionHandler() { }
private static final LifecycleRejectedExecutionHandler INSTANCE = new LifecycleRejectedExecutionHandler();
public static LifecycleRejectedExecutionHandler getInstance() {
return INSTANCE;
}
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
throw new IllegalLifecycleStateException();
}
super.rejectedExecution(r, executor);
}
}
| 878
| 29.310345
| 109
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/util/logging/TraceException.java
|
package org.infinispan.commons.util.logging;
/**
* This exception is used to add stack trace information to exceptions as they move from one thread to another.
*
* @author Dan Berindei
* @since 9.3
*/
public class TraceException extends Exception {
public TraceException() {
}
}
| 291
| 21.461538
| 111
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/executors/package-info.java
|
/**
* Commons Executors package
*
* @api.public
*/
package org.infinispan.commons.executors;
| 97
| 13
| 41
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/executors/ScheduledThreadPoolExecutorFactory.java
|
package org.infinispan.commons.executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import org.infinispan.commons.util.concurrent.LifecycleRejectedExecutionHandler;
/**
* @author Galder Zamarreño
*/
public enum ScheduledThreadPoolExecutorFactory implements ThreadPoolExecutorFactory<ScheduledExecutorService> {
INSTANCE;
@Override
public ScheduledExecutorService createExecutor(ThreadFactory factory) {
ScheduledThreadPoolExecutor result = new ScheduledThreadPoolExecutor(1, factory,
LifecycleRejectedExecutionHandler.getInstance());
result.setRemoveOnCancelPolicy(true);
return result;
}
@Override
public void validate() {
// No-op
}
public static ScheduledThreadPoolExecutorFactory create() {
return INSTANCE;
}
}
| 906
| 26.484848
| 111
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/executors/ExecutorFactory.java
|
package org.infinispan.commons.executors;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
/**
* Used to configure and create executors
*
* @author Manik Surtani
* @since 4.0
*/
public interface ExecutorFactory {
ExecutorService getExecutor(Properties p);
}
| 293
| 18.6
| 45
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/executors/NonBlockingResource.java
|
package org.infinispan.commons.executors;
/**
* Interface to designate the resource is a non blocking one
* @author wburns
* @since 11.0
*/
public interface NonBlockingResource {
}
| 186
| 17.7
| 60
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/executors/CachedThreadPoolExecutorFactory.java
|
package org.infinispan.commons.executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* @author Galder Zamarreño
*/
public enum CachedThreadPoolExecutorFactory implements ThreadPoolExecutorFactory<ExecutorService> {
INSTANCE;
@Override
public ExecutorService createExecutor(ThreadFactory factory) {
return Executors.newCachedThreadPool(factory);
}
@Override
public void validate() {
// No-op
}
public static CachedThreadPoolExecutorFactory create() {
return INSTANCE;
}
}
| 612
| 20.892857
| 99
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/executors/ThreadPoolExecutorFactory.java
|
package org.infinispan.commons.executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
/**
* @author Galder Zamarreño
*/
public interface ThreadPoolExecutorFactory<T extends ExecutorService> {
T createExecutor(ThreadFactory factory);
/**
* Validate parameters for the thread pool executor factory
*/
void validate();
default boolean createsNonBlockingThreads() {
return false;
}
}
| 460
| 19.954545
| 71
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/executors/BlockingThreadPoolExecutorFactory.java
|
package org.infinispan.commons.executors;
import static org.infinispan.commons.logging.Log.CONFIG;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.infinispan.commons.util.concurrent.BlockingRejectedExecutionHandler;
import org.infinispan.commons.util.concurrent.NonBlockingRejectedExecutionHandler;
/**
* @author Galder Zamarreño
* @deprecated since 12.0 with no replacement
*/
@Deprecated
public class BlockingThreadPoolExecutorFactory implements ThreadPoolExecutorFactory<ExecutorService> {
public static final int DEFAULT_KEEP_ALIVE_MILLIS = 60000;
private final int maxThreads;
private final int coreThreads;
private final int queueLength;
private final long keepAlive;
private final boolean nonBlocking;
public BlockingThreadPoolExecutorFactory(int maxThreads, int coreThreads, int queueLength, long keepAlive) {
this(maxThreads, coreThreads, queueLength, keepAlive, false);
}
public BlockingThreadPoolExecutorFactory(int maxThreads, int coreThreads, int queueLength, long keepAlive,
boolean nonBlocking) {
this.maxThreads = maxThreads;
this.coreThreads = coreThreads;
this.queueLength = queueLength;
this.keepAlive = keepAlive;
this.nonBlocking = nonBlocking;
}
public int maxThreads() {
return maxThreads;
}
public int coreThreads() {
return coreThreads;
}
public int queueLength() {
return queueLength;
}
public long keepAlive() {
return keepAlive;
}
@Override
public boolean createsNonBlockingThreads() {
return nonBlocking;
}
@Override
public ExecutorService createExecutor(ThreadFactory threadFactory) {
BlockingQueue<Runnable> queue = queueLength == 0 ? new SynchronousQueue<>() : new LinkedBlockingQueue<>(queueLength);
if (nonBlocking) {
if (!(threadFactory instanceof NonBlockingResource)) {
throw new IllegalStateException("Executor factory configured to be non blocking and received a thread" +
" factory that can create blocking threads!");
}
}
return new ThreadPoolExecutor(coreThreads, maxThreads, keepAlive,
TimeUnit.MILLISECONDS, queue, threadFactory,
nonBlocking ? NonBlockingRejectedExecutionHandler.getInstance() : BlockingRejectedExecutionHandler.getInstance());
}
@Override
public void validate() {
if (coreThreads < 0)
throw CONFIG.illegalValueThreadPoolParameter("core threads", ">= 0");
if (maxThreads <= 0)
throw CONFIG.illegalValueThreadPoolParameter("max threads", "> 0");
if (maxThreads < coreThreads)
throw CONFIG.illegalValueThreadPoolParameter(
"max threads and core threads", "max threads >= core threads");
if (keepAlive < 0)
throw CONFIG.illegalValueThreadPoolParameter("keep alive time", ">= 0");
if (queueLength < 0)
throw CONFIG.illegalValueThreadPoolParameter("work queue length", ">= 0");
}
@Override
public String toString() {
return "BlockingThreadPoolExecutorFactory{" +
"maxThreads=" + maxThreads +
", coreThreads=" + coreThreads +
", queueLength=" + queueLength +
", keepAlive=" + keepAlive +
'}';
}
public static BlockingThreadPoolExecutorFactory create(int maxThreads, int queueSize, boolean nonBlocking) {
int coreThreads = queueSize == 0 ? 1 : maxThreads;
return new BlockingThreadPoolExecutorFactory(maxThreads, coreThreads, queueSize, DEFAULT_KEEP_ALIVE_MILLIS,
nonBlocking);
}
}
| 3,884
| 32.491379
| 126
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/executors/BlockingResource.java
|
package org.infinispan.commons.executors;
/**
* Interface to designate the resource is a blocking one.
* @author wburns
* @since 11.0
*/
public interface BlockingResource {
}
| 180
| 17.1
| 57
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/jmx/package-info.java
|
/**
* Pluggable lookup for MBeanServer.
*
* @api.public
*/
package org.infinispan.commons.jmx;
| 99
| 13.285714
| 36
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/jmx/MBeanServerLookup.java
|
package org.infinispan.commons.jmx;
import java.util.Properties;
import javax.management.MBeanServer;
/**
* Implementors of this should return an MBeanServer to which MBeans will be registered.
*
* @author Mircea.Markus@jboss.com
* @see org.infinispan.commons.jmx.PlatformMBeanServerLookup
* @since 4.0
*/
public interface MBeanServerLookup {
/**
* Retrieves an {@link MBeanServer} instance.
*
* @param properties optional properties (can be null) to configure the MBeanServer instance
* @return an MBeanServer instance
*/
MBeanServer getMBeanServer(Properties properties);
default MBeanServer getMBeanServer() {
return getMBeanServer(null);
}
}
| 695
| 23.857143
| 95
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/jmx/PlatformMBeanServerLookup.java
|
package org.infinispan.commons.jmx;
import java.lang.management.ManagementFactory;
import java.util.Properties;
import javax.management.MBeanServer;
/**
* Default implementation for {@link MBeanServerLookup}, will return the platform MBean server.
* <p/>
* Note: to enable platform MBeanServer the following system property should be passed to the Sun JVM:
* <b>-Dcom.sun.management.jmxremote</b>.
*
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class PlatformMBeanServerLookup implements MBeanServerLookup {
@Override
public MBeanServer getMBeanServer(Properties properties) {
return ManagementFactory.getPlatformMBeanServer();
}
}
| 671
| 27
| 102
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/time/DefaultTimeService.java
|
package org.infinispan.commons.time;
import java.time.Clock;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
/**
* The default implementation of {@link TimeService}. It does not perform any optimization and relies on {@link
* System#currentTimeMillis()} and {@link System#nanoTime()}.
*
* @author Pedro Ruivo
* @since 5.3
*/
public class DefaultTimeService implements TimeService {
public static final DefaultTimeService INSTANCE = new DefaultTimeService();
private final Clock clock;
public DefaultTimeService() {
this.clock = Clock.systemUTC();
}
@Override
public long wallClockTime() {
return System.currentTimeMillis();
}
@Override
public long time() {
return System.nanoTime();
}
@Override
public Instant instant() {
return clock.instant();
}
@Override
public long timeDuration(long startTimeNanos, TimeUnit outputTimeUnit) {
return timeDuration(startTimeNanos, time(), outputTimeUnit);
}
@Override
public long timeDuration(long startTimeNanos, long endTimeNanos, TimeUnit outputTimeUnit) {
long remaining = endTimeNanos - startTimeNanos;
if (remaining <= 0) {
return 0;
}
return outputTimeUnit.convert(remaining, TimeUnit.NANOSECONDS);
}
@Override
public boolean isTimeExpired(long endTimeNanos) {
return time() - endTimeNanos >= 0;
}
@Override
public long remainingTime(long endTimeNanos, TimeUnit outputTimeUnit) {
long remaining = endTimeNanos - time();
return remaining <= 0 ? 0 : outputTimeUnit.convert(remaining, TimeUnit.NANOSECONDS);
}
@Override
public long expectedEndTime(long duration, TimeUnit inputTimeUnit) {
if (duration <= 0) {
return time();
}
return time() + inputTimeUnit.toNanos(duration);
}
}
| 1,847
| 24.666667
| 111
|
java
|
null |
infinispan-main/commons/all/src/main/java/org/infinispan/commons/time/TimeService.java
|
package org.infinispan.commons.time;
import java.time.Instant;
import java.util.concurrent.TimeUnit;
/**
* Encapsulates all the time related logic in this interface.
*
* @author Pedro Ruivo
* @since 5.3
*/
public interface TimeService {
/**
* @return the current clock time in milliseconds. Note that it depends of the system time.
*/
long wallClockTime();
/**
* @return the current cpu time in nanoseconds. Note that some platforms do not provide nanosecond precision.
*/
long time();
/**
* @return the current {@link Instant}. Similarly to {@link #time()}, note that some platforms do not provide nanosecond precision.
*/
Instant instant();
/**
* It is equivalent to {@code timeDuration(startTime, time(), outputTimeUnit)}.
*
* @param startTimeNanos start cpu time in nanoseconds, usually returned by {@link #time()}.
* @param outputTimeUnit the {@link TimeUnit} of the returned value.
* @return the duration between the current cpu time and startTime. It returns zero if startTime is less than zero or
* if startTime is greater than the current cpu time.
*/
long timeDuration(long startTimeNanos, TimeUnit outputTimeUnit);
/**
* @param startTimeNanos start cpu time in nanoseconds, usually returned by {@link #time()}.
* @param endTimeNanos end cpu time in nanoseconds, usually returned by {@link #time()}.
* @param outputTimeUnit the {@link TimeUnit} of the returned value.
* @return the duration between the endTime and startTime. It returns zero if startTime or endTime are less than zero
* or if startTime is greater than the endTime.
*/
long timeDuration(long startTimeNanos, long endTimeNanos, TimeUnit outputTimeUnit);
/**
* @param endTimeNanos a cpu time in nanoseconds, usually returned by {@link #time()}
* @return {@code true} if the endTime is less or equals than the current cpu time.
*/
boolean isTimeExpired(long endTimeNanos);
/**
* @param endTimeNanos the end cpu time in nanoseconds.
* @param outputTimeUnit the {@link TimeUnit} of the returned value.
* @return the remaining cpu time until the endTime is reached.
*/
long remainingTime(long endTimeNanos, TimeUnit outputTimeUnit);
/**
* @param duration the duration.
* @param inputTimeUnit the {@link TimeUnit} of the duration.
* @return the expected end time in nano seconds. If duration is less or equals to zero, the current cpu time is returned ({@link
* #time()}).
*/
long expectedEndTime(long duration, TimeUnit inputTimeUnit);
}
| 2,629
| 36.571429
| 134
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.