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-test/src/main/java/org/infinispan/commons/test/CommonsTestBlockHoundIntegration.java
package org.infinispan.commons.test; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.kohsuke.MetaInfServices; import reactor.blockhound.BlockHound; import reactor.blockhound.integration.BlockHoundIntegration; @SuppressWarnings("unused") @MetaInfServices public class CommonsTestBlockHoundIntegration implements BlockHoundIntegration { @Override public void applyTo(BlockHound.Builder builder) { // Allow for various threads to determine blocking dynamically - which means the below non blocking predicate // will be evaluated each time a blocking operation is found on these threads builder.addDynamicThreadPredicate(t -> // TestNG may be started on main thread and load this before renaming to testng t.getName().startsWith("main") || // The threads our tests run on directly t.getName().startsWith("testng") || // These threads are part of AbstractInfinispanTest#testExecutor and fork methods t.getName().startsWith("ForkThread")); builder.nonBlockingThreadPredicate(threadPredicate -> threadPredicate.or(t -> { return BlockHoundHelper.currentThreadRequiresNonBlocking(); })); // Let any test suite progress stuff block registerAllPublicMethodsOnClass(builder, TestSuiteProgress.class); builder.markAsBlocking(BlockHoundHelper.class, "blockingConsume", "(Ljava/lang/Object;)V"); } // This is a duplicate of CommonsBlockHoundIntegration - but unfortunately neither can reference each other // as commons doesn't rely on commons-test, only the commons test jar private static void registerAllPublicMethodsOnClass(BlockHound.Builder builder, Class<?> clazz) { Method[] methods = clazz.getMethods(); for (Method method : methods) { if (Modifier.isPublic(method.getModifiers())) { builder.allowBlockingCallsInside(clazz.getName(), method.getName()); } } } }
1,992
41.404255
115
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/ThrowableSupplier.java
package org.infinispan.commons.test; /** * Supplier that can throw any exception. * * @author Tristan Tarrant * @since 10.0 */ @FunctionalInterface public interface ThrowableSupplier<T> { T get() throws Throwable; }
225
16.384615
41
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/TestNGTestListener.java
package org.infinispan.commons.test; import java.util.Arrays; import org.jboss.logging.Logger; import org.testng.IConfigurationListener2; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import org.testng.annotations.Test; /** * Logs TestNG test progress. */ public class TestNGTestListener implements ITestListener, IConfigurationListener2, ISuiteListener { private static final Logger log = Logger.getLogger(TestNGTestListener.class); private final TestSuiteProgress progressLogger; public TestNGTestListener() { progressLogger = new TestSuiteProgress(); } @Override public void onTestStart(ITestResult result) { progressLogger.testStarted(testName(result)); } @Override public void onTestSuccess(ITestResult result) { progressLogger.testSucceeded(testName(result)); } @Override public void onTestFailure(ITestResult result) { progressLogger.testFailed(testName(result), result.getThrowable()); } @Override public void onTestSkipped(ITestResult result) { // Unregister thread in case the method threw a SkipException RunningTestsRegistry.unregisterThreadWithTest(); progressLogger.testIgnored(testName(result)); } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { progressLogger.testFailed(testName(result), result.getThrowable()); } @Override public void onStart(ITestContext context) { Thread.currentThread().setName("testng-" + context.getName()); ThreadLeakChecker.testStarted(context.getCurrentXmlTest().getXmlClasses().get(0).getName()); } @Override public void onFinish(ITestContext context) { String testName = context.getCurrentXmlTest().getXmlClasses().get(0).getName(); // Mark the test as finished. The actual leak check is in TestNGSuiteChecksTest ThreadLeakChecker.testFinished(testName); } private String testName(ITestResult res) { StringBuilder result = new StringBuilder(); // We prefer using the instance name, in case it's customized, // but when running JUnit tests, TestNG sets the instance name to `methodName(className)` if (res.getInstanceName().contains(res.getMethod().getMethodName())) { result.append(res.getTestClass().getName()); } else { result.append(res.getInstanceName()); } result.append(".").append(res.getMethod().getMethodName()); if (res.getMethod().getConstructorOrMethod().getMethod().isAnnotationPresent(Test.class)) { String dataProviderName = res.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class) .dataProvider(); // Add parameters for methods that use a data provider only if (res.getParameters().length != 0 && !dataProviderName.isEmpty()) { result.append("(").append(Arrays.deepToString(res.getParameters())).append(")"); } } return result.toString(); } @Override public void onStart(ISuite suite) { try { Class.forName("reactor.blockhound.BlockHound"); log.info("BlockHound on classpath, installing non blocking checks!"); BlockHoundHelper.installBlockHound(); } catch (ClassNotFoundException e) { log.info("BlockHound not on classpath, not enabling"); } ThreadLeakChecker.saveInitialThreads(); } @Override public void onFinish(ISuite suite) { ThreadLeakChecker.checkForLeaks(suite.getName()); } @Override public void beforeConfiguration(ITestResult testResult) { progressLogger.configurationStarted(testName(testResult)); String simpleName = testResult.getTestClass().getRealClass().getSimpleName(); RunningTestsRegistry.registerThreadWithTest(testName(testResult), simpleName); } @Override public void onConfigurationSuccess(ITestResult testResult) { RunningTestsRegistry.unregisterThreadWithTest(); progressLogger.configurationFinished(testName(testResult)); } @Override public void onConfigurationFailure(ITestResult testResult) { RunningTestsRegistry.unregisterThreadWithTest(); if (testResult.getThrowable() != null) { progressLogger.configurationFailed(testName(testResult), testResult.getThrowable()); } } @Override public void onConfigurationSkip(ITestResult testResult) { // Unregister thread in case the configuration method threw a SkipException RunningTestsRegistry.unregisterThreadWithTest(); if (testResult.getThrowable() != null) { progressLogger.testIgnored(testName(testResult)); } } }
4,753
34.214815
113
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/TestSuiteProgress.java
package org.infinispan.commons.test; import static org.infinispan.commons.test.Ansi.CYAN; import static org.infinispan.commons.test.Ansi.GREEN; import static org.infinispan.commons.test.Ansi.RED; import static org.infinispan.commons.test.Ansi.RESET; import static org.infinispan.commons.test.Ansi.YELLOW; import java.io.PrintStream; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.logging.Logger; /** * Helper class for test listeners. * * @author Dan Berindei * @since 9.0 */ public class TestSuiteProgress { private static final Logger log = Logger.getLogger(TestSuiteProgress.class); private final AtomicInteger failed = new AtomicInteger(0); private final AtomicInteger succeeded = new AtomicInteger(0); private final AtomicInteger skipped = new AtomicInteger(0); private final PrintStream out; public TestSuiteProgress() { // Use a system property to avoid color out = System.out; } void testStarted(String name) { String message = "Test starting: " + name; progress(message); log.info(message); } void testSucceeded(String name) { succeeded.incrementAndGet(); String message = "Test succeeded: " + name; progress(GREEN, message); log.info(message); } void testFailed(String name, Throwable exception) { failed.incrementAndGet(); String message = "Test failed: " + name; progress(RED, message, exception); log.error(message, exception); } void testIgnored(String name) { skipped.incrementAndGet(); String message = "Test ignored: " + name; progress(YELLOW, message); log.info(message); } void testAssumptionFailed(String name, Throwable exception) { skipped.incrementAndGet(); String message = "Test assumption failed: " + name; progress(YELLOW, message, exception); log.info(message, exception); } void configurationStarted(String name) { log.debug("Test configuration started: " + name); } void configurationFinished(String name) { log.debug("Test configuration finished: " + name); } void configurationFailed(String name, Throwable exception) { failed.incrementAndGet(); String message = "Test configuration failed: " + name; progress(RED, message, exception); log.error(message, exception); } /** * Write a fake test failures in the test-failures log, for {@code process_trace_logs.sh} */ public static void fakeTestFailure(String name, Throwable exception) { String message = "Test failed: " + name; System.out.printf("[TestSuiteProgress] %s%n", message); log.error(message, exception); } public static void printTestJDKInformation() { String message = "Running tests with JDK " + System.getProperty("java.version"); System.out.println(message); log.info(message); } private void progress(CharSequence message) { progress(null, message, null); } private void progress(String color, CharSequence message) { progress(color, message, null); } private synchronized void progress(String color, CharSequence message, Throwable t) { String actualColor = ""; String reset = ""; String okColor = ""; String koColor = ""; String skipColor = ""; if (Ansi.useColor && color != null) { actualColor = color; reset = RESET; if (succeeded.get() > 0) { okColor = GREEN; } if (failed.get() > 0) { okColor = RED; } if (skipped.get() > 0) { skipColor = CYAN; } } // Must format explicitly, see SUREFIRE-1814 out.println(String.format("[%sOK: %5s%s, %sKO: %5s%s, %sSKIP: %5s%s] %s%s%s", okColor, succeeded.get(), reset, koColor, failed.get(), reset, skipColor, skipped.get(), reset, actualColor, message, reset)); if (t != null) { t.printStackTrace(out); } } }
3,997
29.287879
210
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/TestResourceTracker.java
package org.infinispan.commons.test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.logging.Logger; /** * Keeps track of resources created by tests and cleans them up at the end of the test. * * @author Dan Berindei * @since 7.0 */ public class TestResourceTracker { private static final Logger log = Logger.getLogger(TestResourceTracker.class); private static final ConcurrentMap<String, TestResources> testResources = new ConcurrentHashMap<>(); // Inheritable to allow for tests that spawn a thread to keep the test thread name of the original private static final ThreadLocal<String> threadTestName = new InheritableThreadLocal<>(); public static void addResource(String testName, final Cleaner<?> cleaner) { TestResources resources = getTestResources(testName); resources.addResource(cleaner); } /** * Add a resource to the current thread's running test. */ public static void addResource(Cleaner<?> cleaner) { String testName = getCurrentTestName(); addResource(testName, cleaner); } public static void cleanUpResources(String testName) { TestResources resources = testResources.remove(testName); if (resources != null) { for (Cleaner<?> cleaner : resources.getCleaners()) { try { cleaner.close(); } catch (Throwable t) { log.fatalf(t, "Error cleaning resource %s for test %s", cleaner.ref, testName); throw new IllegalStateException("Error cleaning resource " + cleaner.ref + " for test " + testName, t); } } } } public static String getCurrentTestShortName() { String currentTestName = TestResourceTracker.getCurrentTestName(); return getTestResources(currentTestName).getShortName(); } public static String getCurrentTestName() { String testName = threadTestName.get(); if (testName == null) { // Either we're running from within the IDE or it's a // @Test(timeOut=nnn) test. We rely here on some specific TestNG // thread naming convention which can break, but TestNG offers no // other alternative. It does not offer any callbacks within the // thread that runs the test that can timeout. String threadName = Thread.currentThread().getName(); if (threadName.equals("main") || threadName.equals("TestNG")) { // Regular test, force the user to extend AbstractInfinispanTest throw new IllegalStateException("Test name is not set! Please extend AbstractInfinispanTest!"); } else if (threadName.startsWith("TestNGInvoker-")) { // This is a timeout test, so force the user to call our marking method throw new IllegalStateException("Test name is not set! Please call TestResourceTracker.testThreadStarted(this.getTestName()) in your test method!"); } else { throw new IllegalStateException("Test name is not set! Please call TestResourceTracker.testThreadStarted(this.getTestName()) in thread " + threadName + " !"); } } return testName; } /** * Called on the "main" test thread, before any configuration method. */ public static void testStarted(String testName) { if (testResources.containsKey(testName)) { throw new IllegalStateException("Two tests with the same name running in parallel: " + testName); } setThreadTestName(testName); Thread.currentThread().setName(getNextTestThreadName()); } /** * Called on the "main" test thread, after any configuration method. */ public static void testFinished(String testName) { cleanUpResources(testName); if (!testName.equals(threadTestName.get())) { cleanUpResources(getCurrentTestName()); throw new IllegalArgumentException("Current thread's test name was not set correctly: " + getCurrentTestName() + ", should have been " + testName); } setThreadTestName(null); } /** * Should be called by the user on any "background" test thread that creates resources, e.g. at the beginning of a * test with a {@code @Test(timeout=n)} annotation. * @param testName */ public static void testThreadStarted(String testName) { setThreadTestName(testName); Thread.currentThread().setName(getNextTestThreadName()); } public static void setThreadTestName(String testName) { threadTestName.set(testName); } public static void setThreadTestNameIfMissing(String testName) { if (threadTestName.get() == null) { threadTestName.set(testName); } } public static String getNextNodeName() { String testName = getCurrentTestName(); TestResources resources = getTestResources(testName); String shortName = resources.getShortName(); int nextNodeIndex = resources.addNode(); return shortName + "-" + "Node" + getNameForIndex(nextNodeIndex); } public static String getNextTestThreadName() { String testName = getCurrentTestName(); TestResources resources = getTestResources(testName); String shortName = resources.getShortName(); int nextThreadIndex = resources.addThread(); return "testng-" + shortName + (nextThreadIndex != 0 ? "-" + nextThreadIndex : ""); } public static String getNameForIndex(int i) { final int k = 'Z' - 'A' + 1; String c = String.valueOf((char) ('A' + i % k)); int q = i / k; return q == 0 ? c : getNameForIndex(q - 1) + c; } private static TestResources getTestResources(final String testName) { return testResources.computeIfAbsent(testName, TestResources::new); } private static class TestResources { private static final boolean shortenTestName = Boolean.getBoolean("infinispan.test.shortTestName"); private final String shortName; private final AtomicInteger nodeCount = new AtomicInteger(0); private final AtomicInteger threadCount = new AtomicInteger(0); private final List<Cleaner<?>> resourceCleaners = Collections.synchronizedList(new ArrayList<Cleaner<?>>()); private TestResources(String testName) { if (shortenTestName) { this.shortName = "Test"; } else { int simpleNameStart = testName.lastIndexOf("."); int parametersStart = testName.indexOf('['); this.shortName = testName.substring(simpleNameStart + 1, parametersStart > 0 ? parametersStart : testName.length()); } } public String getShortName() { return shortName; } public int addNode() { return nodeCount.getAndIncrement(); } public int addThread() { return threadCount.getAndIncrement(); } public void addResource(Cleaner<?> cleaner) { resourceCleaners.add(cleaner); } public List<Cleaner<?>> getCleaners() { return resourceCleaners; } } public static abstract class Cleaner<T> { protected final T ref; protected Cleaner(T ref) { this.ref = ref; } public abstract void close(); } }
7,431
36.16
170
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/TestNGLongTestsHook.java
package org.infinispan.commons.test; import static org.infinispan.commons.test.RunningTestsRegistry.registerThreadWithTest; import static org.infinispan.commons.test.RunningTestsRegistry.unregisterThreadWithTest; import org.testng.IHookCallBack; import org.testng.IHookable; import org.testng.ITestResult; /** * TestNG hook to interrupt tests that take too long (usually because of a deadlock). * * @author Dan Berindei * @since 9.2 */ public class TestNGLongTestsHook implements IHookable { @Override public void run(IHookCallBack hookCallBack, ITestResult testResult) { String testName = testResult.getInstanceName() + "." + testResult.getMethod().getMethodName(); String simpleName = testResult.getTestClass().getRealClass().getSimpleName(); registerThreadWithTest(testName, simpleName); try { hookCallBack.runTestMethod(testResult); } finally { unregisterThreadWithTest(); } } }
956
29.870968
100
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/BlockHoundHelper.java
package org.infinispan.commons.test; import java.util.concurrent.Executor; import java.util.function.Supplier; import reactor.blockhound.BlockHound; public class BlockHoundHelper { private BlockHoundHelper() { } /** * Installs BlockHound and all service loaded integrations to ensure that blocking doesn't occur where it shouldn't */ static void installBlockHound() { // Automatically registers all services that implement BlockHoundIntegration interface // This is a terrible hack but gets around the issue that blockhound doesn't allow the registering thread // to be a dynamic blocking thread - in which case our checks in // AbstractInfinispanTest#currentThreadRequiresNonBlocking will never be evaluated // To be removed when BlockHound 1.0.4.RELEASE is available Thread otherThread = new Thread(BlockHound::install); otherThread.start(); try { otherThread.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } } /** * Returns true if the current thread at this time requires all invocations to be non blocking */ public static boolean currentThreadRequiresNonBlocking() { return isNonBlocking.get() == Boolean.TRUE; } private static final ThreadLocal<Boolean> isNonBlocking = ThreadLocal.withInitial(() -> Boolean.FALSE); /** * Invokes the provided Supplier in a scope that guarantees that the current thread is not blocked. If blocking is * found the invoking test will fail. */ public static <V> V ensureNonBlocking(Supplier<V> supplier) { Boolean previousSetting = isNonBlocking.get(); isNonBlocking.set(Boolean.TRUE); try { return supplier.get(); } finally { isNonBlocking.set(previousSetting); } } /** * Invokes the provided Runnable in a scope that guarantees that the current thread is not blocked. If blocking is * found the invoking test will fail. */ public static void ensureNonBlocking(Runnable runnable) { allowBlocking(runnable, Boolean.TRUE); } public static void allowBlocking(Runnable runnable) { allowBlocking(runnable, Boolean.FALSE); } private static void allowBlocking(Runnable runnable, Boolean nonBlockingSetting) { Boolean previousSetting = isNonBlocking.get(); isNonBlocking.set(nonBlockingSetting); try { runnable.run(); } finally { isNonBlocking.set(previousSetting); } } /** * Returns an Executor that when supplied a task, will guarantee that task does not block when invoked. If the * task does block it will fail the invoking test. */ public static Executor ensureNonBlockingExecutor() { return BlockHoundHelper::ensureNonBlocking; } /** * Returns an Executor that when supplied a task, will allow it to invoke blocking calls, even if the invoking * context was already registered as non blocking. Useful to mock submission to a blocking executor. */ public static Executor allowBlockingExecutor() { return BlockHoundHelper::allowBlocking; } /** * Helper method that "blocks" as dictated by block hound but in actuality does nothing. This is useful to detect * if the given code is actually be invoked in an method that allows for blocking or not. * @param consumed an argument useful for making this method a `Consumer` via method reference * @param <V> whatever desired type is */ public static <V> void blockingConsume(V consumed) { // Do nothing - this method is instrumented via block hound to be "blocking" for use by tests to simulate blocking // without actually blocking } }
3,738
35.656863
120
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/TestResourceTrackingListener.java
package org.infinispan.commons.test; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; /** * TestNG listener to call {@link TestResourceTracker#testStarted(String)} and * {@link TestResourceTracker#testFinished(String)}. * * @author Dan Berindei * @since 9.0 */ public class TestResourceTrackingListener implements ITestListener { @Override public void onTestStart(ITestResult result) { } @Override public void onTestSuccess(ITestResult result) { } @Override public void onTestFailure(ITestResult result) { } @Override public void onTestSkipped(ITestResult result) { } @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) { } @Override public void onStart(ITestContext context) { Class testClass = context.getCurrentXmlTest().getXmlClasses().get(0).getSupportClass(); TestResourceTracker.testStarted(testClass.getName()); } @Override public void onFinish(ITestContext context) { Class testClass = context.getCurrentXmlTest().getXmlClasses().get(0).getSupportClass(); TestResourceTracker.testFinished(testClass.getName()); } }
1,201
24.574468
93
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/ThreadLeakChecker.java
package org.infinispan.commons.test; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; 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.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.jboss.logging.Logger; /** * Check for leaked threads in the test suite. * * <p>Every second record new threads and the tests that might have started them. * After the last test, log the threads that are still running and the source tests.</p> * * <p> * Strategies for debugging test suite thread leaks: * </p> * <ul> * <li>Use -Dinfinispan.test.parallel.threads=3 (or even less) to narrow down source tests</li> * <li>Set a conditional breakpoint in Thread.start with the name of the leaked thread</li> * <li>If the thread has the pattern of a particular component, set a conditional breakpoint in that component</li> * </ul> * * @author Dan Berindei * @since 10.0 */ public class ThreadLeakChecker { private static final Pattern IGNORED_THREADS_REGEX = Pattern.compile("(testng-" + // RunningTestRegistry uses a scheduled executor "|RunningTestsRegistry-Worker" + // TestingUtil.orTimeout "|test-timeout-thread" + // JUnit FailOnTimeout rule "|Time-limited test" + // Distributed streams use ForkJoinPool.commonPool "|ForkJoinPool.commonPool-" + // RxJava "|RxCachedWorkerPoolEvictor" + "|RxSchedulerPurge" + "|globalEventExecutor" + // Narayana "|Transaction Reaper" + // H2 "|Generate Seed" + // JDK HTTP client "|Keep-Alive-Timer" + // JVM debug agent thread (sometimes started dynamically by Byteman) "|Attach Listener" + // Hibernate search sometimes leaks consumer threads (ISPN-9890) "|Hibernate Search sync consumer thread for index" + // Reader thread sometimes stays alive for 20s after stop (JGRP-2328) "|NioConnection.Reader" + // java.lang.ProcessHandleImpl "|process reaper" + // Arquillian uses the static default XNIO worker "|XNIO-1 " + // org.apache.mina.transport.socket.nio.NioDatagramAcceptor.DEFAULT_RECYCLER "|ExpiringMapExpirer" + // jboss-modules "|Reference Reaper" + // jboss-remoting "|remoting-jmx client" + // wildfly-controller-client "|management-client-thread" + // IBM JRE specific "|ClassCache Reaper" + // Elytron "|SecurityDomain ThreadGroup" + // Testcontainers "|ducttape" + "|testcontainers" + "|Okio Watchdog" + "|OkHttp ConnectionPool" + // OkHttp uses daemon threads for HTTP/2 "|OkHttp Http2Connection" + // The mysql driver uses a daemon thread to check for connection leaks "|mysql-cj-abandoned-connection-cleanup" + ").*"); private static final String ARQUILLIAN_CONSOLE_CONSUMER = "org.jboss.as.arquillian.container.CommonManagedDeployableContainer$ConsoleConsumer"; private static final boolean ENABLED = "true".equalsIgnoreCase(System.getProperty("infinispan.test.checkThreadLeaks", "true")); private static final Logger log = Logger.getLogger(ThreadLeakChecker.class); private static final Map<Thread, LeakInfo> runningThreads = new ConcurrentHashMap<>(); private static final Lock lock = new ReentrantLock(); private static final LeakException IGNORED = new LeakException("IGNORED"); private static final LeakException UNKNOWN = new LeakException("UNKNOWN"); private static final ThreadInfoLocal threadInfo = new ThreadInfoLocal(); private static class ThreadInfoLocal extends InheritableThreadLocal<LeakException> { @Override protected LeakException childValue(LeakException parentValue) { return new LeakException(Thread.currentThread().getName(), parentValue); } } /** * A test class has started, and we should consider it as a potential owner for new threads. */ public static void testStarted(String testName) { threadInfo.set(new LeakException(testName)); } /** * Save the system threads in order to ignore them */ public static void saveInitialThreads() { lock.lock(); try { Set<Thread> currentThreads = getThreadsSnapshot(); for (Thread thread : currentThreads) { LeakInfo leakInfo = new LeakInfo(thread, IGNORED); runningThreads.putIfAbsent(thread, leakInfo); } } finally { lock.unlock(); } // Initialize the thread-local, in case some tests don't call testStarted() threadInfo.set(UNKNOWN); } /** * A test class has finished, and we should not consider it a potential owner for new threads any more. */ public static void testFinished(String testName) { threadInfo.set(new LeakException("after-" + testName)); } private static void updateThreadOwnership(String testName) { // Update the thread ownership information Set<Thread> currentThreads = getThreadsSnapshot(); runningThreads.keySet().retainAll(currentThreads); Field threadLocalsField; Method getEntryMethod; Field valueField; try { threadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals"); threadLocalsField.setAccessible(true); getEntryMethod = Class.forName("java.lang.ThreadLocal$ThreadLocalMap").getDeclaredMethod("getEntry", ThreadLocal.class); getEntryMethod.setAccessible(true); valueField = Class.forName("java.lang.ThreadLocal$ThreadLocalMap$Entry").getDeclaredField("value"); valueField.setAccessible(true); } catch (NoSuchFieldException | NoSuchMethodException | ClassNotFoundException e) { log.error("Error obtaining thread local accessors, ignoring thread leaks"); return; } for (Thread thread : currentThreads) { if (runningThreads.containsKey(thread)) continue; try { Object threadLocalsMap = threadLocalsField.get(thread); Object entry = threadLocalsMap != null ? getEntryMethod.invoke(threadLocalsMap, threadInfo) : null; LeakException stacktrace = entry != null ? (LeakException) valueField.get(entry) : new LeakException(testName); runningThreads.putIfAbsent(thread, new LeakInfo(thread, stacktrace)); } catch (IllegalAccessException | InvocationTargetException e) { log.error("Error extracting backtrace of leaked thread " + thread.getName()); } } } /** * Check for leaked threads. * * Assumes that no tests are running. */ public static void checkForLeaks(String lastTestName) { if (!ENABLED) return; lock.lock(); try { performCheck(lastTestName); } finally { lock.unlock(); } } private static void performCheck(String lastTestName) { String ownerTest = "UNKNOWN[" + lastTestName + "]"; updateThreadOwnership(ownerTest); List<LeakInfo> leaks = computeLeaks(); if (!leaks.isEmpty()) { // Give the threads some more time to finish, in case the stop method didn't wait try { Thread.sleep(1500); } catch (InterruptedException e) { // Ignore Thread.currentThread().interrupt(); } // Update the thread ownership information updateThreadOwnership(ownerTest); leaks = computeLeaks(); } if (!leaks.isEmpty()) { try { File reportsDir = new File("target/surefire-reports"); if (!reportsDir.exists() && !reportsDir.mkdirs()) { throw new IOException("Cannot create report directory " + reportsDir.getAbsolutePath()); } PolarionJUnitXMLWriter writer = new PolarionJUnitXMLWriter( new File(reportsDir, "TEST-ThreadLeakChecker" + lastTestName + ".xml")); String property = System.getProperty("infinispan.modulesuffix"); String moduleName = property != null ? property.substring(1) : ""; writer.start(moduleName, leaks.size(), 0, leaks.size(), 0, false); for (LeakInfo leakInfo : leaks) { String testName = "ThreadLeakChecker"; Throwable cause = leakInfo.stacktrace; while (cause != null) { testName = cause.getMessage(); cause = cause.getCause(); } LeakException exception = new LeakException("Leaked thread: " + leakInfo.thread.getName(), leakInfo.stacktrace); exception.setStackTrace(leakInfo.thread.getStackTrace()); TestSuiteProgress.fakeTestFailure(testName + ".ThreadLeakChecker", exception); StringWriter exceptionWriter = new StringWriter(); exception.printStackTrace(new PrintWriter(exceptionWriter)); writer.writeTestCase("ThreadLeakChecker", testName, 0, PolarionJUnitXMLWriter.Status.FAILURE, exceptionWriter.toString(), exception.getClass().getName(), exception.getMessage()); leakInfo.markReported(); } writer.close(); } catch (Exception e) { throw new RuntimeException("Error reporting thread leaks", e); } } } private static List<LeakInfo> computeLeaks() { List<LeakInfo> leaks = new ArrayList<>(); for (LeakInfo leakInfo : runningThreads.values()) { if (leakInfo.shouldReport() && leakInfo.thread.isAlive() && !ignore(leakInfo.thread)) { leaks.add(leakInfo); } } return leaks; } private static boolean ignore(Thread thread) { // System threads (running before the first test) have no potential owners String threadName = thread.getName(); if (IGNORED_THREADS_REGEX.matcher(threadName).matches()) return true; if (thread.getName().startsWith("Thread-")) { // Special check for ByteMan, because nobody calls TransformListener.terminate() if (thread.getClass().getName().equals("org.jboss.byteman.agent.TransformListener")) return true; // Special check for Arquillian, because it uses an unnamed thread to read from the container console StackTraceElement[] s = thread.getStackTrace(); for (StackTraceElement ste : s) { if (ste.getClassName().equals(ARQUILLIAN_CONSOLE_CONSUMER)) { return true; } } } return false; } private static String prettyPrintStacktrace(StackTraceElement[] stackTraceElements) { StringBuilder sb = new StringBuilder(); for (StackTraceElement ste : stackTraceElements) { sb.append("\tat ").append(ste).append('\n'); } return sb.toString(); } private static Set<Thread> getThreadsSnapshot() { ThreadGroup group = Thread.currentThread().getThreadGroup(); while (group.getParent() != null) { group = group.getParent(); } int capacity = group.activeCount() * 2; while (true) { Thread[] threadsArray = new Thread[capacity]; int count = group.enumerate(threadsArray, true); if (count < capacity) return Arrays.stream(threadsArray, 0, count).collect(Collectors.toSet()); capacity = count * 2; } } /** * Ignore threads matching a predicate. */ public static void ignoreThreadsMatching(Predicate<Thread> filter) { // Update the thread ownership information Set<Thread> currentThreads = getThreadsSnapshot(); for (Thread thread : currentThreads) { if (filter.test(thread)) { ignoreThread(thread); } } } /** * Ignore a running thread. */ public static void ignoreThread(Thread thread) { LeakInfo leakInfo = runningThreads.computeIfAbsent(thread, k -> new LeakInfo(thread, IGNORED)); } /** * Ignore threads containing a regex. */ public static void ignoreThreadsContaining(String threadNameRegex) { Pattern pattern = Pattern.compile(".*" + threadNameRegex + ".*"); ignoreThreadsMatching(thread -> pattern.matcher(thread.getName()).matches()); } private static class LeakInfo { final Thread thread; final LeakException stacktrace; boolean reported; LeakInfo(Thread thread, LeakException stacktrace) { this.thread = thread; this.stacktrace = stacktrace; } void markReported() { reported = true; } boolean shouldReport() { return stacktrace != IGNORED && !reported; } @Override public String toString() { String owners; if (stacktrace == IGNORED) { owners = "ignored"; } else { owners = "created by " + stacktrace.getMessage(); } return "{" + thread.getName() + ": " + owners + "}"; } } private static class LeakException extends Exception { private static final long serialVersionUID = 2192447894828825555L; LeakException(String testName) { super(testName, null, false, false); } LeakException(String message, LeakException parent) { super(message + " << " + parent.getMessage(), parent, false, true); } } }
14,697
37.176623
129
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/JUnitTestListener.java
package org.infinispan.commons.test; import static org.infinispan.commons.test.RunningTestsRegistry.registerThreadWithTest; import static org.infinispan.commons.test.RunningTestsRegistry.unregisterThreadWithTest; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; /** * Logs JUnit test progress. * * <p>To enable when running a test in the IDE, annotate the test class with * {@code @RunWith(JUnitTestListener.Runner.class)}.</p> * * <p>To enable in Maven, set the {@code listener} property in the surefire/failsafe plugin.</p> * * @author Dan Berindei * @since 9.0 */ public class JUnitTestListener extends RunListener { /** * Use this runner to add the listener to your test */ public static class Runner extends BlockJUnit4ClassRunner { public Runner(Class<?> klass) throws InitializationError { super(klass); } @Override protected void runChild(final FrameworkMethod method, RunNotifier notifier) { notifier.addListener(new JUnitTestListener()); super.runChild(method, notifier); } } private ThreadLocal<Boolean> currentTestIsSuccessful = new ThreadLocal<>(); private final TestSuiteProgress progressLogger; private String currentTestRunName; public JUnitTestListener() { progressLogger = new TestSuiteProgress(); } @Override public void testStarted(Description description) throws Exception { String testName = testName(description); String simpleName = description.getTestClass().getSimpleName(); progressLogger.testStarted(testName); registerThreadWithTest(testName, simpleName); currentTestIsSuccessful.set(true); } @Override public void testFinished(Description description) throws Exception { unregisterThreadWithTest(); if (currentTestIsSuccessful.get()) { progressLogger.testSucceeded(testName(description)); } } @Override public void testFailure(Failure failure) { currentTestIsSuccessful.set(false); progressLogger.testFailed(testName(failure.getDescription()), failure.getException()); } @Override public void testIgnored(Description description) { currentTestIsSuccessful.set(false); progressLogger.testIgnored(testName(description)); } @Override public void testAssumptionFailure(Failure failure) { currentTestIsSuccessful.set(false); progressLogger.testAssumptionFailed(testName(failure.getDescription()), failure.getException()); } private String testName(Description description) { String className = description.isSuite() ? "suite" : description.getTestClass().getSimpleName(); return className + "." + description.getMethodName(); } @Override public void testRunStarted(Description description) { TestSuiteProgress.printTestJDKInformation(); ThreadLeakChecker.saveInitialThreads(); currentTestRunName = description.getDisplayName(); } @Override public void testRunFinished(Result result) { try { // We don't use @RunWith(Suite.class) so we only have a single suite ThreadLeakChecker.checkForLeaks(currentTestRunName); } catch (Throwable e) { progressLogger.configurationFailed("[ERROR]", e); throw e; } } }
3,609
31.818182
102
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/PolarionJUnitXMLReporter.java
package org.infinispan.commons.test; import java.io.File; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.stream.XMLStreamException; import org.testng.ISuite; import org.testng.ISuiteListener; import org.testng.ISuiteResult; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.annotations.Test; import org.testng.collections.Maps; import org.testng.internal.IResultListener2; import org.testng.internal.Utils; /** * A JUnit XML report generator for Polarion based on the JUnitXMLReporter * * @author <a href='mailto:afield[at]redhat[dot]com'>Alan Field</a> */ public class PolarionJUnitXMLReporter implements IResultListener2, ISuiteListener { public static final Pattern DUPLICATE_TESTS_MODULE_PATTERN = Pattern.compile(".*-(embedded|remote|v\\d+)"); /** * keep lists of all the results */ private AtomicInteger m_numFailed = new AtomicInteger(0); private AtomicInteger m_numSkipped = new AtomicInteger(0); private Map<String, List<ITestResult>> m_allTests = Collections.synchronizedMap(new TreeMap<>()); /** * @see org.testng.IConfigurationListener2#beforeConfiguration(ITestResult) */ @Override public void beforeConfiguration(ITestResult tr) { } /** * @see org.testng.ITestListener#onTestStart(ITestResult) */ @Override public void onTestStart(ITestResult result) { } /** * @see org.testng.ITestListener#onTestSuccess(ITestResult) */ @Override public void onTestSuccess(ITestResult tr) { checkDuplicatesAndAdd(tr); } /** * @see org.testng.ITestListener#onTestFailure(ITestResult) */ @Override public void onTestFailure(ITestResult tr) { checkDuplicatesAndAdd(tr); m_numFailed.incrementAndGet(); } /** * @see org.testng.ITestListener#onTestFailedButWithinSuccessPercentage(ITestResult) */ @Override public void onTestFailedButWithinSuccessPercentage(ITestResult tr) { checkDuplicatesAndAdd(tr); m_numFailed.incrementAndGet(); } /** * @see org.testng.ITestListener#onTestSkipped(ITestResult) */ @Override public void onTestSkipped(ITestResult tr) { checkDuplicatesAndAdd(tr); m_numSkipped.incrementAndGet(); } /** * @see org.testng.ITestListener#onStart(ITestContext) */ @Override public void onStart(ITestContext context) { } /** * @see org.testng.ITestListener#onFinish(ITestContext) */ @Override public void onFinish(ITestContext context) { } /** * @see org.testng.ISuiteListener#onStart(ISuite) */ @Override public void onStart(ISuite suite) { resetAll(); } /** * @see org.testng.ISuiteListener#onFinish(ISuite) */ @Override public void onFinish(ISuite suite) { generateReport(suite); } /** * @see org.testng.IConfigurationListener#onConfigurationFailure(org.testng.ITestResult) */ @Override public void onConfigurationFailure(ITestResult tr) { checkDuplicatesAndAdd(tr); m_numFailed.incrementAndGet(); } /** * @see org.testng.IConfigurationListener#onConfigurationSkip(org.testng.ITestResult) */ @Override public void onConfigurationSkip(ITestResult tr) { } /** * @see org.testng.IConfigurationListener#onConfigurationSuccess(org.testng.ITestResult) */ @Override public void onConfigurationSuccess(ITestResult itr) { } /** * generate the XML report given what we know from all the test results */ private void generateReport(ISuite suite) { // Get elapsed time for testsuite element long elapsedTime = 0; long testCount = 0; for (List<ITestResult> testResults : m_allTests.values()) { for (ITestResult tr : testResults) { elapsedTime += (tr.getEndMillis() - tr.getStartMillis()); // if (tr.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class) != null) { // testCount += tr.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class) // .invocationCount(); // } else { testCount++; // } } } PolarionJUnitXMLWriter writer = null; try { String outputDir = suite.getOutputDirectory().replaceAll(".Surefire suite", ""); String baseName = String.format("TEST-%s.xml", getSuiteName(suite)); File outputFile = new File(outputDir, baseName); writer = new PolarionJUnitXMLWriter(outputFile); writer.start(getModuleSuffix(), testCount, m_numSkipped.get(), m_numFailed.get(), elapsedTime, true); // TODO Also write a report based on suite.getAllInvokedMethod() and check for differences writeTestResults(writer, m_allTests.values()); } catch (Exception e) { System.err.println("Error writing test report"); e.printStackTrace(System.err); } finally { try { if (writer != null) { writer.close(); } } catch (Exception e) { System.err.println("Error writing test report"); e.printStackTrace(System.err); } } } private void writeTestResults(PolarionJUnitXMLWriter document, Collection<List<ITestResult>> results) throws XMLStreamException { synchronized (results) { for (List<ITestResult> testResults : results) { boolean hasFailures = false; // A single test method might have multiple invocations for (ITestResult tr : testResults) { if (!tr.isSuccess()) { hasFailures = true; // Report all failures writeTestCase(document, tr); } } if (!hasFailures) { // If there were no failures, report a single success writeTestCase(document, testResults.get(0)); } } } } private void writeTestCase(PolarionJUnitXMLWriter writer, ITestResult tr) throws XMLStreamException { String className = tr.getTestClass().getRealClass().getName(); String testName = testName(tr); long elapsedTimeMillis = tr.getEndMillis() - tr.getStartMillis(); PolarionJUnitXMLWriter.Status status = translateStatus(tr); Throwable throwable = tr.getThrowable(); if (throwable != null) { writer.writeTestCase(testName, className, elapsedTimeMillis, status, Utils.shortStackTrace(throwable, true), throwable.getClass().getName(), throwable.getMessage()); } else { writer.writeTestCase(testName, className, elapsedTimeMillis, status, null, null, null); } } private PolarionJUnitXMLWriter.Status translateStatus(ITestResult tr) { switch (tr.getStatus()) { case ITestResult.FAILURE: return PolarionJUnitXMLWriter.Status.FAILURE; case ITestResult.SUCCESS: return PolarionJUnitXMLWriter.Status.SUCCESS; case ITestResult.SUCCESS_PERCENTAGE_FAILURE: case ITestResult.SKIP: return PolarionJUnitXMLWriter.Status.SKIPPED; default: return PolarionJUnitXMLWriter.Status.ERROR; } } /** * Reset all member variables for next test. */ private void resetAll() { m_allTests = Collections.synchronizedMap(Maps.newHashMap()); m_numFailed.set(0); m_numSkipped.set(0); } private String getSuiteName(ISuite suite) { String name = getModuleSuffix(); Collection<ISuiteResult> suiteResults = suite.getResults().values(); if (suiteResults.size() == 1) { ITestNGMethod[] testMethods = suiteResults.iterator().next().getTestContext().getAllTestMethods(); if (testMethods.length > 0) { Class<?> testClass = testMethods[0].getConstructorOrMethod().getDeclaringClass(); // If only one test class executed, then use that as the filename String className = testClass.getName(); // If only one test package executed, then use that as the filename String packageName = testClass.getPackage().getName(); boolean oneTestClass = true; boolean oneTestPackage = true; for (ITestNGMethod method : testMethods) { if (!method.getConstructorOrMethod().getDeclaringClass().getName().equals(className)) { oneTestClass = false; } if (!method.getConstructorOrMethod().getDeclaringClass().getPackage().getName().equals(packageName)) { oneTestPackage = false; } } if (oneTestClass) { name = className; } else { if (oneTestPackage) { name = packageName; } } } else { System.err.println( "[" + this.getClass().getSimpleName() + "] Test suite '" + name + "' results have no test methods"); } } return name; } private String testName(ITestResult res) { StringBuilder result = new StringBuilder(res.getMethod().getMethodName()); if (res.getMethod().getConstructorOrMethod().getMethod().isAnnotationPresent(Test.class)) { String dataProviderName = res.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class) .dataProvider(); // Add parameters for methods that use a data provider only if (res.getParameters().length != 0 && (dataProviderName != null && !dataProviderName.isEmpty())) { result.append("(").append(deepToStringParameters(res)); } // Add number of invocations to method name if (res.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class).invocationCount() > 1) { if (result.indexOf("(") == -1) { result.append("("); } else { result.append(", "); } result.append("invoked ").append( res.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class).invocationCount()) .append(" times"); } } String moduleSuffix = getModuleSuffix(); if (moduleSuffix.contains("hibernate")) { if (result.indexOf("(") == -1) { result.append("("); } else { result.append(", "); } // module Matcher moduleMatcher = DUPLICATE_TESTS_MODULE_PATTERN.matcher(moduleSuffix); if (moduleMatcher.matches()) { result.append(moduleMatcher.group(1)); } } // end if (result.indexOf("(") != -1) { result.append(")"); } return result.toString(); } private String deepToStringParameters(ITestResult res) { Object[] parameters = res.getParameters(); for (int i=0; i<parameters.length; i++) { Object parameter = parameters[i]; if (parameter != null) { if (parameter instanceof Path) { parameters[i] = ((Path) parameter).getFileName().toString(); } else if (parameter.getClass().getSimpleName().contains("$$Lambda$")) { res.setStatus(ITestResult.FAILURE); res.setThrowable(new IllegalStateException("Cannot identify which test is running. Use NamedLambdas.of static method")); } } } return Arrays.deepToString(parameters); } private String getModuleSuffix() { // Remove the "-" from the beginning of the string return System.getProperty("infinispan.module-suffix").substring(1); } private void checkDuplicatesAndAdd(ITestResult tr) { // Need fully qualified name to guarantee uniqueness in the results map String instanceName = tr.getInstanceName(); String key = instanceName + "." + testName(tr); if (m_allTests.containsKey(key)) { if (tr.getMethod().getCurrentInvocationCount() == 1 && tr.isSuccess()) { System.err.println("[" + this.getClass().getSimpleName() + "] Test case '" + key + "' already exists in the results"); tr.setStatus(ITestResult.FAILURE); tr.setThrowable(new IllegalStateException("Duplicate test: " + key)); } List<ITestResult> itrList = m_allTests.get(key); itrList.add(tr); m_allTests.put(key, itrList); } else { ArrayList<ITestResult> itrList = new ArrayList<>(); itrList.add(tr); m_allTests.put(key, itrList); } } }
13,036
34.42663
135
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/PrettyXMLStreamWriter.java
package org.infinispan.commons.test; import java.util.Arrays; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * XMLStreamWriter that adds an indent for each open element. * * @author Dan Berindei * @since 10.0 */ class PrettyXMLStreamWriter implements XMLStreamWriter { private static final int INDENT_STEP = 2; private static final int MAX_INDENT = 64; private static final char[] INDENT = new char[MAX_INDENT + 1]; static { Arrays.fill(INDENT, ' '); INDENT[0] = '\n'; } private XMLStreamWriter writer; private int indent; private boolean skipIndent; PrettyXMLStreamWriter(XMLStreamWriter writer) { this.writer = writer; } @Override public void writeStartElement(String localName) throws XMLStreamException { writeIndent(1); writer.writeStartElement(localName); } @Override public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { writeIndent(1); writer.writeStartElement(namespaceURI, localName); } @Override public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { writeIndent(1); writer.writeStartElement(prefix, localName, namespaceURI); } @Override public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { writeIndent(0); writer.writeEmptyElement(namespaceURI, localName); } @Override public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { writeIndent(0); writer.writeEmptyElement(prefix, localName, namespaceURI); } @Override public void writeEmptyElement(String localName) throws XMLStreamException { writeIndent(0); writer.writeEmptyElement(localName); } @Override public void writeEndElement() throws XMLStreamException { writeIndent(-1); writer.writeEndElement(); } @Override public void writeEndDocument() throws XMLStreamException { writer.writeEndDocument(); } @Override public void close() throws XMLStreamException { writer.close(); } @Override public void flush() throws XMLStreamException { writer.flush(); } @Override public void writeAttribute(String localName, String value) throws XMLStreamException { writer.writeAttribute(localName, value); } @Override public void writeAttribute(String prefix, String namespaceURI, String localName, String value) throws XMLStreamException { writer.writeAttribute(prefix, namespaceURI, localName, value); } @Override public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { writer.writeAttribute(namespaceURI, localName, value); } @Override public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { writer.writeNamespace(prefix, namespaceURI); } @Override public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { writer.writeDefaultNamespace(namespaceURI); } @Override public void writeComment(String data) throws XMLStreamException { writeIndent(0); writer.writeComment(data); } @Override public void writeProcessingInstruction(String target) throws XMLStreamException { writer.writeProcessingInstruction(target); } @Override public void writeProcessingInstruction(String target, String data) throws XMLStreamException { writer.writeProcessingInstruction(target, data); } @Override public void writeCData(String data) throws XMLStreamException { writeIndent(0); writer.writeCData(data); } @Override public void writeDTD(String dtd) throws XMLStreamException { writer.writeDTD(dtd); } @Override public void writeEntityRef(String name) throws XMLStreamException { writer.writeEntityRef(name); } @Override public void writeStartDocument() throws XMLStreamException { writer.writeStartDocument(); } @Override public void writeStartDocument(String version) throws XMLStreamException { writer.writeStartDocument(version); } @Override public void writeStartDocument(String encoding, String version) throws XMLStreamException { writer.writeStartDocument(encoding, version); } @Override public void writeCharacters(String text) throws XMLStreamException { skipIndent = true; writer.writeCharacters(text); } @Override public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { skipIndent = true; writer.writeCharacters(text, start, len); } @Override public String getPrefix(String uri) throws XMLStreamException { return writer.getPrefix(uri); } @Override public void setPrefix(String prefix, String uri) throws XMLStreamException { writer.setPrefix(prefix, uri); } @Override public void setDefaultNamespace(String uri) throws XMLStreamException { writer.setDefaultNamespace(uri); } @Override public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { writer.setNamespaceContext(context); } @Override public NamespaceContext getNamespaceContext() { return writer.getNamespaceContext(); } @Override public Object getProperty(String name) throws IllegalArgumentException { return writer.getProperty(name); } private void writeIndent(int increment) throws XMLStreamException { // Unindent before start element if (increment < 0) { indent += increment * INDENT_STEP; } if (skipIndent) { skipIndent = false; } else { writer.writeCharacters(INDENT, 0, Math.min(indent, MAX_INDENT) + 1); } // Indent after start element if (increment > 0) { indent += increment * INDENT_STEP; } } }
6,111
26.408072
114
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/Exceptions.java
package org.infinispan.commons.test; import java.util.concurrent.Callable; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; /** * Utility methods for testing expected exceptions. * * @author Dan Berindei * @since 8.2 */ public class Exceptions { public static void assertException(Class<? extends Throwable> exceptionClass, Throwable t) { if (t == null) { throw new AssertionError("Should have thrown an " + exceptionClass.getName(), null); } if (t.getClass() != exceptionClass) { throw new AssertionError( "Wrong exception thrown: expected:<" + exceptionClass.getName() + ">, actual:<" + t.getClass().getName() + ">", t); } } public static void assertException(Class<? extends Throwable> exceptionClass, String messageRegex, Throwable t) { assertException(exceptionClass, t); Pattern pattern = Pattern.compile(messageRegex); if (!pattern.matcher(t.getMessage()).matches()) { throw new AssertionError( "Wrong exception message: expected:<" + messageRegex + ">, actual:<" + t.getMessage() + ">", t); } } /** * Expect an exception of class {@code exceptionClass} or its subclasses. */ public static void assertExceptionNonStrict(Class<? extends Throwable> exceptionClass, Throwable t) { if (t == null) { throw new AssertionError("Should have thrown an " + exceptionClass, null); } if (!exceptionClass.isInstance(t)) { throw new AssertionError( "Wrong exception thrown: expected:<" + exceptionClass + ">, actual:<" + t.getClass() + ">", t); } } public static void assertException(Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, Throwable t) { assertException(wrapperExceptionClass, t); assertException(exceptionClass, t.getCause()); } public static void assertException(Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, String messageRegex, Throwable t) { assertException(wrapperExceptionClass, t); assertException(exceptionClass, messageRegex, t.getCause()); } public static void assertException(Class<? extends Throwable> wrapperExceptionClass2, Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, Throwable t) { assertException(wrapperExceptionClass2, t); assertException(wrapperExceptionClass, t.getCause()); assertException(exceptionClass, t.getCause().getCause()); } public static void assertException(Class<? extends Throwable> wrapperExceptionClass2, Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, String messageRegex, Throwable t) { assertException(wrapperExceptionClass2, t); assertException(wrapperExceptionClass, t.getCause()); assertException(exceptionClass, messageRegex, t.getCause().getCause()); } public static void assertException(Class<? extends Throwable> wrapperExceptionClass3, Class<? extends Throwable> wrapperExceptionClass2, Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, Throwable t) { assertException(wrapperExceptionClass3, t); assertException(wrapperExceptionClass2, t.getCause()); assertException(wrapperExceptionClass, t.getCause().getCause()); assertException(exceptionClass, t.getCause().getCause().getCause()); } public static void expectException(Class<? extends Throwable> exceptionClass, String messageRegex, ExceptionRunnable runnable) { Throwable t = extractException(runnable); assertException(exceptionClass, messageRegex, t); } public static void expectException(Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, String messageRegex, ExceptionRunnable runnable) { Throwable t = extractException(runnable); assertException(wrapperExceptionClass, exceptionClass, messageRegex, t); } public static void expectException(Class<? extends Throwable> wrapperExceptionClass2, Class<? extends Throwable> wrapperExceptionClass1, Class<? extends Throwable> exceptionClass, ExceptionRunnable runnable) { Throwable t = extractException(runnable); assertException(wrapperExceptionClass2, wrapperExceptionClass1, exceptionClass, t); } public static void expectException(Class<? extends Throwable> wrapperExceptionClass2, Class<? extends Throwable> wrapperExceptionClass1, Class<? extends Throwable> exceptionClass, String regex, ExceptionRunnable runnable) { Throwable t = extractException(runnable); assertException(wrapperExceptionClass2, wrapperExceptionClass1, exceptionClass, regex, t); } public static void expectException(Class<? extends Throwable> exceptionClass, ExceptionRunnable runnable) { Throwable t = extractException(runnable); assertException(exceptionClass, t); } public static void expectException(Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, ExceptionRunnable runnable) { Throwable t = extractException(runnable); assertException(wrapperExceptionClass, t); assertException(exceptionClass, t.getCause()); } @SafeVarargs public static void expectException(String regex, ExceptionRunnable runnable, Class<? extends Throwable>... wrapperExceptionClass) { Throwable t = extractException(runnable); // Go until one before last as we have to check regex against it below for (int i = 0; i < wrapperExceptionClass.length - 1; i++) { Class<? extends Throwable> exceptionClass = wrapperExceptionClass[i]; assertException(exceptionClass, t); t = t.getCause(); } assertException(wrapperExceptionClass[wrapperExceptionClass.length - 1], regex, t); } public static void expectRootCause(Class<? extends Throwable> exceptionClass, ExceptionRunnable runnable) { Throwable t = getRootCause(extractException(runnable)); assertException(exceptionClass, t); } public static void expectExceptionNonStrict(Class<? extends Throwable> e, ExceptionRunnable runnable) { Throwable t = extractException(runnable); assertExceptionNonStrict(e, t); } public static void expectExceptionNonStrict(Class<? extends Throwable> we1, Class<? extends Throwable> e, ExceptionRunnable runnable) { Throwable t = extractException(runnable); assertExceptionNonStrict(we1, t); assertExceptionNonStrict(e, t.getCause()); } public static void expectExceptionNonStrict(Class<? extends Throwable> we2, Class<? extends Throwable> we1, Class<? extends Throwable> e, ExceptionRunnable runnable) { Throwable t = extractException(runnable); assertExceptionNonStrict(we2, t); assertExceptionNonStrict(we1, t.getCause()); assertExceptionNonStrict(e, t.getCause().getCause()); } public static void expectExecutionException(Class<? extends Throwable> exceptionClass, String messageRegex, Future<?> future) { expectExecutionException(exceptionClass, messageRegex, future, 10, TimeUnit.SECONDS); } public static void expectExecutionException(Class<? extends Throwable> exceptionClass, String messageRegex, Future<?> future, long timeout, TimeUnit unit) { Throwable t = extractException(() -> future.get(timeout, unit)); assertException(ExecutionException.class, t); assertException(exceptionClass, messageRegex, t.getCause()); } public static void expectExecutionException(Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, String messageRegex, Future<?> future) { Throwable t = extractException(() -> future.get(10, TimeUnit.SECONDS)); assertException(ExecutionException.class, t); assertException(wrapperExceptionClass, t.getCause()); assertException(exceptionClass, messageRegex, t.getCause().getCause()); } public static void expectExecutionException(Class<? extends Throwable> wrapperExceptionClass2, Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, String messageRegex, Future<?> future) { Throwable t = extractException(() -> future.get(10, TimeUnit.SECONDS)); assertException(ExecutionException.class, t); assertException(wrapperExceptionClass2, t.getCause()); assertException(wrapperExceptionClass, exceptionClass, messageRegex, t.getCause().getCause()); } public static void expectExecutionException(Class<? extends Throwable> exceptionClass, Future<?> future) { Throwable t = extractException(() -> future.get(10, TimeUnit.SECONDS)); assertException(ExecutionException.class, t); assertException(exceptionClass, t.getCause()); } public static void expectExecutionException(Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, Future<?> future) { Throwable t = extractException(() -> future.get(10, TimeUnit.SECONDS)); assertException(ExecutionException.class, t); assertException(wrapperExceptionClass, t.getCause()); assertException(exceptionClass, t.getCause().getCause()); } public static void expectExecutionException(Class<? extends Throwable> wrapperExceptionClass2, Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, Future<?> future) { Throwable t = extractException(() -> future.get(10, TimeUnit.SECONDS)); assertException(ExecutionException.class, t); assertException(wrapperExceptionClass2, t.getCause()); assertException(wrapperExceptionClass, exceptionClass, t.getCause().getCause()); } public static void expectCompletionException(Class<? extends Throwable> exceptionClass, String messageRegex, CompletionStage<?> stage) { expectCompletionException(exceptionClass, messageRegex, stage, 10, TimeUnit.SECONDS); } public static void expectCompletionException(Class<? extends Throwable> exceptionClass, String messageRegex, CompletionStage<?> stage, long timeout, TimeUnit unit) { // Need to use get() for the timeout, but that converts the exception to an ExecutionException Throwable t = extractException(() -> stage.toCompletableFuture().get(timeout, unit)); assertException(ExecutionException.class, t); assertException(exceptionClass, messageRegex, t.getCause()); } public static void expectCompletionException(Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, String messageRegex, CompletionStage<?> stage) { // Need to use get() for the timeout, but that converts the exception to an ExecutionException Throwable t = extractException(() -> stage.toCompletableFuture().get(10, TimeUnit.SECONDS)); assertException(ExecutionException.class, t); assertException(wrapperExceptionClass, t.getCause()); assertException(exceptionClass, messageRegex, t.getCause().getCause()); } public static void expectCompletionException(Class<? extends Throwable> wrapperExceptionClass2, Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, String messageRegex, CompletionStage<?> stage) { // Need to use get() for the timeout, but that converts the exception to an ExecutionException Throwable t = extractException(() -> stage.toCompletableFuture().get(10, TimeUnit.SECONDS)); assertException(ExecutionException.class, t); assertException(wrapperExceptionClass2, t.getCause()); assertException(wrapperExceptionClass, exceptionClass, messageRegex, t.getCause().getCause()); } public static void expectCompletionException(Class<? extends Throwable> exceptionClass, CompletionStage<?> stage) { // Need to use get() for the timeout, but that converts the exception to an ExecutionException Throwable t = extractException(() -> stage.toCompletableFuture().get(10, TimeUnit.SECONDS)); assertException(ExecutionException.class, t); assertException(exceptionClass, t.getCause()); } public static void expectCompletionException(Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, CompletionStage<?> stage) { // Need to use get() for the timeout, but that converts the exception to an ExecutionException Throwable t = extractException(() -> stage.toCompletableFuture().get(10, TimeUnit.SECONDS)); assertException(ExecutionException.class, t); assertException(wrapperExceptionClass, t.getCause()); assertException(exceptionClass, t.getCause().getCause()); } public static void expectCompletionException(Class<? extends Throwable> wrapperExceptionClass2, Class<? extends Throwable> wrapperExceptionClass, Class<? extends Throwable> exceptionClass, CompletionStage<?> stage) { // Need to use get() for the timeout, but that converts the exception to an ExecutionException Throwable t = extractException(() -> stage.toCompletableFuture().get(10, TimeUnit.SECONDS)); assertException(ExecutionException.class, t); assertException(wrapperExceptionClass2, t.getCause()); assertException(wrapperExceptionClass, exceptionClass, t.getCause().getCause()); } public static Throwable extractException(ExceptionRunnable runnable) { Throwable exception = null; try { runnable.run(); } catch (Throwable t) { exception = t; } return exception; } 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 void unchecked(ExceptionRunnable runnable) { try { runnable.run(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } public static <T> T unchecked(Callable<T> callable) { try { return callable.call(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } public static <T> T uncheckedThrowable(ThrowableSupplier<T> supplier) { try { return supplier.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (RuntimeException e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } }
15,749
46.155689
170
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/Eventually.java
package org.infinispan.commons.test; import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import org.junit.ComparisonFailure; public class Eventually { public static final int DEFAULT_TIMEOUT_MILLIS = 10000; public static final int DEFAULT_POLL_INTERVAL_MILLIS = 100; @FunctionalInterface public interface Condition { boolean isSatisfied() throws Exception; } public static void eventually(Supplier<AssertionError> assertionErrorSupplier, Condition ec, long timeout, long pollInterval, TimeUnit unit) { if (pollInterval <= 0) { throw new IllegalArgumentException("Check interval must be positive"); } try { long expectedEndTime = System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeout, unit); long sleepMillis = MILLISECONDS.convert(pollInterval, unit); do { if (ec.isSatisfied()) return; Thread.sleep(sleepMillis); } while (expectedEndTime - System.nanoTime() > 0); throw assertionErrorSupplier.get(); } catch (Exception e) { throw new RuntimeException("Unexpected!", e); } } public static void eventually(String message, Condition ec, long timeout, long pollInterval, TimeUnit unit) { eventually(() -> new AssertionError(message), ec, timeout, pollInterval, unit); } public static void eventually(Condition ec) { eventually(ec, DEFAULT_TIMEOUT_MILLIS); } public static void eventually(Condition ec, long timeoutMillis) { eventually(ec, timeoutMillis, MILLISECONDS); } public static void eventually(String message, Condition ec) { eventually(message, ec, DEFAULT_TIMEOUT_MILLIS, DEFAULT_POLL_INTERVAL_MILLIS, MILLISECONDS); } public static void eventually(Condition ec, long timeout, TimeUnit unit) { eventually(() -> new AssertionError(), ec, unit.toMillis(timeout), DEFAULT_POLL_INTERVAL_MILLIS, MILLISECONDS); } public static void eventually(Condition ec, long timeout, long pollInterval, TimeUnit unit) { eventually(() -> new AssertionError(), ec, timeout, pollInterval, unit); } public static <T> void eventuallyEquals(T expected, Supplier<T> supplier, long timeout, long pollInterval, TimeUnit unit) { if (pollInterval <= 0) { throw new IllegalArgumentException("Check interval must be positive"); } try { long expectedEndTime = System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeout, unit); long sleepMillis = MILLISECONDS.convert(pollInterval, unit); T value; do { value = supplier.get(); if (Objects.equals(expected, value)) return; Thread.sleep(sleepMillis); } while (expectedEndTime - System.nanoTime() > 0); if (expected instanceof String && value instanceof String) { throw new ComparisonFailure(null, (String) expected, (String) value); } else { String expectedClass = expected != null ? expected.getClass().getSimpleName() : ""; String valueClass = value != null ? value.getClass().getSimpleName() : ""; throw new AssertionError( String.format("expected: %s<%s>, but was %s<%s>", expectedClass, expected, valueClass, value)); } } catch (Exception e) { throw new RuntimeException("Unexpected!", e); } } public static <T> void eventuallyEquals(T expected, Supplier<T> supplier, long timeout, TimeUnit unit) { eventuallyEquals(expected, supplier, unit.toMillis(timeout), DEFAULT_POLL_INTERVAL_MILLIS, MILLISECONDS); } public static <T> void eventuallyEquals(T expected, Supplier<T> supplier) { eventuallyEquals(expected, supplier, DEFAULT_TIMEOUT_MILLIS, DEFAULT_POLL_INTERVAL_MILLIS, MILLISECONDS); } }
3,991
37.757282
117
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/ExceptionRunnable.java
package org.infinispan.commons.test; /** * Runnable that can throw any exception. * * @author Dan Berindei * @since 9.2 */ @FunctionalInterface public interface ExceptionRunnable { void run() throws Exception; }
221
16.076923
41
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/PolarionJUnitXMLWriter.java
package org.infinispan.commons.test; import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * A JUnit XML report generator for Polarion based on the JUnitXMLReporter * * <p>Extracted from {@link PolarionJUnitXMLReporter}</p> * * @author <a href='mailto:afield[at]redhat[dot]com'>Alan Field</a> * @author Dan Berindei * @since 10.0 */ public class PolarionJUnitXMLWriter implements AutoCloseable { private final FileWriter fileWriter; public enum Status {SUCCESS, FAILURE, ERROR, SKIPPED} private static final String TESTSUITE = "testsuite"; private static final String ATTR_TESTS = "tests"; private static final String ATTR_TIME = "time"; private static final String ATTR_NAME = "name"; private static final String ATTR_SKIPPED = "skipped"; private static final String ATTR_ERRORS = "errors"; private static final String ATTR_FAILURES = "failures"; private static final String TESTCASE = "testcase"; private static final String FAILURE = "failure"; private static final String ERROR = "error"; private static final String SKIPPED = "skipped"; private static final String ATTR_CLASSNAME = "classname"; private static final String ATTR_MESSAGE = "message"; private static final String ATTR_TYPE = "type"; private static final String ATTR_VALUE = "value"; private static final String PROPERTIES = "properties"; private static final String PROPERTY = "property"; private static final char UNICODE_REPLACEMENT = 0xFFFD; private static XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory(); private XMLStreamWriter xmlWriter; public PolarionJUnitXMLWriter(File outputFile) throws IOException { File outputDirectory = outputFile.getParentFile(); if (!outputDirectory.exists()) { if (!outputDirectory.mkdirs()) { throw new IllegalStateException("Unable to create report directory " + outputDirectory); } } fileWriter = new FileWriter(outputFile); } public void start(String moduleName, long testCount, long skippedCount, long failedCount, long elapsedTime, boolean includeProperties) throws XMLStreamException { xmlWriter = new PrettyXMLStreamWriter(xmlOutputFactory.createXMLStreamWriter(fileWriter)); xmlWriter.writeStartDocument(); xmlWriter.writeCharacters("\n"); xmlWriter.writeComment("Generated by " + getClass().getName()); xmlWriter.writeStartElement(TESTSUITE); xmlWriter.writeAttribute(ATTR_TESTS, "" + testCount); xmlWriter.writeAttribute(ATTR_TIME, "" + elapsedTime / 1000.0); xmlWriter.writeAttribute(ATTR_NAME, moduleName); xmlWriter.writeAttribute(ATTR_SKIPPED, "" + skippedCount); xmlWriter.writeAttribute(ATTR_ERRORS, "0"); xmlWriter.writeAttribute(ATTR_FAILURES, "" + failedCount); if (includeProperties) { writeProperties(); } xmlWriter.writeComment("Tests results"); } @Override public void close() throws Exception { xmlWriter.writeEndElement(); xmlWriter.writeEndDocument(); xmlWriter.close(); fileWriter.close(); } public void writeTestCase(String testName, String className, long elapsedTimeMillis, Status status, String stackTrace, String throwableClass, String throwableMessage) throws XMLStreamException { String elapsedTime = "" + (((double) elapsedTimeMillis) / 1000); if (Status.SUCCESS == status) { xmlWriter.writeEmptyElement(TESTCASE); } else { xmlWriter.writeStartElement(TESTCASE); } xmlWriter.writeAttribute(ATTR_NAME, testName); xmlWriter.writeAttribute(ATTR_CLASSNAME, className); xmlWriter.writeAttribute(ATTR_TIME, elapsedTime); if (Status.SUCCESS != status) { switch (status) { case FAILURE: writeCauseElement(FAILURE, throwableClass, throwableMessage, stackTrace); break; case ERROR: writeCauseElement(ERROR, throwableClass, throwableMessage, stackTrace); break; case SKIPPED: writeSkipElement(); } xmlWriter.writeEndElement(); } } private void writeCauseElement(String tag, String throwableClass, String message, String stackTrace) throws XMLStreamException { xmlWriter.writeStartElement(tag); xmlWriter.writeAttribute(ATTR_TYPE, throwableClass); if ((message != null) && (message.length() > 0)) { xmlWriter.writeAttribute(ATTR_MESSAGE, escapeInvalidChars(message)); } xmlWriter.writeCData(stackTrace); xmlWriter.writeEndElement(); } private void writeSkipElement() throws XMLStreamException { xmlWriter.writeEmptyElement(SKIPPED); } private String escapeInvalidChars(String chars) { // Restricted chars for xml are [#x1-#x8], [#xB-#xC], [#xE-#x1F], [#x7F-#x84], [#x86-#x9F] return chars.codePoints() .map(c -> { if (!Character.isDefined(c) || 0x1 <= c && c <= 0x8 || c == 0xB || c == 0xC || 0xE <= c && c <= 0x1F || 0x7F <= c && c < 0x84 || 0x86 <= c && c <= 0x9F) { return UNICODE_REPLACEMENT; } else { return c; } }) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); } private void writeProperties() throws XMLStreamException { xmlWriter.writeStartElement(PROPERTIES); // Add all system properties xmlWriter.writeComment("Java System properties"); for (Object key : System.getProperties().keySet()) { xmlWriter.writeEmptyElement(PROPERTY); xmlWriter.writeAttribute(ATTR_NAME, key.toString()); xmlWriter.writeAttribute(ATTR_VALUE, System.getProperty(key.toString())); } // Add all environment variables xmlWriter.writeComment("Environment variables"); for (String key : System.getenv().keySet()) { xmlWriter.writeEmptyElement(PROPERTY); xmlWriter.writeAttribute(ATTR_NAME, key); xmlWriter.writeAttribute(ATTR_VALUE, System.getenv(key)); } xmlWriter.writeEndElement(); } }
6,503
36.165714
110
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/CommonsTestingUtil.java
package org.infinispan.commons.test; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.CopyOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.function.Consumer; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ public class CommonsTestingUtil { public static final String TEST_PATH = "infinispanTempFiles"; /** * Creates a path to a unique (per test) temporary directory. By default, the directory is created in the platform's * temp directory, but the location can be overridden with the {@code infinispan.test.tmpdir} system property. * * @param test test that requires this directory. * @return an absolute path */ public static String tmpDirectory(Class<?> test) { return Paths.get(tmpDirectory(), TEST_PATH, test.getSimpleName()).toString(); } /** * See {@link CommonsTestingUtil#tmpDirectory(Class)} * * @return an absolute path */ public static String tmpDirectory(String... folders) { if (Paths.get(folders[0]).isAbsolute()) { throw new IllegalArgumentException("Cannot use absolute path " + folders[0]); } String[] tFolders = new String[folders.length + 1]; tFolders[0] = TEST_PATH; System.arraycopy(folders, 0, tFolders, 1, folders.length); return Paths.get(tmpDirectory(), tFolders).toString(); } public static String tmpDirectory() { return System.getProperty("infinispan.test.tmpdir", System.getProperty("java.io.tmpdir")); } public static String loadFileAsString(InputStream is) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); for (String line = r.readLine(); line != null; line = r.readLine()) { sb.append(line); sb.append("\n"); } return sb.toString(); } public static class CopyFileVisitor extends SimpleFileVisitor<Path> { private final Path targetPath; private Path sourcePath = null; private final CopyOption[] copyOptions; private final Consumer<File> manipulator; public CopyFileVisitor(Path targetPath, boolean overwrite) { this(targetPath, overwrite, null); } public CopyFileVisitor(Path targetPath, boolean overwrite, Consumer<File> manipulator) { this.targetPath = targetPath; this.manipulator = manipulator; this.copyOptions = overwrite ? new CopyOption[]{StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES} : new CopyOption[0]; } @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { if (sourcePath == null) { sourcePath = dir; } else { Files.createDirectories(targetPath.resolve(sourcePath.relativize(dir).toString())); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Path target = targetPath.resolve(sourcePath.relativize(file).toString()); Files.copy(file, target, copyOptions); if (manipulator != null) { manipulator.accept(target.toFile()); } return FileVisitResult.CONTINUE; } } }
3,776
35.317308
150
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/TestNGSuiteChecksTest.java
package org.infinispan.commons.test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.testng.ITestContext; import org.testng.ITestNGMethod; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; /** * This test checks for thread leaks. * * The check must be in a configuration method, because TestNG doesn't report listener exceptions properly. * * @since 10.0 * @author Dan Berindei */ @Test(groups = {"unit", "smoke"}, testName = "test.fwk.TestNGSuiteChecksTest") public class TestNGSuiteChecksTest { private static final Set<String> REQUIRED_GROUPS = new HashSet<>( Arrays.asList("unit", "functional", "xsite", "arquillian", "stress", "profiling", "manual", "unstable")); private static final Set<String> ALLOWED_GROUPS = new HashSet<>( Arrays.asList("unit", "functional", "xsite", "arquillian", "stress", "profiling", "manual", "unstable", "smoke", "java11", "transaction")); @BeforeSuite(alwaysRun = true) public void beforeSuite(ITestContext context) { TestSuiteProgress.printTestJDKInformation(); List<String> errors = new ArrayList<>(); Set<Class> classes = new HashSet<>(); checkAnnotations(errors, classes, context.getSuite().getExcludedMethods()); checkAnnotations(errors, classes, context.getSuite().getAllMethods()); if (!errors.isEmpty()) { throw new AssertionError(String.join("\n", errors)); } } @AfterSuite(alwaysRun = true) public void afterSuite() { ThreadLeakChecker.checkForLeaks(""); } private void checkAnnotations(List<String> errors, Set<Class> classes, Collection<ITestNGMethod> methods) { for (ITestNGMethod m : methods) { checkMethodAnnotations(errors, m); checkClassAnnotations(errors, classes, m); } } private void checkMethodAnnotations(List<String> errors, ITestNGMethod m) { if (!m.getEnabled()) return; boolean hasRequiredGroup = false; for (String g : m.getGroups()) { if (!ALLOWED_GROUPS.contains(g)) { errors.add( "Method " + m.getConstructorOrMethod() + " and/or its class has a @Test annotation with the wrong group: " + g + ".\nAllowed groups are " + ALLOWED_GROUPS); return; } if (REQUIRED_GROUPS.contains(g)) { hasRequiredGroup = true; } } if (!hasRequiredGroup) { errors.add("Method " + m.getConstructorOrMethod() + " and/or its class don't have any required group." + "\nRequired groups are " + REQUIRED_GROUPS); return; } // Some stress tests extend a functional test and change some parameters (e.g. number of operations) // If the author forgets to override the test methods, they inherit the group from the base class Class<?> testClass = m.getRealClass(); Class<?> declaringClass = m.getConstructorOrMethod().getDeclaringClass(); Test annotation = testClass.getAnnotation(Test.class); if (testClass != declaringClass) { if (!Arrays.equals(annotation.groups(), m.getGroups())) { errors.add("Method " + m.getConstructorOrMethod() + " was inherited from class " + declaringClass + " with groups " + Arrays.toString(m.getGroups()) + ", but the test class has groups " + Arrays.toString(annotation.groups())); } } } private void checkClassAnnotations(List<String> errors, Set<Class> processedClasses, ITestNGMethod m) { // Class of the test instance Class<?> testClass = m.getTestClass().getRealClass(); // Check that the test instance's class matches the XmlTest's support class // They can be different if a test inherits a @Factory method and doesn't override it // Ignore multiple classes in the same XmlTest, which can happen when running from the IDE // or when the testName is incorrect (handled below) if (m.getXmlTest().getXmlClasses().size() == 1) { Class xmlClass = m.getXmlTest().getXmlClasses().get(0).getSupportClass(); if (xmlClass != testClass && processedClasses.add(xmlClass)) { errors.add("Class " + xmlClass.getName() + " must override the @Factory method from base class " + testClass.getName()); return; } } if (!processedClasses.add(testClass)) return; // Check that the testName in the @Test annotation is set and matches the test class // All tests with the same testName or without a testName run in the same XmlTest // which means they also run in the same thread, not in parallel Test annotation = testClass.getAnnotation(Test.class); if (annotation == null || annotation.testName().isEmpty()) { errors.add("Class " + testClass.getName() + " does not have a testName"); return; } if (!annotation.testName().contains(testClass.getSimpleName())) { errors.add("Class " + testClass.getName() + " has an invalid testName: " + annotation.testName()); } } }
5,315
41.190476
113
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/Ansi.java
package org.infinispan.commons.test; /** * @since 15.0 **/ public class Ansi { public static final String BLACK = "\u001b[30m"; public static final String RED = "\u001b[31m"; public static final String GREEN = "\u001b[32m"; public static final String YELLOW = "\u001b[33m"; public static final String BLUE = "\u001b[34m"; public static final String PURPLE = "\u001b[35m"; public static final String CYAN = "\u001b[36m"; public static final String WHITE = "\u001b[37m"; public static final String RESET = "\u001b[0m"; public static final String[] DISTINCT_COLORS = { fg(63), fg(208), fg(213), fg(43), fg(99), fg(159), fg(202), fg(229) }; public static final boolean useColor = !Boolean.getBoolean("ansi.strip"); private Ansi() { } public static String fg(int color) { return "\u001b[38;5;" + color + "m"; } }
941
24.459459
76
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/categories/Profiling.java
package org.infinispan.commons.test.categories; /** * JUnit category for profiling tests. */ public interface Profiling { }
127
15
47
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/categories/Unstable.java
package org.infinispan.commons.test.categories; /** * JUnit category for unstable tests. */ public interface Unstable { }
125
14.75
47
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/categories/Smoke.java
package org.infinispan.commons.test.categories; /** * JUnit category for smoke tests. */ public interface Smoke { }
119
14
47
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/categories/Stress.java
package org.infinispan.commons.test.categories; /** * JUnit category for stress tests. */ public interface Stress { }
121
14.25
47
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/categories/Java11.java
package org.infinispan.commons.test.categories; /** * JUnit category for Java11 tests */ public interface Java11 { }
120
14.125
47
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/security/TestCertificates.java
package org.infinispan.commons.test.security; import java.io.OutputStream; import java.io.Writer; import java.math.BigInteger; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import javax.security.auth.x500.X500Principal; import org.wildfly.security.x500.cert.BasicConstraintsExtension; import org.wildfly.security.x500.cert.SelfSignedX509CertificateAndSigningKey; import org.wildfly.security.x500.cert.X509CertificateBuilder; /** * @since 15.0 **/ public class TestCertificates { public static final String BASE_DN = "CN=%s,OU=Infinispan,O=JBoss,L=Red Hat"; public static final char[] KEY_PASSWORD = "secret".toCharArray(); public static final String KEY_ALGORITHM = "RSA"; public static final String KEY_SIGNATURE_ALGORITHM = "SHA256withRSA"; public static final String KEYSTORE_TYPE = KeyStore.getDefaultType(); public static final String EXTENSION = ".pfx"; private static final AtomicLong CERT_SERIAL = new AtomicLong(1); static { createKeyStores(); } public static String certificate(String name) { return baseDir().resolve(name + EXTENSION).toString(); } public static String pem(String name) { return baseDir().resolve(name + ".pem").toString(); } private static void createKeyStores() { try { // Create the CA KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey signingKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); X500Principal CA_DN = dn("CA"); KeyStore trustStore = KeyStore.getInstance(KEYSTORE_TYPE); trustStore.load(null, null); SelfSignedX509CertificateAndSigningKey ca = createSelfSignedCertificate(CA_DN, true, "ca"); trustStore.setCertificateEntry("ca", ca.getSelfSignedCertificate()); // Create a server certificate signed by the CA createSignedCertificate(signingKey, publicKey, ca, CA_DN, "server", trustStore); // Create a client certificate signed by the CA createSignedCertificate(signingKey, publicKey, ca, CA_DN, "client", trustStore); // A certificate for SNI tests createSignedCertificate(signingKey, publicKey, ca, CA_DN, "sni", trustStore); // Write the trust store try (OutputStream os = Files.newOutputStream(getCertificateFile("trust" + EXTENSION))) { trustStore.store(os, KEY_PASSWORD); } // Create an untrusted certificate createSelfSignedCertificate(CA_DN, true, "untrusted"); } catch (Exception e) { throw new RuntimeException(e); } } public static Path baseDir() { return Paths.get(System.getProperty("user.dir"), "target", "test-classes"); } private static X500Principal dn(String cn) { return new X500Principal(String.format(BASE_DN, cn)); } private static Path getCertificateFile(String name) { return baseDir().resolve(name); } private static SelfSignedX509CertificateAndSigningKey createSelfSignedCertificate(X500Principal dn, boolean isCA, String name) { SelfSignedX509CertificateAndSigningKey.Builder certificateBuilder = SelfSignedX509CertificateAndSigningKey.builder() .setDn(dn) .setSignatureAlgorithmName(KEY_SIGNATURE_ALGORITHM) .setKeyAlgorithmName(KEY_ALGORITHM); if (isCA) { certificateBuilder.addExtension(false, "BasicConstraints", "CA:true,pathlen:2147483647"); } SelfSignedX509CertificateAndSigningKey certificate = certificateBuilder.build(); X509Certificate issuerCertificate = certificate.getSelfSignedCertificate(); writeKeyStore(getCertificateFile(name + EXTENSION), ks -> { try { ks.setCertificateEntry(name, issuerCertificate); } catch (KeyStoreException e) { throw new RuntimeException(e); } }); try (Writer w = Files.newBufferedWriter(baseDir().resolve(name + ".pem"))) { w.write("-----BEGIN PRIVATE KEY-----\n"); w.write(Base64.getEncoder().encodeToString(certificate.getSigningKey().getEncoded())); w.write("\n-----END PRIVATE KEY-----\n"); w.write("-----BEGIN CERTIFICATE-----\n"); w.write(Base64.getEncoder().encodeToString(issuerCertificate.getEncoded())); w.write("\n-----END CERTIFICATE-----\n"); } catch (Exception e) { throw new RuntimeException(e); } return certificate; } private static void createSignedCertificate(PrivateKey signingKey, PublicKey publicKey, SelfSignedX509CertificateAndSigningKey ca, X500Principal issuerDN, String name, KeyStore trustStore) throws CertificateException { X509Certificate caCertificate = ca.getSelfSignedCertificate(); X509Certificate certificate = new X509CertificateBuilder() .setIssuerDn(issuerDN) .setSubjectDn(dn(name)) .setSignatureAlgorithmName(KEY_SIGNATURE_ALGORITHM) .setSigningKey(ca.getSigningKey()) .setPublicKey(publicKey) .setSerialNumber(BigInteger.valueOf(CERT_SERIAL.getAndIncrement())) .addExtension(new BasicConstraintsExtension(false, false, -1)) .build(); try { trustStore.setCertificateEntry(name, certificate); } catch (KeyStoreException e) { throw new RuntimeException(e); } writeKeyStore(getCertificateFile(name + EXTENSION), ks -> { try { ks.setCertificateEntry("ca", caCertificate); ks.setKeyEntry(name, signingKey, KEY_PASSWORD, new X509Certificate[]{certificate, caCertificate}); } catch (KeyStoreException e) { throw new RuntimeException(e); } }); } private static void writeKeyStore(Path file, Consumer<KeyStore> consumer) { try (OutputStream os = Files.newOutputStream(file)) { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); consumer.accept(keyStore); keyStore.store(os, KEY_PASSWORD); } catch (Exception e) { throw new RuntimeException(e); } } }
6,807
37.902857
131
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/junit/JUnitThreadTrackerRule.java
package org.infinispan.commons.test.junit; import org.infinispan.commons.test.ThreadLeakChecker; import org.infinispan.commons.test.TestResourceTracker; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class JUnitThreadTrackerRule implements TestRule { @Override public Statement apply(Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { String testName = description.getTestClass().getName(); if (description.getMethodName() != null) { throw new IllegalArgumentException(String.format("Please use TestThreadTrackerRule with @ClassRule, %s is using @Rule", testName)); } TestResourceTracker.testStarted(testName); ThreadLeakChecker.testStarted(testName); try { base.evaluate(); } finally { TestResourceTracker.testFinished(testName); ThreadLeakChecker.testFinished(testName); } } }; } }
1,213
33.685714
146
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/skip/OS.java
package org.infinispan.commons.test.skip; /** * 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; 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 { return UNIX; } } }
588
21.653846
97
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/skip/StringLogAppender.java
package org.infinispan.commons.test.skip; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Predicate; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.AppenderRef; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.LoggerConfig; import org.apache.logging.log4j.core.config.Property; /** * A Log4J Appender which stores logs in a StringBuilder * * @author Tristan Tarrant * @since 9.2 */ public class StringLogAppender extends AbstractAppender { private final String category; private final Level level; private final List<String> logs; private final Predicate<Thread> threadFilter; public StringLogAppender(String category, Level level, Predicate<Thread> threadFilter, Layout<?> layout) { super(StringLogAppender.class.getName(), null, layout, true, Property.EMPTY_ARRAY); this.category = category; this.level = level; this.logs = Collections.synchronizedList(new ArrayList<>()); this.threadFilter = threadFilter; } public void install() { LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); Configuration config = loggerContext.getConfiguration(); this.start(); config.addAppender(this); AppenderRef ref = AppenderRef.createAppenderRef(this.getName(), level, null); AppenderRef[] refs = new AppenderRef[]{ref}; LoggerConfig loggerConfig = LoggerConfig.createLogger(true, level, category, null, refs, null, config, null); loggerConfig.addAppender(this, null, null); config.addLogger(category, loggerConfig); loggerContext.updateLoggers(); } public void uninstall() { LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); loggerContext.getConfiguration().removeLogger(category); loggerContext.updateLoggers(); } @Override public void append(LogEvent event) { if (threadFilter.test(Thread.currentThread())) { logs.add((String) getLayout().toSerializable(event)); } } public String getLog(int index) { if (index < 0) { throw new IllegalArgumentException("Index must not be negative."); } int size = logs.size(); if (index >= size) { throw new IllegalArgumentException("Index " + index + " is out of bounds. " + (size == 0 ? "No logs recorded yet." : "Accepted values are: [0 .. " + (size - 1) + "]")); } return logs.get(index); } }
2,863
35.717949
142
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/skip/SkipTestNG.java
package org.infinispan.commons.test.skip; import java.util.Arrays; import org.testng.SkipException; /** * Allows to skip a test on certain Operation Systems. */ public class SkipTestNG { /** * Skip the test if a condition is true. */ public static void skipIf(boolean skip, String message) { if (skip) { throw new SkipException(message); } } /** * Use within a {@code @Test} method to skip that method on some OSes. * Use in a {@code @BeforeClass} method to skip all methods in a class on some OSes. */ public static void skipOnOS(OS... oses) { OS currentOs = OS.getCurrentOs(); if (Arrays.asList(oses).contains(currentOs)) { throw new SkipException("Skipping test on " + currentOs); } } /** * Use within a {@code @Test} method to run this test only on certain OSes. * Use in a {@code @BeforeClass} method to run all methods in a class only on some OSes. */ public static void onlyOnOS(OS... oses) { OS currentOs = OS.getCurrentOs(); if (!Arrays.asList(oses).contains(currentOs)) { throw new SkipException("Skipping test on " + currentOs); } } /** * Use within a {@code @Test} method to skip that method on all versions of Java equal or greater * to the one specified. * Use in a {@code @BeforeClass} method to skip all methods in a class on some JDKs. */ public static void skipSinceJDK(int major) { int version = getJDKVersion(); if (version >= major) { throw new SkipException("Skipping test on JDK " + version); } } /** * Use within a {@code @Test} method to skip that method on all versions of Java less than the one specified. * Use in a {@code @BeforeClass} method to skip all methods in a class on some JDKs. */ public static void skipBeforeJDK(int major) { int version = getJDKVersion(); if (version < major) { throw new SkipException("Skipping test on JDK " + version); } } private static int getJDKVersion() { String[] parts = System.getProperty("java.version").replaceAll("[^0-9\\.]", "").split("\\."); int version = Integer.parseInt(parts[0]); if (version == 1) version = Integer.parseInt(parts[1]); return version; } }
2,317
30.324324
112
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/skip/SkipJunit.java
package org.infinispan.commons.test.skip; import java.util.Arrays; import java.util.Objects; import java.util.function.Supplier; import org.junit.AssumptionViolatedException; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; /** * Use as a {@code @Rule} or {@code @ClassRule} to skip all methods in a class on some OSes. */ public class SkipJunit implements TestRule { private final OS[] oses; private final int jdkMajorVersion; public SkipJunit(OS... oses) { this.oses = Objects.requireNonNull(oses); this.jdkMajorVersion = -1; } public SkipJunit(int jdkMajorVersion) { this.jdkMajorVersion = jdkMajorVersion; this.oses = null; } @Override public Statement apply(Statement base, Description description) { if (oses != null) { OS os = OS.getCurrentOs(); if (!Arrays.asList(oses).contains(os)) { return base; } else { return new Statement() { @Override public void evaluate() { throw new AssumptionViolatedException("Ignoring test " + description.getDisplayName() + " on OS " + os); } }; } } else { int version = getJDKVersion(); if (version >= jdkMajorVersion) { return new Statement() { @Override public void evaluate() { throw new AssumptionViolatedException("Ignoring test " + description.getDisplayName() + " on JDK " + version); } }; } else { return base; } } } /** * Use within a {@code @Test} method to skip that method on some OSes. Use in a {@code @BeforeClass} method to skip * all methods in a class on some OSes. */ public static void skipOnOS(OS... oses) { OS os = OS.getCurrentOs(); if (Arrays.asList(oses).contains(os)) throw new AssumptionViolatedException("Skipping test on " + os); } /** * Use within a {@code @Test} method to run this test only on certain OSes. Use in a {@code @BeforeClass} method to * run all methods in a class only on some OSes. */ public static void onlyOnOS(OS... oses) { OS os = OS.getCurrentOs(); if (!Arrays.asList(oses).contains(os)) throw new AssumptionViolatedException("Skipping test on " + os); } public static void skipSinceJDK(int major) { int version = getJDKVersion(); if (version >= major) { throw new AssumptionViolatedException("Skipping test on JDK " + version); } } private static int getJDKVersion() { String[] parts = System.getProperty("java.version").replaceAll("[^0-9\\.]", "").split("\\."); int version = Integer.parseInt(parts[0]); if (version == 1) version = Integer.parseInt(parts[1]); return version; } public static void skipCondition(Supplier<Boolean> condition) { if (condition.get()) { throw new AssumptionViolatedException("Skipping test"); } } }
3,118
30.505051
128
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/test/annotation/TestForIssue.java
package org.infinispan.commons.test.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A documentation annotation for notating what JIRA issue is being tested. * <p> * Copied from <a href="https://github.com/hibernate/hibernate-orm">Hibernate ORM project</a>. * * @author Steve Ebersole */ @Retention(RetentionPolicy.SOURCE) @Target({ElementType.METHOD, ElementType.TYPE}) public @interface TestForIssue { /** * The keys of the JIRA issues tested. * * @return The JIRA issue keys */ String[] jiraKey(); }
665
23.666667
94
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/junit/ClassResource.java
package org.infinispan.commons.junit; import java.util.function.Consumer; import org.jboss.logging.Logger; import org.junit.rules.ExternalResource; /** * Use with {@link org.junit.ClassRule @ClassRule} to initialize a resource in a non-static method * and release it after all the methods in the class. * * @author Dan Berindei * @since 10.0 */ public class ClassResource<T> extends ExternalResource { private static final Logger log = Logger.getLogger(ClassResource.class); // TODO Do we need a reference to the test so we can differentiate between resources of subclasses? private T resource; private Consumer<T> closer; public ClassResource() { this.closer = r -> { try { ((AutoCloseable) r).close(); } catch (Exception e) { throw new RuntimeException(e); } }; } /** * Use a custom closer for non-{@linkplain AutoCloseable} resources. */ public ClassResource(Consumer<T> closer) { this.closer = closer; } @Override protected void after() { try { closer.accept(resource); resource = null; } catch (Throwable t) { log.errorf(t, "Failed to close resource %s", resource); } } public T cache(ExceptionSupplier<T> supplier) throws Exception { if (resource != null) { return resource; } resource = supplier.get(); if (!(resource instanceof AutoCloseable)) { throw new IllegalStateException( "Resource does not implement AutoCloseable, please set up a custom closer in the constructor"); } return resource; } public T get() { return resource; } public interface ExceptionSupplier<T> { T get() throws Exception; } }
1,781
24.457143
107
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/junit/Cleanup.java
package org.infinispan.commons.junit; import java.util.ArrayDeque; import java.util.Deque; import java.util.function.Supplier; import org.jboss.logging.Logger; import org.junit.rules.ExternalResource; /** * Use with {@link org.junit.Rule @Rule} to release resources after a method * or with {@link org.junit.ClassRule @ClassRule} to release them after all the methods in the class. * * @author Dan Berindei * @since 10.0 */ public class Cleanup extends ExternalResource { private static final Logger log = Logger.getLogger(Cleanup.class); // TODO Do we need a reference to the test so we can differentiate between resources of subclasses? private final Deque<AutoCloseable> stack = new ArrayDeque<>(); public Cleanup() { } public Cleanup(AutoCloseable resource) { stack.push(resource); } public Cleanup(AutoCloseable resource1, AutoCloseable resource2) { stack.push(resource1); stack.push(resource2); } public Cleanup(Supplier<? extends AutoCloseable> supplier) { stack.push(new SupplierCloser(supplier)); } public Cleanup(Supplier<? extends AutoCloseable> supplier1, Supplier<? extends AutoCloseable> supplier2) { stack.push(new SupplierCloser(supplier1)); stack.push(new SupplierCloser(supplier2)); } @Override protected void after() { while (!stack.isEmpty()) { AutoCloseable resource = stack.pop(); try { resource.close(); } catch (Throwable t) { log.errorf(t, "Failed to close resource %s", resource); } } } public <T extends AutoCloseable> T add(T resource) { stack.push(resource); return resource; } public <T extends AutoCloseable> void add(T resource1, T resource2) { stack.push(resource1); stack.push(resource2); } public <T> T add(ExceptionConsumer<T> closer, T resource) { stack.push(new NamedCloser<>(closer, resource)); return resource; } public <T> void add(ExceptionConsumer<T> closer, T resource1, T resource2) { stack.push(new NamedCloser<>(closer, resource1)); stack.push(new NamedCloser<>(closer, resource2)); } private static class NamedCloser<T> implements AutoCloseable { private final ExceptionConsumer<T> closer; private final T resource; NamedCloser(ExceptionConsumer<T> closer, T resource) { this.closer = closer; this.resource = resource; } @Override public void close() throws Exception { closer.accept(resource); } @Override public String toString() { return resource.toString(); } } private static class SupplierCloser implements AutoCloseable { private final Supplier<? extends AutoCloseable> supplier; SupplierCloser(Supplier<? extends AutoCloseable> supplier) { this.supplier = supplier; } @Override public void close() throws Exception { supplier.get().close(); } @Override public String toString() { return String.valueOf(supplier.get()); } } public interface ExceptionConsumer<T> { void accept(T ref) throws Exception; } }
3,217
26.504274
109
java
null
infinispan-main/commons-test/src/main/java/org/infinispan/commons/lambda/NamedLambdas.java
package org.infinispan.commons.lambda; import java.util.function.BiConsumer; import java.util.function.Predicate; public class NamedLambdas { public static <T, U> BiConsumer<T, U> of(String description, BiConsumer<T, U> consumer) { return new NamedBiConsumer<>(description, consumer); } public static <T> Predicate<T> of(String description, Predicate<T> predicate) { return new NamedPredicate(description, predicate); } public static Runnable of(String description, Runnable runnable) { return new NamedRunnable(description, runnable); } private static class NamedPredicate<T> implements Predicate<T> { private String description; private Predicate<T> predicate; public NamedPredicate(String description, Predicate<T> predicate) { this.description = description; this.predicate = predicate; } @Override public boolean test(T t) { return predicate.test(t); } @Override public Predicate<T> and(Predicate<? super T> other) { return predicate.and(other); } @Override public Predicate<T> negate() { return predicate.negate(); } @Override public Predicate<T> or(Predicate<? super T> other) { return predicate.or(other); } @Override public String toString() { return this.description; } } private static class NamedBiConsumer<T, U> implements BiConsumer<T, U> { private String description; private BiConsumer<T, U> biConsumer; public NamedBiConsumer(String description, BiConsumer<T, U> biConsumer) { this.description = description; this.biConsumer = biConsumer; } @Override public void accept(T t, U u) { this.biConsumer.accept(t, u); } @Override public BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) { return this.biConsumer.andThen(after); } @Override public String toString() { return this.description; } } private static class NamedRunnable implements Runnable { private final String description; private final Runnable runnable; private NamedRunnable(String description, Runnable runnable) { this.description = description; this.runnable = runnable; } @Override public void run() { runnable.run(); } @Override public String toString() { return this.description; } } }
2,559
23.854369
92
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/DistributedMultimapCacheTest.java
package org.infinispan.multimap.impl; import static java.lang.String.format; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.multimap.impl.MultimapTestUtils.EMPTY_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.JULIEN; import static org.infinispan.multimap.impl.MultimapTestUtils.NAMES_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.NULL_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.NULL_USER; import static org.infinispan.multimap.impl.MultimapTestUtils.OIHANA; import static org.infinispan.multimap.impl.MultimapTestUtils.PEPE; import static org.infinispan.multimap.impl.MultimapTestUtils.RAMON; import static org.infinispan.multimap.impl.MultimapTestUtils.assertMultimapCacheSize; import static org.infinispan.multimap.impl.MultimapTestUtils.putValuesOnMultimapCache; import static org.infinispan.commons.test.Exceptions.expectException; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.container.DataContainer; import org.infinispan.container.entries.ImmortalCacheEntry; import org.infinispan.container.entries.InternalCacheEntry; import org.infinispan.distribution.BaseDistFunctionalTest; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.multimap.api.embedded.EmbeddedMultimapCacheManagerFactory; import org.infinispan.multimap.api.embedded.MultimapCache; import org.infinispan.multimap.api.embedded.MultimapCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.remoting.transport.Address; import org.infinispan.test.data.Person; import org.testng.annotations.Test; @Test(groups = "functional", testName = "distribution.DistributedMultimapCacheTest") public class DistributedMultimapCacheTest extends BaseDistFunctionalTest<String, Collection<Person>> { protected Map<Address, MultimapCache<String, Person>> multimapCacheCluster = new HashMap<>(); protected boolean fromOwner; public DistributedMultimapCacheTest fromOwner(boolean fromOwner) { this.fromOwner = fromOwner; return this; } @Override protected String[] parameterNames() { return concat(super.parameterNames(), "fromOwner"); } @Override protected Object[] parameterValues() { return concat(super.parameterValues(), fromOwner ? Boolean.TRUE : Boolean.FALSE); } @Override public Object[] factory() { return new Object[]{ new DistributedMultimapCacheTest().fromOwner(false).cacheMode(CacheMode.DIST_SYNC).transactional(false), new DistributedMultimapCacheTest().fromOwner(true).cacheMode(CacheMode.DIST_SYNC).transactional(false), }; } @Override protected void createCacheManagers() throws Throwable { super.createCacheManagers(); for (EmbeddedCacheManager cacheManager : cacheManagers) { MultimapCacheManager multimapCacheManager = EmbeddedMultimapCacheManagerFactory.from(cacheManager); multimapCacheCluster.put(cacheManager.getAddress(), multimapCacheManager.get(cacheName)); } } @Override protected SerializationContextInitializer getSerializationContext() { return MultimapSCI.INSTANCE; } @Override protected void initAndTest() { assertMultimapCacheSize(multimapCacheCluster, 0); putValuesOnMultimapCache(getMultimapCacheMember(), NAMES_KEY, OIHANA); assertValuesAndOwnership(NAMES_KEY, OIHANA); } public void testPut() { initAndTest(); MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN); assertValuesAndOwnership(NAMES_KEY, JULIEN); putValuesOnMultimapCache(multimapCache, EMPTY_KEY, RAMON); assertValuesAndOwnership(EMPTY_KEY, RAMON); putValuesOnMultimapCache(multimapCache, NAMES_KEY, PEPE); assertValuesAndOwnership(NAMES_KEY, PEPE); } public void testPutDuplicates() { initAndTest(); MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN); putValuesOnMultimapCache(multimapCache, NAMES_KEY, RAMON); assertValuesAndOwnership(NAMES_KEY, JULIEN); assertValuesAndOwnership(NAMES_KEY, RAMON); assertEquals(3, await(multimapCache.size()).intValue()); putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN); assertValuesAndOwnership(NAMES_KEY, JULIEN); assertValuesAndOwnership(NAMES_KEY, RAMON); assertEquals(3, await(multimapCache.size()).intValue()); putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN); assertValuesAndOwnership(NAMES_KEY, JULIEN); assertValuesAndOwnership(NAMES_KEY, RAMON); assertEquals(3, await(multimapCache.size()).intValue()); } public void testRemoveKey() { initAndTest(); MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); await( multimapCache.remove(NAMES_KEY, OIHANA).thenCompose(r1 -> { assertTrue(r1); return multimapCache.get(NAMES_KEY).thenAccept(v -> assertTrue(v.isEmpty())); }) ); assertRemovedOnAllCaches(NAMES_KEY); putValuesOnMultimapCache(multimapCache, EMPTY_KEY, RAMON); await(multimapCache.remove(EMPTY_KEY).thenCompose(r1 -> { assertTrue(r1); return multimapCache.get(EMPTY_KEY).thenAccept(v -> assertTrue(v.isEmpty())); })); } public void testRemoveKeyValue() { initAndTest(); MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); await(multimapCache.remove("unexistingKey", OIHANA).thenAccept(r -> assertFalse(r))); assertValuesAndOwnership(NAMES_KEY, OIHANA); await( multimapCache.remove(NAMES_KEY, OIHANA).thenCompose(r1 -> { assertTrue(r1); return multimapCache.get(NAMES_KEY).thenAccept(v -> assertTrue(v.isEmpty())); } ) ); assertRemovedOnAllCaches(NAMES_KEY); putValuesOnMultimapCache(multimapCache, EMPTY_KEY, RAMON); await(multimapCache.remove(EMPTY_KEY, RAMON).thenCompose(r1 -> { assertTrue(r1); return multimapCache.get(EMPTY_KEY).thenAccept(v -> assertTrue(v.isEmpty())); })); putValuesOnMultimapCache(multimapCache, NAMES_KEY, PEPE); await(multimapCache.remove(NAMES_KEY, PEPE).thenCompose(r1 -> { assertTrue(r1); return multimapCache.get(NAMES_KEY).thenAccept(v -> assertTrue(v.isEmpty())); })); } public void testRemoveWithPredicate() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(); await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r1 -> multimapCache.put(NAMES_KEY, JULIEN)) .thenCompose(r2 -> multimapCache.get(NAMES_KEY)) .thenAccept(v -> assertEquals(2, v.size())) ); assertValuesAndOwnership(NAMES_KEY, OIHANA); assertValuesAndOwnership(NAMES_KEY, JULIEN); MultimapCache<String, Person> multimapCache2 = getMultimapCacheMember(NAMES_KEY); await( multimapCache2.remove(o -> o.getName().contains("Ka")) .thenCompose(r1 -> multimapCache2.get(NAMES_KEY)) .thenAccept(v -> assertEquals(2, v.size()) ) ); assertValuesAndOwnership(NAMES_KEY, OIHANA); assertValuesAndOwnership(NAMES_KEY, JULIEN); await( multimapCache.remove(o -> o.getName().contains("Ju")) .thenCompose(r1 -> multimapCache.get(NAMES_KEY)) .thenAccept(v -> assertEquals(1, v.size()) ) ); assertValuesAndOwnership(NAMES_KEY, OIHANA); assertKeyValueNotFoundInAllCaches(NAMES_KEY, JULIEN); await( multimapCache.remove(o -> o.getName().contains("Oi")) .thenCompose(r1 -> multimapCache.get(NAMES_KEY)) .thenAccept(v -> assertTrue(v.isEmpty()) ) ); assertRemovedOnAllCaches(NAMES_KEY); } public void testGet() { initAndTest(); MultimapCache<String, Person> multimapCache = getMultimapCacheMember(); await(multimapCache.get(NAMES_KEY).thenAccept(v -> { assertTrue(v.contains(OIHANA)); })); await(multimapCache.getEntry(NAMES_KEY).thenAccept(v -> { assertTrue(v.isPresent() && v.get().getKey().equals(NAMES_KEY) && v.get().getValue().contains(OIHANA)); })); await(multimapCache.put(EMPTY_KEY, RAMON).thenCompose(r3 -> multimapCache.get(EMPTY_KEY)).thenAccept(v -> { assertTrue(v.contains(RAMON)); })); } public void testGetEmpty() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(); await( multimapCache.get(NAMES_KEY) .thenAccept(v -> { assertTrue(v.isEmpty()); } ) ); await(multimapCache.getEntry(NAMES_KEY).thenAccept(v -> { assertTrue(!v.isPresent()); })); } public void testGetAndModifyResults() { initAndTest(); MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); Person pepe = new Person("Pepe"); await( multimapCache.get(NAMES_KEY) .thenAccept(v -> { List<Person> modifiedList = new ArrayList<>(v); modifiedList.add(pepe); } ) ); assertKeyValueNotFoundInAllCaches(NAMES_KEY, pepe); } public void testContainsKey() { initAndTest(); multimapCacheCluster.values().forEach(mc -> { await( mc.containsKey("other") .thenAccept(containsKey -> assertFalse(containsKey)) ); await( mc.containsKey(NAMES_KEY) .thenAccept(containsKey -> assertTrue(containsKey)) ); await( mc.containsKey(EMPTY_KEY) .thenAccept(containsKey -> assertFalse(containsKey)) ); }); } public void testContainsValue() { initAndTest(); MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); putValuesOnMultimapCache(multimapCache, NAMES_KEY, PEPE); multimapCacheCluster.values().forEach(mc -> { await( mc.containsValue(RAMON) .thenAccept(containsValue -> assertFalse(containsValue)) ); await( mc.containsValue(OIHANA) .thenAccept(containsValue -> assertTrue(containsValue)) ); await( mc.containsValue(PEPE) .thenAccept(containsValue -> assertTrue(containsValue)) ); }); } public void testContainEntry() { initAndTest(); putValuesOnMultimapCache(multimapCacheCluster, EMPTY_KEY, PEPE); multimapCacheCluster.values().forEach(mc -> { await( mc.containsEntry(NAMES_KEY, RAMON) .thenAccept(containsValue -> assertFalse(containsValue)) ); await( mc.containsEntry(NAMES_KEY, OIHANA) .thenAccept(containsValue -> assertTrue(containsValue)) ); await( mc.containsEntry(EMPTY_KEY, RAMON) .thenAccept(containsValue -> assertFalse(containsValue)) ); await( mc.containsEntry(EMPTY_KEY, PEPE) .thenAccept(containsValue -> assertTrue(containsValue)) ); }); } public void testSize() { String anotherKey = "firstNames"; MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r1 -> multimapCache.put(NAMES_KEY, JULIEN)) .thenCompose(r2 -> multimapCache.put(anotherKey, OIHANA)) .thenCompose(r3 -> multimapCache.put(anotherKey, JULIEN)) .thenCompose(r4 -> multimapCache.size()) .thenAccept(s -> { assertEquals(4, s.intValue()); assertValuesAndOwnership(NAMES_KEY, JULIEN); assertValuesAndOwnership(NAMES_KEY, OIHANA); assertValuesAndOwnership(anotherKey, JULIEN); assertValuesAndOwnership(anotherKey, OIHANA); }) .thenCompose(r1 -> multimapCache.remove(NAMES_KEY, JULIEN)) .thenCompose(r2 -> multimapCache.remove(NAMES_KEY, OIHANA)) .thenCompose(r2 -> multimapCache.remove(NAMES_KEY, JULIEN)) .thenCompose(r3 -> multimapCache.put(anotherKey, JULIEN)) .thenCompose(r4 -> multimapCache.size()) .thenAccept(s -> { assertEquals(2, s.intValue()); assertValuesAndOwnership(anotherKey, JULIEN); assertValuesAndOwnership(anotherKey, OIHANA); }) ); } public void testGetEntry() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); await( multimapCache.getEntry(NAMES_KEY) .thenAccept(maybeEntry -> { assertFalse(NAMES_KEY, maybeEntry.isPresent()); } ) ); await( multimapCache.put(NAMES_KEY, JULIEN) .thenCompose(r3 -> multimapCache.getEntry(NAMES_KEY)) .thenAccept(maybeEntry -> { assertTrue(NAMES_KEY, maybeEntry.isPresent()); } ) ); await(multimapCache.put(EMPTY_KEY, RAMON).thenCompose(r3 -> multimapCache.getEntry(EMPTY_KEY)).thenAccept(v -> { assertTrue(v.isPresent() && v.get().getKey().equals(EMPTY_KEY) && v.get().getValue().contains(RAMON)); })); } public void testPutWithNull() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); expectException(NullPointerException.class, "key can't be null", () -> multimapCache.put(NULL_KEY, OIHANA)); expectException(NullPointerException.class, "value can't be null", () -> multimapCache.put(NAMES_KEY, NULL_USER)); } public void testGetWithNull() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); expectException(NullPointerException.class, "key can't be null", () -> multimapCache.get(NULL_KEY)); } public void testGetEntryWithNull() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); expectException(NullPointerException.class, "key can't be null", () -> multimapCache.getEntry(NULL_KEY)); } public void testRemoveKeyValueWithNull() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); expectException(NullPointerException.class, "key can't be null", () -> multimapCache.remove(NULL_KEY, RAMON)); expectException(NullPointerException.class, "value can't be null", () -> multimapCache.remove(NAMES_KEY, NULL_USER)); } public void testRemoveKeyWithNulll() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); expectException(NullPointerException.class, "key can't be null", () -> multimapCache.remove((String) NULL_KEY)); } public void testRemoveWithNullPredicate() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); expectException(NullPointerException.class, "predicate can't be null", () -> multimapCache.remove((Predicate<? super Person>) null)); } public void testContainsKeyWithNull() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); expectException(NullPointerException.class, "key can't be null", () -> multimapCache.containsKey(NULL_KEY)); } public void testContainsValueWithNull() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); expectException(NullPointerException.class, "value can't be null", () -> multimapCache.containsValue(NULL_USER)); } public void testContainsEntryWithNull() { MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); expectException(NullPointerException.class, "key can't be null", () -> multimapCache.containsEntry(NULL_KEY, OIHANA)); expectException(NullPointerException.class, "value can't be null", () -> multimapCache.containsEntry(NAMES_KEY, NULL_USER)); } protected MultimapCache getMultimapCacheMember() { return multimapCacheCluster.values().stream().findFirst().orElseThrow(() -> new IllegalStateException("Cluster is empty")); } protected MultimapCache getMultimapCacheMember(String key) { Cache<String, Collection<Person>> cache = fromOwner ? getFirstOwner(key) : getFirstNonOwner(key); return multimapCacheCluster.get(cache.getCacheManager().getAddress()); } protected MultimapCache getMultimapCacheFirstOwner(String key) { Cache<String, Collection<Person>> cache = getFirstOwner(key); return multimapCacheCluster.get(cache.getCacheManager().getAddress()); } protected void assertValuesAndOwnership(String key, Person value) { assertOwnershipAndNonOwnership(key, l1CacheEnabled); assertOnAllCaches(key, value); } protected void assertKeyValueNotFoundInAllCaches(String key, Person value) { for (Map.Entry<Address, MultimapCache<String, Person>> entry : multimapCacheCluster.entrySet()) { await(entry.getValue().get(key).thenAccept(v -> { assertNotNull(format("values on the key %s must be not null", key), v); assertFalse(format("values on the key '%s' must not contain '%s' on node '%s'", key, value, entry.getKey()), v.contains(value)); }) ); } } protected void assertKeyValueFoundInOwners(String key, Person value) { Cache<String, Collection<Person>> firstOwner = getFirstOwner(key); Cache<String, Collection<Person>> secondNonOwner = getSecondNonOwner(key); MultimapCache<String, Person> mcFirstOwner = multimapCacheCluster.get(firstOwner.getCacheManager().getAddress()); MultimapCache<String, Person> mcSecondOwner = multimapCacheCluster.get(secondNonOwner.getCacheManager().getAddress()); await(mcFirstOwner.get(key).thenAccept(v -> { assertTrue(format("firstOwner '%s' must contain key '%s' value '%s' pair", firstOwner.getCacheManager().getAddress(), key, value), v.contains(value)); }) ); await(mcSecondOwner.get(key).thenAccept(v -> { assertTrue(format("secondOwner '%s' must contain key '%s' value '%s' pair", secondNonOwner.getCacheManager().getAddress(), key, value), v.contains(value)); }) ); } @Override protected void assertOwnershipAndNonOwnership(Object key, boolean allowL1) { for (Cache cache : caches) { Object keyToBeChecked = cache.getAdvancedCache().getKeyDataConversion().toStorage(key); DataContainer dc = cache.getAdvancedCache().getDataContainer(); InternalCacheEntry ice = dc.get(keyToBeChecked); if (isOwner(cache, keyToBeChecked)) { assertNotNull(ice); assertTrue(ice instanceof ImmortalCacheEntry); } else { if (allowL1) { assertTrue("ice is null or L1Entry", ice == null || ice.isL1Entry()); } else { // Segments no longer owned are invalidated asynchronously eventuallyEquals("Fail on non-owner cache " + addressOf(cache) + ": dc.get(" + key + ")", null, () -> dc.get(keyToBeChecked)); } } } } protected void assertOnAllCaches(Object key, Person value) { for (Map.Entry<Address, MultimapCache<String, Person>> entry : multimapCacheCluster.entrySet()) { await(entry.getValue().get((String) key).thenAccept(v -> { assertNotNull(format("values on the key %s must be not null", key), v); assertTrue(format("values on the key '%s' must contain '%s' on node '%s'", key, value, entry.getKey()), v.contains(value)); }) ); } } }
21,234
37.963303
170
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/DistributedSetTest.java
package org.infinispan.multimap.impl; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.multimap.impl.MultimapTestUtils.ELAIA; import static org.infinispan.multimap.impl.MultimapTestUtils.FELIX; import static org.infinispan.multimap.impl.MultimapTestUtils.NAMES_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.OIHANA; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.distribution.BaseDistFunctionalTest; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.remoting.transport.Address; import org.infinispan.test.data.Person; import org.testng.annotations.Test; @Test(groups = "functional", testName = "distribution.DistributedSetTest") public class DistributedSetTest extends BaseDistFunctionalTest<String, Collection<Person>> { protected Map<Address, EmbeddedSetCache<String, Person>> listCluster = new HashMap<>(); protected boolean fromOwner; public DistributedSetTest fromOwner(boolean fromOwner) { this.fromOwner = fromOwner; return this; } @Override protected void createCacheManagers() throws Throwable { super.createCacheManagers(); for (EmbeddedCacheManager cm : cacheManagers) { listCluster.put(cm.getAddress(), new EmbeddedSetCache<String, Person>(cm.getCache(cacheName))); } } @Override protected SerializationContextInitializer getSerializationContext() { return MultimapSCIImpl.INSTANCE; } @Override protected String[] parameterNames() { return concat(super.parameterNames(), "fromOwner"); } @Override protected Object[] parameterValues() { return concat(super.parameterValues(), fromOwner ? Boolean.TRUE : Boolean.FALSE); } @Override public Object[] factory() { return new Object[] { new DistributedSetTest().fromOwner(false).cacheMode(CacheMode.DIST_SYNC).transactional(false), new DistributedSetTest().fromOwner(true).cacheMode(CacheMode.DIST_SYNC).transactional(false), }; } @Override protected void initAndTest() { for (var set : listCluster.values()) { assertThat(await(set.size(NAMES_KEY))).isEqualTo(0L); } } protected EmbeddedSetCache<String, Person> getSetCacheMember() { return listCluster.values().stream().findFirst().orElseThrow(() -> new IllegalStateException("Cluster is empty")); } @Test public void testAdd() { initAndTest(); EmbeddedSetCache<String, Person> set = getSetCacheMember(); await(set.add(NAMES_KEY, OIHANA)); assertValuesAndOwnership(NAMES_KEY, OIHANA); await(set.add(NAMES_KEY, ELAIA)); assertValuesAndOwnership(NAMES_KEY, ELAIA); } @Test public void testGet() { testAdd(); EmbeddedSetCache<String, Person> set = getSetCacheMember(); set.get(NAMES_KEY).thenAccept(resultSet -> assertThat(resultSet).containsExactlyInAnyOrder(ELAIA, OIHANA)); } @Test public void testSize() { initAndTest(); EmbeddedSetCache<String, Person> set = getSetCacheMember(); await( set.add(NAMES_KEY, OIHANA) .thenCompose(r1 -> set.add(NAMES_KEY, ELAIA)) .thenCompose(r1 -> set.add(NAMES_KEY, FELIX)) .thenCompose(r1 -> set.add(NAMES_KEY, OIHANA)) .thenCompose(r1 -> set.size(NAMES_KEY)) .thenAccept(size -> assertThat(size).isEqualTo(3)) ); } @Test public void testSet() { initAndTest(); EmbeddedSetCache<String, Person> set = getSetCacheMember(); Set<Person> pers = Set.of(OIHANA, ELAIA); await(set.set(NAMES_KEY, pers)); assertValuesAndOwnership(NAMES_KEY, OIHANA); assertValuesAndOwnership(NAMES_KEY, ELAIA); } protected void assertValuesAndOwnership(String key, Person value) { assertOwnershipAndNonOwnership(key, l1CacheEnabled); assertOnAllCaches(key, value); } protected void assertOnAllCaches(Object key, Person value) { for (Map.Entry<Address, EmbeddedSetCache<String, Person>> entry : listCluster.entrySet()) { var set = await(entry.getValue().get((String) key)); assertNotNull(format("values on the key %s must be not null", key), set); assertTrue(format("values on the key '%s' must contain '%s' on node '%s'", key, value, entry.getKey()), set.contains(value)); } } }
4,824
33.963768
120
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/EmbeddedMultimapCacheTest.java
package org.infinispan.multimap.impl; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.multimap.impl.MultimapTestUtils.EMPTY_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.JULIEN; import static org.infinispan.multimap.impl.MultimapTestUtils.KOLDO; import static org.infinispan.multimap.impl.MultimapTestUtils.NAMES_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.NULL_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.NULL_USER; import static org.infinispan.multimap.impl.MultimapTestUtils.OIHANA; import static org.infinispan.multimap.impl.MultimapTestUtils.PEPE; import static org.infinispan.multimap.impl.MultimapTestUtils.RAMON; import static org.infinispan.multimap.impl.MultimapTestUtils.putValuesOnMultimapCache; import static org.infinispan.commons.test.Exceptions.expectException; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.Predicate; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.container.entries.CacheEntry; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.multimap.api.embedded.EmbeddedMultimapCacheManagerFactory; import org.infinispan.multimap.api.embedded.MultimapCache; import org.infinispan.multimap.api.embedded.MultimapCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.data.Person; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; /** * Single Multimap Cache Test * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ @Test(groups = "functional", testName = "multimap.EmbeddedMultimapCacheTest") public class EmbeddedMultimapCacheTest extends SingleCacheManagerTest { protected MultimapCache<String, Person> multimapCache; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { // start a single cache instance EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(MultimapSCI.INSTANCE); cm.defineConfiguration("test", new ConfigurationBuilder().build()); MultimapCacheManager multimapCacheManager = EmbeddedMultimapCacheManagerFactory.from(cm); multimapCache = multimapCacheManager.get("test"); cm.getClassAllowList().addClasses(SuperPerson.class); return cm; } public void testSupportsDuplicates() { assertFalse(multimapCache.supportsDuplicates()); } public void testPut() { await( multimapCache.put(NAMES_KEY, JULIEN) .thenCompose(r1 -> multimapCache.put(NAMES_KEY, OIHANA)) .thenCompose(r2 -> multimapCache.put(NAMES_KEY, JULIEN)) .thenCompose(r3 -> multimapCache.get(NAMES_KEY)) .thenAccept(v -> { assertTrue(v.contains(JULIEN)); assertEquals(1, v.stream().filter(n -> n.equals(JULIEN)).count()); } ) ); await( multimapCache.get(NAMES_KEY).thenAccept(v -> { assertFalse(v.contains(KOLDO)); assertEquals(2, v.size()); } ) ); await( multimapCache.put(EMPTY_KEY, RAMON) .thenCompose(r1 -> multimapCache.get(EMPTY_KEY) .thenAccept(v -> { assertTrue(v.contains(RAMON)); assertEquals(1, v.stream().filter(n -> n.equals(RAMON)).count()); })) ); await( multimapCache.put(NAMES_KEY, PEPE) .thenCompose(r1 -> multimapCache.get(NAMES_KEY) .thenAccept(v -> { assertTrue(v.contains(PEPE)); assertEquals(1, v.stream().filter(n -> n.equals(PEPE)).count()); })) ); } public void testPutDuplicates() { await(multimapCache.put(NAMES_KEY, JULIEN) .thenCompose(r1 -> multimapCache.put(NAMES_KEY, RAMON).thenCompose(r2 -> multimapCache.get(NAMES_KEY).thenAccept(v -> { assertTrue(v.contains(JULIEN)); assertEquals(1, v.stream().filter(n -> n.equals(JULIEN)).count()); assertTrue(v.contains(RAMON)); assertEquals(1, v.stream().filter(n -> n.equals(RAMON)).count()); }).thenCompose(r3 -> multimapCache.size()).thenAccept(v -> { assertEquals(2, v.intValue()); }).thenCompose(r4 -> multimapCache.put(NAMES_KEY, JULIEN).thenCompose(r5 -> multimapCache.get(NAMES_KEY)).thenAccept(v -> { assertTrue(v.contains(JULIEN)); assertEquals(1, v.stream().filter(n -> n.equals(JULIEN)).count()); assertTrue(v.contains(RAMON)); assertEquals(1, v.stream().filter(n -> n.equals(RAMON)).count()); }).thenCompose(r3 -> multimapCache.size()).thenAccept(v -> { assertEquals(2, v.intValue()); }).thenCompose(r5 -> multimapCache.put(NAMES_KEY, JULIEN).thenCompose(r6 -> multimapCache.get(NAMES_KEY)).thenAccept(v -> { assertTrue(v.contains(JULIEN)); assertEquals(1, v.stream().filter(n -> n.equals(JULIEN)).count()); assertTrue(v.contains(RAMON)); assertEquals(1, v.stream().filter(n -> n.equals(RAMON)).count()); }).thenCompose(r7 -> multimapCache.size()).thenAccept(v -> { assertEquals(2, v.intValue()); }) ))))); } public void testRemoveKey() { await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r1 -> multimapCache.size()) .thenAccept(s -> assertEquals(1, s.intValue())) ); await( multimapCache.remove(NAMES_KEY, OIHANA).thenCompose(r1 -> { assertTrue(r1); return multimapCache.get(NAMES_KEY).thenAccept(v -> assertTrue(v.isEmpty())); }) ); await(multimapCache.remove(NAMES_KEY).thenAccept(r -> assertFalse(r))); await( multimapCache.put(EMPTY_KEY, RAMON) .thenCompose(r1 -> multimapCache.size()) .thenAccept(s -> assertEquals(1, s.intValue())) ); await( multimapCache.remove(EMPTY_KEY, RAMON).thenCompose(r1 -> { assertTrue(r1); return multimapCache.get(EMPTY_KEY).thenAccept(v -> assertTrue(v.isEmpty())); }) ); } public void testRemoveKeyValue() { await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r1 -> multimapCache.size()) .thenAccept(s -> assertEquals(1, s.intValue())) ); await(multimapCache.remove("unexistingKey", OIHANA).thenAccept(r -> assertFalse(r))); await( multimapCache.remove(NAMES_KEY, JULIEN).thenCompose(r1 -> { assertFalse(r1); return multimapCache.get(NAMES_KEY).thenAccept(v -> assertEquals(1, v.size())); } ) ); await( multimapCache.remove(NAMES_KEY, OIHANA).thenCompose(r1 -> { assertTrue(r1); return multimapCache.get(NAMES_KEY).thenAccept(v -> assertTrue(v.isEmpty())); } ) ); await(multimapCache.size().thenAccept(s -> assertEquals(0, s.intValue()))); await( multimapCache.put(EMPTY_KEY, RAMON) .thenCompose(r1 -> multimapCache.size()) .thenAccept(s -> assertEquals(1, s.intValue())) ); await( multimapCache.remove(EMPTY_KEY, RAMON).thenCompose(r1 -> { assertTrue(r1); return multimapCache.get(EMPTY_KEY).thenAccept(v -> assertTrue(v.isEmpty())); } ) ); await( multimapCache.put(NAMES_KEY, PEPE) .thenCompose(r1 -> multimapCache.size()) .thenAccept(s -> assertEquals(1, s.intValue())) ); await( multimapCache.remove(NAMES_KEY, PEPE).thenCompose(r1 -> { assertTrue(r1); return multimapCache.get(NAMES_KEY).thenAccept(v -> assertTrue(v.isEmpty())); } ) ); } public void testRemoveWithPredicate() { await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r1 -> multimapCache.put(NAMES_KEY, JULIEN)) .thenCompose(r2 -> multimapCache.get(NAMES_KEY)) .thenAccept(v -> assertEquals(2, v.size())) ); await( multimapCache.remove(o -> o.getName().contains("Ka")) .thenCompose(r1 -> multimapCache.get(NAMES_KEY)) .thenAccept(v -> assertEquals(2, v.size()) ) ); await( multimapCache.remove(o -> o.getName().contains("Ju")) .thenCompose(r1 -> multimapCache.get(NAMES_KEY)) .thenAccept(v -> assertEquals(1, v.size()) ) ); await( multimapCache.remove(o -> o.getName().contains("Oi")) .thenCompose(r1 -> multimapCache.get(NAMES_KEY)) .thenAccept(v -> assertTrue(v.isEmpty()) ) ); } public void testGetAndModifyResults() { Person pepe = new Person("Pepe"); await( multimapCache.put(NAMES_KEY, JULIEN) .thenCompose(r1 -> multimapCache.put(NAMES_KEY, OIHANA)) .thenCompose(r2 -> multimapCache.put(NAMES_KEY, RAMON)) .thenCompose(r3 -> multimapCache.get(NAMES_KEY)) .thenAccept(v -> { assertEquals(3, v.size()); List<Person> modifiedList = new ArrayList<>(v); modifiedList.add(pepe); assertEquals(3, v.size()); assertEquals(4, modifiedList.size()); } ) ); await( multimapCache.get(NAMES_KEY).thenAccept(v -> { assertFalse(v.contains(pepe)); assertEquals(3, v.size()); } ) ); } public void testSize() { String anotherKey = "firstNames"; await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r1 -> multimapCache.put(NAMES_KEY, JULIEN)) .thenCompose(r2 -> multimapCache.put(anotherKey, OIHANA)) .thenCompose(r3 -> multimapCache.put(anotherKey, JULIEN)) .thenCompose(r4 -> multimapCache.size()) .thenAccept(s -> { assertEquals(4, s.intValue()); }) .thenCompose(r1 -> multimapCache.remove(NAMES_KEY, JULIEN)) .thenCompose(r2 -> multimapCache.remove(NAMES_KEY, OIHANA)) .thenCompose(r2 -> multimapCache.remove(NAMES_KEY, JULIEN)) .thenCompose(r3 -> multimapCache.put(anotherKey, JULIEN)) .thenCompose(r4 -> multimapCache.size()) .thenAccept(s -> { assertEquals(2, s.intValue()); }) ); } public void testContainsKey() { await( multimapCache.containsKey(NAMES_KEY) .thenAccept(containsKey -> assertFalse(containsKey)) ); await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r -> multimapCache.containsKey(NAMES_KEY)) .thenAccept(containsKey -> assertTrue(containsKey)) ); await( multimapCache.put(EMPTY_KEY, KOLDO) .thenCompose(r -> multimapCache.containsKey(EMPTY_KEY)) .thenAccept(containsKey -> assertTrue(containsKey)) ); } public void testContainsValue() { await( multimapCache.containsValue(OIHANA) .thenAccept(containsValue -> assertFalse(containsValue)) ); putValuesOnMultimapCache(multimapCache, NAMES_KEY, OIHANA, JULIEN, RAMON, KOLDO, PEPE); await( multimapCache.containsValue(RAMON) .thenAccept(containsValue -> assertTrue(containsValue)) ); await( multimapCache.containsValue(PEPE) .thenAccept(containsValue -> assertTrue(containsValue)) ); } public void testContainEntry() { await( multimapCache.containsEntry(NAMES_KEY, OIHANA) .thenAccept(containsEntry -> assertFalse(containsEntry)) ); await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r -> multimapCache.containsEntry(NAMES_KEY, OIHANA)) .thenAccept(containsEntry -> assertTrue(containsEntry)) ); await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r -> multimapCache.containsEntry(NAMES_KEY, JULIEN)) .thenAccept(containsEntry -> assertFalse(containsEntry)) ); await( multimapCache.put(NAMES_KEY, PEPE) .thenCompose(r -> multimapCache.containsEntry(NAMES_KEY, PEPE)) .thenAccept(containsEntry -> assertTrue(containsEntry)) ); } public void testGetEntry() { await( multimapCache.getEntry(NAMES_KEY) .thenAccept(maybeEntry -> { assertFalse(NAMES_KEY, maybeEntry.isPresent()); } ) ); await( multimapCache.put(NAMES_KEY, JULIEN) .thenCompose(r3 -> multimapCache.getEntry(NAMES_KEY)) .thenAccept(maybeEntry -> { assertTrue(NAMES_KEY, maybeEntry.isPresent()); CacheEntry<String, Collection<Person>> entry = maybeEntry.get(); assertEquals(NAMES_KEY, entry.getKey()); assertTrue(entry.getValue().contains(JULIEN)); } ) ); await(multimapCache.put(EMPTY_KEY, RAMON).thenCompose(r3 -> multimapCache.getEntry(EMPTY_KEY)).thenAccept(v -> { assertTrue(v.isPresent() && v.get().getKey().equals(EMPTY_KEY) && v.get().getValue().contains(RAMON)); })); } public void testPutWithNull() { expectException(NullPointerException.class, "key can't be null", () -> multimapCache.put(NULL_KEY, OIHANA)); expectException(NullPointerException.class, "value can't be null", () -> multimapCache.put(NAMES_KEY, NULL_USER)); } public void testGetWithNull() { expectException(NullPointerException.class, "key can't be null", () -> multimapCache.get(NULL_KEY)); } public void testGetEntryWithNull() { expectException(NullPointerException.class, "key can't be null", () -> multimapCache.getEntry(NULL_KEY)); } public void testRemoveKeyValueWithNull() { expectException(NullPointerException.class, "key can't be null", () -> multimapCache.remove(NULL_KEY, RAMON)); expectException(NullPointerException.class, "value can't be null", () -> multimapCache.remove(NAMES_KEY, NULL_USER)); } public void testRemoveKeyWithNulll() { expectException(NullPointerException.class, "key can't be null", () -> multimapCache.remove((String) NULL_KEY)); } public void testRemoveWithNullPredicate() { expectException(NullPointerException.class, "predicate can't be null", () -> multimapCache.remove((Predicate<? super Person>) null)); } public void testContainsKeyWithNull() { expectException(NullPointerException.class, "key can't be null", () -> multimapCache.containsKey(NULL_KEY)); } public void testContainsValueWithNull() { expectException(NullPointerException.class, "value can't be null", () -> multimapCache.containsValue(NULL_USER)); } public void testContainsEntryWithNull() { expectException(NullPointerException.class, "key can't be null", () -> multimapCache.containsEntry(NULL_KEY, OIHANA)); expectException(NullPointerException.class, "value can't be null", () -> multimapCache.containsEntry(NAMES_KEY, NULL_USER)); } }
16,803
38.446009
139
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/DistributedMultimapListCacheTest.java
package org.infinispan.multimap.impl; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.distribution.BaseDistFunctionalTest; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.multimap.api.embedded.EmbeddedMultimapCacheManagerFactory; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.remoting.transport.Address; import org.infinispan.test.data.Person; import org.testng.annotations.Test; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.multimap.impl.MultimapTestUtils.ELAIA; import static org.infinispan.multimap.impl.MultimapTestUtils.NAMES_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.OIHANA; import static org.infinispan.multimap.impl.MultimapTestUtils.RAMON; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; @Test(groups = "functional", testName = "distribution.DistributedMultimapListCacheTest") public class DistributedMultimapListCacheTest extends BaseDistFunctionalTest<String, Collection<Person>> { protected Map<Address, EmbeddedMultimapListCache<String, Person>> listCluster = new HashMap<>(); protected boolean fromOwner; public DistributedMultimapListCacheTest fromOwner(boolean fromOwner) { this.fromOwner = fromOwner; return this; } @Override protected void createCacheManagers() throws Throwable { super.createCacheManagers(); for (EmbeddedCacheManager cacheManager : cacheManagers) { EmbeddedMultimapCacheManager multimapCacheManager = (EmbeddedMultimapCacheManager) EmbeddedMultimapCacheManagerFactory.from(cacheManager); listCluster.put(cacheManager.getAddress(), multimapCacheManager.getMultimapList(cacheName)); } } @Override protected SerializationContextInitializer getSerializationContext() { return MultimapSCI.INSTANCE; } @Override protected String[] parameterNames() { return concat(super.parameterNames(), "fromOwner"); } @Override protected Object[] parameterValues() { return concat(super.parameterValues(), fromOwner ? Boolean.TRUE : Boolean.FALSE); } @Override public Object[] factory() { return new Object[]{ new DistributedMultimapListCacheTest().fromOwner(false).cacheMode(CacheMode.DIST_SYNC).transactional(false), new DistributedMultimapListCacheTest().fromOwner(true).cacheMode(CacheMode.DIST_SYNC).transactional(false), }; } @Override protected void initAndTest() { for (EmbeddedMultimapListCache list : listCluster.values()) { assertThat(await(list.size(NAMES_KEY))).isEqualTo(0L); } } protected EmbeddedMultimapListCache<String, Person> getMultimapCacheMember() { return listCluster. values().stream().findFirst().orElseThrow(() -> new IllegalStateException("Cluster is empty")); } public void testOfferFirstAndLast() { initAndTest(); EmbeddedMultimapListCache<String, Person> list = getMultimapCacheMember(); await(list.offerFirst(NAMES_KEY, OIHANA)); assertValuesAndOwnership(NAMES_KEY, OIHANA); await(list.offerLast(NAMES_KEY, ELAIA)); assertValuesAndOwnership(NAMES_KEY, ELAIA); } public void testPollFirstAndLast() { initAndTest(); EmbeddedMultimapListCache<String, Person> list = getMultimapCacheMember(); await( list.offerLast(NAMES_KEY, OIHANA) .thenCompose(r1 -> list.offerLast(NAMES_KEY, ELAIA)) .thenCompose(r1 -> list.offerLast(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.offerLast(NAMES_KEY, ELAIA)) .thenCompose(r1 -> list.size(NAMES_KEY)) .thenAccept(size -> assertThat(size).isEqualTo(4)) ); await( list.pollLast(NAMES_KEY, 2) .thenAccept(r1 -> assertThat(r1).containsExactly(ELAIA, OIHANA)) ); await( list.pollFirst(NAMES_KEY, 1) .thenAccept(r1 -> assertThat(r1).containsExactly(OIHANA)) ); await( list.size(NAMES_KEY) .thenAccept(r1 -> assertThat(r1).isEqualTo(1)) ); } public void testSize() { initAndTest(); EmbeddedMultimapListCache<String, Person> list = getMultimapCacheMember(); await( list.offerFirst(NAMES_KEY, OIHANA) .thenCompose(r1 -> list.offerFirst(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.offerFirst(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.offerFirst(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.size(NAMES_KEY)) .thenAccept(size -> assertThat(size).isEqualTo(4)) ); } public void testIndex() { initAndTest(); EmbeddedMultimapListCache<String, Person> list = getMultimapCacheMember(); await( list.offerLast(NAMES_KEY, OIHANA) .thenCompose(r1 -> list.offerLast(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.offerLast(NAMES_KEY, ELAIA)) .thenCompose(r1 -> list.offerLast(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.index(NAMES_KEY, 2)) .thenAccept(v -> assertThat(v).isEqualTo(ELAIA)) ); } public void testSubList() { initAndTest(); EmbeddedMultimapListCache<String, Person> list = getMultimapCacheMember(); await( list.offerLast(NAMES_KEY, OIHANA) .thenCompose(r1 -> list.offerLast(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.offerLast(NAMES_KEY, ELAIA)) .thenCompose(r1 -> list.offerLast(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.subList(NAMES_KEY, 1, 3)) .thenAccept(c -> assertThat(c).containsExactly(OIHANA, ELAIA, OIHANA)) ); } public void testSet() { initAndTest(); EmbeddedMultimapListCache<String, Person> list = getMultimapCacheMember(); await( list.offerLast(NAMES_KEY, OIHANA) .thenCompose(r1 -> list.offerLast(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.offerLast(NAMES_KEY, ELAIA)) .thenCompose(r1 -> list.offerLast(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.index(NAMES_KEY, 2)) .thenAccept(v -> assertThat(v).isEqualTo(ELAIA)) ); await( list.set(NAMES_KEY, 2, OIHANA) .thenCompose(r1 -> list.index(NAMES_KEY, 2)) .thenAccept(v -> assertThat(v).isEqualTo(OIHANA)) ); } public void testIndexOf() { initAndTest(); EmbeddedMultimapListCache<String, Person> list = getMultimapCacheMember(); await( list.offerLast(NAMES_KEY, OIHANA) .thenCompose(r1 -> list.offerLast(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.offerLast(NAMES_KEY, ELAIA)) .thenCompose(r1 -> list.offerLast(NAMES_KEY, OIHANA)) .thenCompose(r1 -> list.indexOf(NAMES_KEY, OIHANA, 0L, null, null)) .thenAccept(v -> assertThat(v).containsExactly(0L, 1L, 3L)) ); } public void testInsert() { initAndTest(); EmbeddedMultimapListCache<String, Person> list = getMultimapCacheMember(); await( list.offerLast(NAMES_KEY, OIHANA) .thenCompose(r1 -> list.insert(NAMES_KEY, true, OIHANA, ELAIA)) .thenAccept(v -> assertThat(v).isEqualTo(2)) ); } public void testRemove() { initAndTest(); EmbeddedMultimapListCache<String, Person> list = getMultimapCacheMember(); await( list.offerLast(NAMES_KEY, OIHANA) .thenCompose(r1 -> list.remove(NAMES_KEY, 1, OIHANA)) .thenAccept(v -> assertThat(v).isEqualTo(1)) ); } public void testTrim() { initAndTest(); EmbeddedMultimapListCache<String, Person> list = getMultimapCacheMember(); await( list.offerLast(NAMES_KEY, OIHANA) .thenCompose(r -> list.offerLast(NAMES_KEY, ELAIA)) .thenCompose(r -> list.offerLast(NAMES_KEY, RAMON)) .thenCompose(r -> list.trim(NAMES_KEY, 1, 2)) .thenCompose(r -> list.subList(NAMES_KEY, 0, -1)) .thenAccept(v -> assertThat(v).containsExactly(ELAIA, RAMON)) ); } public void testRotate() { initAndTest(); EmbeddedMultimapListCache<String, Person> list = getMultimapCacheMember(); await( list.offerLast(NAMES_KEY, OIHANA) .thenCompose(r1 -> list.offerLast(NAMES_KEY, ELAIA)) .thenCompose(r1 -> list.offerLast(NAMES_KEY, RAMON)) ); await( list.rotate(NAMES_KEY, false) .thenAccept(v -> assertThat(v).isEqualTo(RAMON)) ); await( list.subList(NAMES_KEY, 0, -1) .thenAccept(v -> assertThat(v).containsExactly(RAMON, OIHANA, ELAIA)) ); } protected void assertValuesAndOwnership(String key, Person value) { assertOwnershipAndNonOwnership(key, l1CacheEnabled); assertOnAllCaches(key, value); } protected void assertOnAllCaches(Object key, Person value) { for (Map.Entry<Address, EmbeddedMultimapListCache<String, Person>> entry : listCluster.entrySet()) { await(entry.getValue().get((String) key).thenAccept(v -> { assertNotNull(format("values on the key %s must be not null", key), v); assertTrue(format("values on the key '%s' must contain '%s' on node '%s'", key, value, entry.getKey()), v.contains(value)); }) ); } } }
10,066
35.875458
147
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/MultimapStoreBucketTest.java
package org.infinispan.multimap.impl; import static org.testng.AssertJUnit.assertTrue; import java.util.concurrent.TimeUnit; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.marshall.core.impl.DelegatingUserMarshaller; import org.infinispan.marshall.persistence.impl.PersistenceMarshallerImpl; import org.infinispan.multimap.api.embedded.EmbeddedMultimapCacheManagerFactory; import org.infinispan.multimap.api.embedded.MultimapCache; import org.infinispan.multimap.api.embedded.MultimapCacheManager; import org.infinispan.persistence.dummy.DummyInMemoryStoreConfigurationBuilder; import org.infinispan.test.AbstractInfinispanTest; import org.infinispan.test.TestingUtil; import org.infinispan.test.data.Person; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "multimap.MultimapStoreBucketTest") public class MultimapStoreBucketTest extends AbstractInfinispanTest { public void testMultimapWithJavaSerializationMarshaller() throws Exception { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder().nonClusteredDefault(); globalBuilder.defaultCacheName("test"); globalBuilder.serialization().marshaller(new JavaSerializationMarshaller()).allowList().addClass(SuperPerson.class.getName()); ConfigurationBuilder config = new ConfigurationBuilder(); config.persistence().addStore(DummyInMemoryStoreConfigurationBuilder.class); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(globalBuilder, config); MultimapCacheManager<String, Person> multimapCacheManager = EmbeddedMultimapCacheManagerFactory.from(cm); MultimapCache<String, Person> multimapCache = multimapCacheManager.get("test"); multimapCache.put("k1", new SuperPerson()); PersistenceMarshallerImpl pm = TestingUtil.extractPersistenceMarshaller(cm); DelegatingUserMarshaller userMarshaller = (DelegatingUserMarshaller) pm.getUserMarshaller(); assertTrue(userMarshaller.getDelegate() instanceof JavaSerializationMarshaller); assertTrue(pm.getSerializationContext().canMarshall(Bucket.class)); assertTrue(multimapCache.containsKey("k1").get(1, TimeUnit.SECONDS)); } }
2,468
53.866667
132
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/SuperPerson.java
package org.infinispan.multimap.impl; import static java.util.Objects.hash; import org.infinispan.test.data.Person; public class SuperPerson extends Person { SuperPerson() {} SuperPerson(String name) { super(name); } @Override public boolean equals(Object o) { return super.equals(o) && o instanceof SuperPerson && ((SuperPerson) o).isSuper(); } public boolean isSuper() { return true; } @Override public int hashCode() { return hash(super.hashCode(), isSuper()); } @Override public String toString() { return "SuperPerson{" + "name='" + getName() + '\'' + ", isSuper=" + isSuper() + '}'; } }
676
17.805556
91
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/StoreTypeMultimapCacheTest.java
package org.infinispan.multimap.impl; import java.util.HashMap; import java.util.Map; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.cache.StorageType; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.multimap.api.embedded.EmbeddedMultimapCacheManagerFactory; import org.infinispan.multimap.api.embedded.MultimapCache; import org.infinispan.multimap.api.embedded.MultimapCacheManager; import org.infinispan.remoting.transport.Address; import org.testng.annotations.Test; @Test(groups = "functional", testName = "distribution.StoreTypeMultimapCacheTest") public class StoreTypeMultimapCacheTest extends DistributedMultimapCacheTest { protected Map<Address, MultimapCache<String, String>> multimapCacheCluster = new HashMap<>(); public StoreTypeMultimapCacheTest() { super(); l1CacheEnabled = false; cacheMode = CacheMode.REPL_SYNC; transactional = false; fromOwner = true; } @Override public Object[] factory() { return new Object[]{ new StoreTypeMultimapCacheTest().storageType(StorageType.OFF_HEAP), new StoreTypeMultimapCacheTest().storageType(StorageType.OBJECT), new StoreTypeMultimapCacheTest().storageType(StorageType.BINARY), }; } @Override protected void createCacheManagers() throws Throwable { super.createCacheManagers(); for (EmbeddedCacheManager cacheManager : cacheManagers) { MultimapCacheManager multimapCacheManager = EmbeddedMultimapCacheManagerFactory.from(cacheManager); multimapCacheCluster.put(cacheManager.getAddress(), multimapCacheManager.get(cacheName)); } } @Override protected ConfigurationBuilder buildConfiguration() { ConfigurationBuilder cacheCfg = super.buildConfiguration(); cacheCfg.memory().storageType(storageType); return cacheCfg; } }
1,981
35.703704
108
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/EmbeddedMultimapCacheWithDuplicatesTest.java
package org.infinispan.multimap.impl; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.multimap.api.embedded.EmbeddedMultimapCacheManagerFactory; import org.infinispan.multimap.api.embedded.MultimapCache; import org.infinispan.multimap.api.embedded.MultimapCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.data.Person; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.multimap.impl.MultimapTestUtils.NAMES_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.OIHANA; import static org.infinispan.multimap.impl.MultimapTestUtils.RAMON; import static org.infinispan.multimap.impl.MultimapTestUtils.JULIEN; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @Test(groups = "functional", testName = "multimap.EmbeddedMultimapCacheWithDuplicatesTest") public class EmbeddedMultimapCacheWithDuplicatesTest extends SingleCacheManagerTest { private static final String TEST_CACHE_NAME = EmbeddedMultimapCacheWithDuplicatesTest.class.getSimpleName(); protected MultimapCache<String, Person> multimapCache; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { // start a single cache instance EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(MultimapSCI.INSTANCE); cm.defineConfiguration(TEST_CACHE_NAME, new ConfigurationBuilder().build()); MultimapCacheManager multimapCacheManager = EmbeddedMultimapCacheManagerFactory.from(cm); multimapCache = multimapCacheManager.get(TEST_CACHE_NAME, true); cm.getClassAllowList().addClasses(SuperPerson.class); return cm; } public void testSupportsDuplicates() { assertTrue(multimapCache.supportsDuplicates()); } public void testPutDuplicates() { await(multimapCache.put(NAMES_KEY, JULIEN) .thenCompose(r1 -> multimapCache.put(NAMES_KEY, RAMON).thenCompose(r2 -> multimapCache.get(NAMES_KEY).thenAccept(v -> { assertTrue(v.contains(JULIEN)); assertEquals(1, v.stream().filter(n -> n.equals(JULIEN)).count()); assertTrue(v.contains(RAMON)); assertEquals(1, v.stream().filter(n -> n.equals(RAMON)).count()); }).thenCompose(r3 -> multimapCache.size()).thenAccept(v -> { assertEquals(2, v.intValue()); }).thenCompose(r4 -> multimapCache.put(NAMES_KEY, JULIEN).thenCompose(r5 -> multimapCache.get(NAMES_KEY)).thenAccept(v -> { assertTrue(v.contains(JULIEN)); assertEquals(2, v.stream().filter(n -> n.equals(JULIEN)).count()); assertTrue(v.contains(RAMON)); assertEquals(1, v.stream().filter(n -> n.equals(RAMON)).count()); }).thenCompose(r3 -> multimapCache.size()).thenAccept(v -> { assertEquals(3, v.intValue()); }).thenCompose(r5 -> multimapCache.put(NAMES_KEY, JULIEN).thenCompose(r6 -> multimapCache.get(NAMES_KEY)).thenAccept(v -> { assertTrue(v.contains(JULIEN)); assertEquals(3, v.stream().filter(n -> n.equals(JULIEN)).count()); assertTrue(v.contains(RAMON)); assertEquals(1, v.stream().filter(n -> n.equals(RAMON)).count()); }).thenCompose(r7 -> multimapCache.size()).thenAccept(v -> assertEquals(4, v.intValue())) ))))); } public void testRemoveKeyValue() { await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r1 -> multimapCache.size()) .thenAccept(s -> assertEquals(1, s.intValue())) ); await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r1 -> multimapCache.size()) .thenAccept(s -> assertEquals(2, s.intValue())) ); await( multimapCache.put(NAMES_KEY, OIHANA) .thenCompose(r1 -> multimapCache.size()) .thenAccept(s -> assertEquals(3, s.intValue())) ); await( multimapCache.remove(NAMES_KEY, OIHANA) .thenCompose(r1 -> multimapCache.size()) .thenAccept(s -> assertEquals(0, s.intValue())) ); } }
4,694
48.946809
139
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/MultimapSCI.java
package org.infinispan.multimap.impl; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; import org.infinispan.test.TestDataSCI; import org.infinispan.test.data.Person; @AutoProtoSchemaBuilder( dependsOn = TestDataSCI.class, includeClasses = { Person.class, SuperPerson.class }, schemaFileName = "test.multimap.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.test.multimap", service = false ) interface MultimapSCI extends SerializationContextInitializer { MultimapSCI INSTANCE = new MultimapSCIImpl(); }
694
30.590909
69
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/EmbeddedMultimapListCacheTest.java
package org.infinispan.multimap.impl; import org.infinispan.commons.CacheException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.data.Person; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.multimap.impl.EmbeddedMultimapListCache.ERR_ELEMENT_CAN_T_BE_NULL; import static org.infinispan.multimap.impl.EmbeddedMultimapListCache.ERR_KEY_CAN_T_BE_NULL; import static org.infinispan.multimap.impl.EmbeddedMultimapListCache.ERR_PIVOT_CAN_T_BE_NULL; import static org.infinispan.multimap.impl.EmbeddedMultimapListCache.ERR_VALUE_CAN_T_BE_NULL; import static org.infinispan.multimap.impl.MultimapTestUtils.ELAIA; import static org.infinispan.multimap.impl.MultimapTestUtils.FELIX; import static org.infinispan.multimap.impl.MultimapTestUtils.JULIEN; import static org.infinispan.multimap.impl.MultimapTestUtils.KOLDO; import static org.infinispan.multimap.impl.MultimapTestUtils.NAMES_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.OIHANA; import static org.infinispan.multimap.impl.MultimapTestUtils.PEPE; import static org.infinispan.multimap.impl.MultimapTestUtils.RAMON; /** * Single Multimap Cache Test with Linked List * * @since 15.0 */ @Test(groups = "functional", testName = "multimap.EmbeddedMultimapListCacheTest") public class EmbeddedMultimapListCacheTest extends SingleCacheManagerTest { EmbeddedMultimapListCache<String, Person> listCache; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { // start a single cache instance EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(MultimapSCI.INSTANCE); ConfigurationBuilder builder = new ConfigurationBuilder(); cm.createCache("test", builder.build()); cm.getClassAllowList().addClasses(Person.class); listCache = new EmbeddedMultimapListCache<>(cm.getCache("test")); return cm; } public void testOfferLast() { await( listCache.offerLast(NAMES_KEY, JULIEN) .thenCompose(r1 -> listCache.offerLast(NAMES_KEY, OIHANA)) .thenCompose(r2 -> listCache.offerLast(NAMES_KEY, ELAIA)) .thenCompose(r3 -> listCache.get(NAMES_KEY)) .thenAccept(v -> { assertThat(v).containsExactly(JULIEN, OIHANA, ELAIA); } ) ); } public void testOfferFirst() { await( listCache.offerFirst(NAMES_KEY, JULIEN) .thenCompose(r1 -> listCache.offerFirst(NAMES_KEY, OIHANA)) .thenCompose(r2 -> listCache.offerFirst(NAMES_KEY, ELAIA)) .thenCompose(r3 -> listCache.get(NAMES_KEY)) .thenAccept(v -> assertThat(v).containsExactly(ELAIA, OIHANA, JULIEN) ) ); } public void testOfferWithDuplicates() { await( listCache.offerLast(NAMES_KEY, OIHANA) .thenCompose(r1 -> listCache.offerFirst(NAMES_KEY, OIHANA)) .thenCompose(r2 -> listCache.offerLast(NAMES_KEY, ELAIA)) .thenCompose(r2 -> listCache.offerFirst(NAMES_KEY, ELAIA)) .thenCompose(r2 -> listCache.offerLast(NAMES_KEY, OIHANA)) .thenCompose(r3 -> listCache.get(NAMES_KEY)) .thenAccept(v -> assertThat(v).containsExactly(ELAIA, OIHANA, OIHANA, ELAIA, OIHANA) ) ); } public void testOfferWithNullArguments() { assertThatThrownBy(() -> await(listCache.offerFirst(null, OIHANA)) ).isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); assertThatThrownBy(() -> await(listCache.offerLast(null, OIHANA)) ).isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); assertThatThrownBy(() -> await(listCache.offerFirst(NAMES_KEY, null)) ).isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_VALUE_CAN_T_BE_NULL); assertThatThrownBy(() -> { await(listCache.offerLast(NAMES_KEY, null)); }).isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_VALUE_CAN_T_BE_NULL); } public void testSize() { await( listCache.size(NAMES_KEY) .thenAccept(size -> assertThat(size).isZero()) ); await( listCache.offerFirst(NAMES_KEY, OIHANA) .thenCompose(r1 -> listCache.size(NAMES_KEY)) .thenAccept(size -> assertThat(size).isEqualTo(1)) ); await( listCache.size("not_exists") .thenAccept(size -> assertThat(size).isZero()) ); assertThatThrownBy(() -> { await(listCache.size(null)); }).isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); } public void testIndex() { await( listCache.index(NAMES_KEY, 0) .thenAccept(opt -> assertThat(opt).isNull()) ); await( listCache.index("not_exists", 4) .thenAccept(opt -> assertThat(opt).isNull()) ); await( listCache.offerLast(NAMES_KEY, KOLDO) .thenCompose(r3 -> listCache.index(NAMES_KEY, 0)) .thenCompose(v -> { assertThat(v).isEqualTo(KOLDO); return listCache.index(NAMES_KEY, -1); }) .thenCompose(v -> { assertThat(v).isEqualTo(KOLDO); return listCache.index(NAMES_KEY, 1); }) .thenCompose(v -> { assertThat(v).isNull(); return listCache.index(NAMES_KEY, -2); }) .thenAccept(opt -> assertThat(opt).isNull()) ); await( listCache.offerLast(NAMES_KEY, OIHANA) .thenCompose(r2 -> listCache.offerLast(NAMES_KEY, ELAIA)) .thenCompose(r2 -> listCache.offerLast(NAMES_KEY, RAMON)) .thenCompose(r3 -> listCache.index(NAMES_KEY, 0)) .thenCompose(v -> { assertThat(v).isEqualTo(KOLDO); return listCache.index(NAMES_KEY, -1); }) .thenCompose(v -> { assertThat(v).isEqualTo(RAMON); return listCache.index(NAMES_KEY, 3); }) .thenCompose(v -> { assertThat(v).isEqualTo(RAMON); return listCache.index(NAMES_KEY, -2); }) .thenCompose(v -> { assertThat(v).isEqualTo(ELAIA); return listCache.index(NAMES_KEY, 1); }) .thenCompose(v -> { assertThat(v).isEqualTo(OIHANA); return listCache.index(NAMES_KEY, 10); }) .thenAccept(opt -> assertThat(opt).isNull()) ); assertThatThrownBy(() -> { await(listCache.index(null, 10)); }).isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); } public void testPollFirst() { await( listCache.pollFirst(NAMES_KEY, 0) .thenAccept(r1 -> assertThat(r1).isNull()) ); await(listCache.offerFirst(NAMES_KEY, OIHANA)); await( listCache.pollFirst(NAMES_KEY, 0) .thenAccept(r1 -> assertThat(r1).isEmpty()) ); await( listCache.pollFirst(NAMES_KEY, 1) .thenAccept(r1 -> assertThat(r1).containsExactly(OIHANA)) ); await( listCache.pollFirst(NAMES_KEY, 1) .thenAccept(r1 -> assertThat(r1).isNull()) ); // [OIHANA, ELAIA, KOLDO] await(listCache.offerLast(NAMES_KEY, OIHANA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await( listCache.pollFirst(NAMES_KEY, 2) .thenAccept(r1 -> assertThat(r1).containsExactly(OIHANA, ELAIA)) ); await( listCache.pollLast(NAMES_KEY, 1) .thenAccept(r1 -> assertThat(r1).containsExactly(KOLDO)) ); await( listCache.pollFirst(NAMES_KEY, 1) .thenAccept(r1 -> assertThat(r1).isNull()) ); // [OIHANA, ELAIA, KOLDO] await(listCache.offerLast(NAMES_KEY, OIHANA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await( listCache.pollFirst(NAMES_KEY, 4) .thenAccept(r1 -> assertThat(r1).containsExactly(OIHANA, ELAIA, KOLDO)) ); await( listCache.pollLast(NAMES_KEY, 1) .thenAccept(r1 -> assertThat(r1).isNull()) ); } public void testPollLast() { await( listCache.pollLast(NAMES_KEY, 0) .thenAccept(r1 -> assertThat(r1).isNull()) ); await(listCache.offerFirst(NAMES_KEY, OIHANA)); await( listCache.pollLast(NAMES_KEY, 0) .thenAccept(r1 -> assertThat(r1).isEmpty()) ); await( listCache.pollLast(NAMES_KEY, 1) .thenAccept(r1 -> assertThat(r1).containsExactly(OIHANA)) ); await( listCache.pollLast(NAMES_KEY, 1) .thenAccept(r1 -> assertThat(r1).isNull()) ); // [OIHANA, ELAIA, KOLDO] await(listCache.offerLast(NAMES_KEY, OIHANA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await( listCache.pollLast(NAMES_KEY, 2) .thenAccept(r1 -> assertThat(r1).containsExactly(KOLDO, ELAIA)) ); await( listCache.pollLast(NAMES_KEY, 1) .thenAccept(r1 -> assertThat(r1).containsExactly(OIHANA)) ); await( listCache.pollLast(NAMES_KEY, 1) .thenAccept(r1 -> assertThat(r1).isNull()) ); // [OIHANA, ELAIA, KOLDO] await(listCache.offerLast(NAMES_KEY, OIHANA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await( listCache.pollLast(NAMES_KEY, 4) .thenAccept(r1 -> assertThat(r1).containsExactly(KOLDO, ELAIA, OIHANA)) ); await( listCache.pollLast(NAMES_KEY, 1) .thenAccept(r1 -> assertThat(r1).isNull()) ); } public void testSet() { await(listCache.offerLast(NAMES_KEY, OIHANA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await(listCache.offerLast(NAMES_KEY, FELIX)); // head assertThat(await(listCache.index(NAMES_KEY, 0))).isEqualTo(OIHANA); assertThat(await(listCache.set(NAMES_KEY,0, RAMON))).isTrue(); assertThat(await(listCache.index(NAMES_KEY, 0))).isEqualTo(RAMON); // tail assertThat(await(listCache.index(NAMES_KEY, -1))).isEqualTo(FELIX); assertThat(await(listCache.set(NAMES_KEY, -1, JULIEN))).isTrue(); assertThat(await(listCache.index(NAMES_KEY, -1))).isEqualTo(JULIEN); // middle assertThat(await(listCache.index(NAMES_KEY, 1))).isEqualTo(ELAIA); assertThat(await(listCache.set(NAMES_KEY, 1, OIHANA))).isTrue(); assertThat(await(listCache.index(NAMES_KEY, 1))).isEqualTo(OIHANA); assertThat(await(listCache.index(NAMES_KEY, -2))).isEqualTo(KOLDO); assertThat(await(listCache.set(NAMES_KEY, -2, ELAIA))).isTrue(); assertThat(await(listCache.index(NAMES_KEY, -2))).isEqualTo(ELAIA); assertThat(await(listCache.index(NAMES_KEY, -3))).isEqualTo(OIHANA); assertThat(await(listCache.set(NAMES_KEY, 1, ELAIA))).isTrue(); assertThat(await(listCache.index(NAMES_KEY, 1))).isEqualTo(ELAIA); // not existing assertThat(await(listCache.set("not_existing", 0, JULIEN))).isFalse(); assertThatThrownBy(() -> { await(listCache.set(NAMES_KEY, 4, JULIEN)); }).cause().cause() .isInstanceOf(CacheException.class) .cause().isInstanceOf(IndexOutOfBoundsException.class) .hasMessageContaining("Index is out of range"); assertThatThrownBy(() -> { await(listCache.set(NAMES_KEY, -5, JULIEN)); }).cause().cause() .isInstanceOf(CacheException.class) .cause().isInstanceOf(IndexOutOfBoundsException.class) .hasMessageContaining("Index is out of range"); assertThatThrownBy(() -> { await(listCache.index(null, 10)); }).isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); } public void testSubList() { await(listCache.offerLast(NAMES_KEY, OIHANA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await(listCache.offerLast(NAMES_KEY, RAMON)); await(listCache.offerLast(NAMES_KEY, JULIEN)); assertThat(await(listCache.subList(NAMES_KEY, 0, 0))).containsExactly(OIHANA); assertThat(await(listCache.subList(NAMES_KEY, 4, 4))).containsExactly(JULIEN); assertThat(await(listCache.subList(NAMES_KEY, 5, 5))).isEmpty(); assertThat(await(listCache.subList(NAMES_KEY, -1, -1))).containsExactly(JULIEN); assertThat(await(listCache.subList(NAMES_KEY, -5, -5))).containsExactly(OIHANA); assertThat(await(listCache.subList(NAMES_KEY, -6, -6))).isEmpty(); assertThat(await(listCache.subList(NAMES_KEY, 0, 4))).containsExactly(OIHANA, ELAIA, KOLDO, RAMON, JULIEN); assertThat(await(listCache.subList(NAMES_KEY, 0, 5))).containsExactly(OIHANA, ELAIA, KOLDO, RAMON, JULIEN); assertThat(await(listCache.subList(NAMES_KEY, 0, 3))).containsExactly(OIHANA, ELAIA, KOLDO, RAMON); assertThat(await(listCache.subList(NAMES_KEY, 1, 2))).containsExactly(ELAIA, KOLDO); assertThat(await(listCache.subList(NAMES_KEY, 1, 0))).isEmpty(); assertThat(await(listCache.subList(NAMES_KEY, -1, 0))).isEmpty(); assertThat(await(listCache.subList(NAMES_KEY, -1, -2))).isEmpty(); assertThat(await(listCache.subList(NAMES_KEY, -5, -1))).containsExactly(OIHANA, ELAIA, KOLDO, RAMON, JULIEN); assertThat(await(listCache.subList(NAMES_KEY, -5, -2))).containsExactly(OIHANA, ELAIA, KOLDO, RAMON); assertThat(await(listCache.subList(NAMES_KEY, -4, -2))).containsExactly(ELAIA, KOLDO, RAMON); assertThat(await(listCache.subList(NAMES_KEY, 1, -1))).containsExactly(ELAIA, KOLDO, RAMON, JULIEN); assertThat(await(listCache.subList(NAMES_KEY, 1, -1))).containsExactly(ELAIA, KOLDO, RAMON, JULIEN); assertThat(await(listCache.subList(NAMES_KEY, -5, 1))).containsExactly(OIHANA, ELAIA); assertThat(await(listCache.subList(NAMES_KEY, -2, 4))).containsExactly(RAMON, JULIEN); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(OIHANA, ELAIA, KOLDO, RAMON, JULIEN); assertThat(await(listCache.subList(NAMES_KEY, 2, -2))).containsExactly(KOLDO, RAMON); assertThat(await(listCache.subList(NAMES_KEY, -1, 7))).containsExactly(JULIEN); assertThat(await(listCache.subList(NAMES_KEY, 2, -6))).isEmpty(); assertThatThrownBy(() -> { await(listCache.subList(null, 1, 10)); }).isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); assertThat(await(listCache.subList("not_existing", 1, 10))).isNull(); } public void testIndexOf() { await(listCache.offerLast(NAMES_KEY, OIHANA));//0 await(listCache.offerLast(NAMES_KEY, ELAIA));//1 await(listCache.offerLast(NAMES_KEY, KOLDO));//2 await(listCache.offerLast(NAMES_KEY, RAMON));//3 await(listCache.offerLast(NAMES_KEY, RAMON));//4 await(listCache.offerLast(NAMES_KEY, JULIEN));//5 await(listCache.offerLast(NAMES_KEY, ELAIA));//6 await(listCache.offerLast(NAMES_KEY, OIHANA));//7 await(listCache.offerLast(NAMES_KEY, OIHANA));//8 await(listCache.offerLast(NAMES_KEY, OIHANA));//9 // defaults assertThat(await(listCache.indexOf("non_existing", OIHANA, null, null, null))).isNull(); assertThat(await(listCache.indexOf(NAMES_KEY, PEPE, null, null, null))).isEmpty(); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, null, null, null))).containsExactly(0L); assertThat(await(listCache.indexOf(NAMES_KEY, KOLDO, null, null, null))).containsExactly(2L); // count parameter assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 1L, null, null))).containsExactly(0L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 2L, null, null))).containsExactly(0L, 7L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 0L, null, null))).containsExactly(0L, 7L, 8L, 9L); // rank parameter assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, null, 1L, null))).containsExactly(0L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, null, 2L, null))).containsExactly(7L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, null, -1L, null))).containsExactly(9L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, null, -2L, null))).containsExactly(8L); assertThat(await(listCache.indexOf(NAMES_KEY, KOLDO, null, 1L, null))).containsExactly(2L); assertThat(await(listCache.indexOf(NAMES_KEY, KOLDO, null, 2L, null))).isEmpty(); // maxLen parameter assertThat(await(listCache.indexOf(NAMES_KEY, KOLDO, null, null, 1L))).isEmpty(); assertThat(await(listCache.indexOf(NAMES_KEY, KOLDO, null, null, 3L))).containsExactly(2L); // count + rank assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 2L, 2L, null))).containsExactly(7L, 8L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 0L, 2L, null))).containsExactly(7L, 8L, 9L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 0L, -2L, null))).containsExactly(8L, 7L, 0L); // count + maxlen assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 0L, null, 3L))).containsExactly(0L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 0L, null, 8L))).containsExactly(0L, 7L); // count + maxlen + rank assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 0L, -1L, 3L))).containsExactly(9L, 8L, 7L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 1L, -1L, 3L))).containsExactly(9L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 2L, -2L, 3L))).containsExactly(8L, 7L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 3L, -3L, 3L))).containsExactly(7L); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 1L, -2L, 1L))).isEmpty(); assertThat(await(listCache.indexOf(NAMES_KEY, OIHANA, 1L, 2L, 1L))).isEmpty(); assertThatThrownBy(() -> { await(listCache.indexOf(null, null, null, null, null)); }).isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); assertThatThrownBy(() -> { await(listCache.indexOf("foo", null, null, null, null)); }).isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_ELEMENT_CAN_T_BE_NULL); assertThatThrownBy(() -> { await(listCache.indexOf(NAMES_KEY, ELAIA, -1L, null, null)); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("count can't be negative"); assertThatThrownBy(() -> { await(listCache.indexOf(NAMES_KEY, ELAIA, null, 0L, null)); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("rank can't be zero"); assertThatThrownBy(() -> { await(listCache.indexOf(NAMES_KEY, ELAIA, null, null, -1L)); }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("maxLen can't be negative"); } public void testInsertElement() { await(listCache.offerLast(NAMES_KEY, OIHANA));//0 await(listCache.offerLast(NAMES_KEY, ELAIA));//1 await(listCache.offerLast(NAMES_KEY, KOLDO));//2 await(listCache.offerLast(NAMES_KEY, OIHANA));//3 assertThat(await(listCache.insert("not_existing", false, OIHANA, ELAIA))).isEqualTo(0); assertThat(await(listCache.insert(NAMES_KEY, false, RAMON, ELAIA))).isEqualTo(-1); assertThat(await(listCache.insert(NAMES_KEY, false, OIHANA, RAMON))).isEqualTo(5); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(OIHANA, RAMON, ELAIA, KOLDO, OIHANA); assertThat(await(listCache.insert(NAMES_KEY, true, OIHANA, RAMON))).isEqualTo(6); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(RAMON, OIHANA, RAMON, ELAIA, KOLDO, OIHANA); assertThat(await(listCache.insert(NAMES_KEY, true, OIHANA, RAMON))).isEqualTo(7); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(RAMON, RAMON, OIHANA, RAMON, ELAIA, KOLDO, OIHANA); assertThatThrownBy(() -> await(listCache.insert(null, false, null, null))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); assertThatThrownBy(() -> await(listCache.insert(NAMES_KEY, false, null, null))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_PIVOT_CAN_T_BE_NULL); assertThatThrownBy(() -> await(listCache.insert(NAMES_KEY, false, OIHANA, null))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_ELEMENT_CAN_T_BE_NULL); } public void testRemoveElement() { await(listCache.offerLast(NAMES_KEY, OIHANA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await(listCache.offerLast(NAMES_KEY, OIHANA)); assertThat(await(listCache.remove("not_existing", 0, OIHANA))).isEqualTo(0); assertThat(await(listCache.remove(NAMES_KEY, 0, RAMON))).isEqualTo(0); assertThat(await(listCache.remove(NAMES_KEY, 0, ELAIA))).isEqualTo(3); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(OIHANA, KOLDO, KOLDO, OIHANA); assertThat(await(listCache.remove(NAMES_KEY, 3, KOLDO))).isEqualTo(2); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(OIHANA, OIHANA); assertThat(await(listCache.remove(NAMES_KEY, 1, OIHANA))).isEqualTo(1); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(OIHANA); assertThat(await(listCache.remove(NAMES_KEY, 1, OIHANA))).isEqualTo(1); assertThat(await(listCache.containsKey(NAMES_KEY))).isFalse(); assertThatThrownBy(() -> await(listCache.remove(null, 0, null))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); assertThatThrownBy(() -> await(listCache.remove(NAMES_KEY, 0, null))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_ELEMENT_CAN_T_BE_NULL); } public void testTrim() { await(listCache.offerLast(NAMES_KEY, OIHANA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await(listCache.offerLast(NAMES_KEY, RAMON)); await(listCache.offerLast(NAMES_KEY, JULIEN)); assertThat(await(listCache.trim("not_existing", 0, 0))).isFalse(); assertThat(await(listCache.trim(NAMES_KEY, 0, 0))).isTrue(); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(OIHANA); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await(listCache.offerLast(NAMES_KEY, RAMON)); await(listCache.offerLast(NAMES_KEY, JULIEN)); assertThat(await(listCache.trim(NAMES_KEY, -3, -3))).isTrue(); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(KOLDO); await(listCache.offerFirst(NAMES_KEY, ELAIA)); await(listCache.offerFirst(NAMES_KEY, OIHANA)); await(listCache.offerLast(NAMES_KEY, RAMON)); await(listCache.offerLast(NAMES_KEY, JULIEN)); assertThat(await(listCache.trim(NAMES_KEY, 0, 2))).isTrue(); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(OIHANA, ELAIA, KOLDO); await(listCache.offerLast(NAMES_KEY, RAMON)); await(listCache.offerLast(NAMES_KEY, JULIEN)); assertThat(await(listCache.trim(NAMES_KEY, -1, -3))).isTrue(); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).isNull(); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await(listCache.offerLast(NAMES_KEY, RAMON)); await(listCache.offerLast(NAMES_KEY, JULIEN)); assertThat(await(listCache.trim(NAMES_KEY, 3, 2))).isTrue(); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).isNull(); await(listCache.offerLast(NAMES_KEY, OIHANA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await(listCache.offerLast(NAMES_KEY, RAMON)); await(listCache.offerLast(NAMES_KEY, JULIEN)); assertThat(await(listCache.trim(NAMES_KEY, 1, -2))).isTrue(); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(ELAIA, KOLDO, RAMON); assertThatThrownBy(() -> await(listCache.subList(null, 1, 10))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); } public void testRotate() { await(listCache.offerLast(NAMES_KEY, OIHANA)); await(listCache.offerLast(NAMES_KEY, ELAIA)); await(listCache.offerLast(NAMES_KEY, KOLDO)); await(listCache.offerLast(NAMES_KEY, RAMON)); await(listCache.offerLast(NAMES_KEY, JULIEN)); assertThat(await(listCache.rotate("not_existing", true))).isNull(); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(OIHANA, ELAIA, KOLDO, RAMON, JULIEN); assertThat(await(listCache.rotate(NAMES_KEY, true))).isEqualTo(OIHANA); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(ELAIA, KOLDO, RAMON, JULIEN, OIHANA); assertThat(await(listCache.rotate(NAMES_KEY, false))).isEqualTo(OIHANA); assertThat(await(listCache.subList(NAMES_KEY, 0, -1))).containsExactly(OIHANA, ELAIA, KOLDO, RAMON, JULIEN); assertThatThrownBy(() -> await(listCache.rotate(null, true))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); } }
27,456
44.383471
128
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/DistributedMultimapPairCacheTest.java
package org.infinispan.multimap.impl; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.multimap.impl.MultimapTestUtils.FELIX; import static org.infinispan.multimap.impl.MultimapTestUtils.KOLDO; import static org.infinispan.multimap.impl.MultimapTestUtils.OIHANA; import static org.infinispan.multimap.impl.MultimapTestUtils.RAMON; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.function.Function; import java.util.stream.Collectors; import org.infinispan.distribution.BaseDistFunctionalTest; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.multimap.api.embedded.EmbeddedMultimapCacheManagerFactory; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.remoting.transport.Address; import org.infinispan.test.data.Person; import org.testng.annotations.Test; @Test(groups = "functional", testName = "distribution.DistributedMultimapPairCacheTest") public class DistributedMultimapPairCacheTest extends BaseDistFunctionalTest<String, Map<byte[], Person>> { protected Map<Address, EmbeddedMultimapPairCache<String, byte[], Person>> pairCacheCluster = new HashMap<>(); @Override protected void createCacheManagers() throws Throwable { super.createCacheManagers(); for (EmbeddedCacheManager cacheManager : cacheManagers) { EmbeddedMultimapCacheManager multimapCacheManager = (EmbeddedMultimapCacheManager) EmbeddedMultimapCacheManagerFactory.from(cacheManager); pairCacheCluster.put(cacheManager.getAddress(), multimapCacheManager.getMultimapPair(cacheName)); } } @Override protected SerializationContextInitializer getSerializationContext() { return MultimapSCI.INSTANCE; } private EmbeddedMultimapPairCache<String, byte[], Person> getMultimapMember() { return pairCacheCluster.values() .stream().findFirst().orElseThrow(() -> new IllegalStateException("No multimap cluster found!")); } public void testSetGetOperations() { EmbeddedMultimapPairCache<String, byte[], Person> multimap = getMultimapMember(); assertThat(await(multimap.set("person1", Map.entry(toBytes("oihana"), OIHANA)))) .isEqualTo(1); assertThat(await(multimap.set("person1", Map.entry(toBytes("koldo"), KOLDO), Map.entry(toBytes("felix"), RAMON)))) .isEqualTo(2); assertThat(await(multimap.set("person1", Map.entry(toBytes("felix"), FELIX)))).isZero(); assertFromAllCaches("person1", Map.of("oihana", OIHANA, "koldo", KOLDO, "felix", FELIX)); assertThat(await(multimap.get("person1", toBytes("oihana")))).isEqualTo(OIHANA); assertThat(await(multimap.get("person1", toBytes("unknown")))).isNull(); assertThat(await(multimap.get("unknown", toBytes("unknown")))).isNull(); } public void testSizeOperation() { EmbeddedMultimapPairCache<String, byte[], Person> multimap = getMultimapMember(); CompletionStage<Integer> cs = multimap.set("size-test", Map.entry(toBytes("oihana"), OIHANA), Map.entry(toBytes("ramon"), RAMON)) .thenCompose(ignore -> multimap.size("size-test")); assertThat(await(cs)).isEqualTo(2); } public void testKeySetOperation() { EmbeddedMultimapPairCache<String, byte[], Person> multimap = getMultimapMember(); CompletionStage<Set<String>> cs = multimap.set("keyset-test", Map.entry(toBytes("oihana"), OIHANA), Map.entry(toBytes("koldo"), KOLDO)) .thenCompose(ignore -> multimap.keySet("keyset-test")) .thenApply(s -> s.stream().map(String::new).collect(Collectors.toSet())); assertThat(await(cs)).contains("oihana", "koldo"); } public void testSetAndRemove() { EmbeddedMultimapPairCache<String, byte[], Person> multimap = getMultimapMember(); await(multimap.set("set-and-remove", Map.entry(toBytes("oihana"), OIHANA), Map.entry(toBytes("koldo"), KOLDO)) .thenCompose(ignore -> multimap.remove("set-and-remove", toBytes("oihana"))) .thenCompose(v -> { assertThat(v).isEqualTo(1); return multimap.remove("set-and-remove", toBytes("koldo"), toBytes("ramon")); }) .thenAccept(v -> assertThat(v).isEqualTo(1))); assertThatThrownBy(() -> await(multimap.remove("set-and-remove", null))) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> await(multimap.remove(null, new byte[] { 1 }))) .isInstanceOf(NullPointerException.class); } protected void assertFromAllCaches(String key, Map<String, Person> expected) { for (EmbeddedMultimapPairCache<String, byte[], Person> multimap : pairCacheCluster.values()) { assertThat(await(multimap.get(key) .thenApply(DistributedMultimapPairCacheTest::convertKeys))) .containsAllEntriesOf(expected); } } protected void assertFromAllCaches(Function<EmbeddedMultimapPairCache<String, byte[], Person>, CompletionStage<?>> f) { for (EmbeddedMultimapPairCache<String, byte[], Person> multimap : pairCacheCluster.values()) { await(f.apply(multimap)); } } private static byte[] toBytes(String s) { return s.getBytes(); } private static Map<String, Person> convertKeys(Map<byte[], Person> map) { return map.entrySet().stream() .map(e -> Map.entry(toString(e.getKey()), e.getValue())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } private static String toString(byte[] b) { return new String(b); } public void testValuesOperation() { EmbeddedMultimapPairCache<String, byte[], Person> multimap = getMultimapMember(); CompletionStage<Collection<Person>> cs = multimap.set("values-test", Map.entry(toBytes("oihana"), OIHANA), Map.entry(toBytes("koldo"), KOLDO)) .thenCompose(ignore -> multimap.values("values-test")); assertThat(await(cs)).contains(OIHANA, KOLDO); } public void testContainsProperty() { EmbeddedMultimapPairCache<String, byte[], Person> multimap = getMultimapMember(); await(multimap.set("contains-test", Map.entry(toBytes("oihana"), OIHANA)) .thenAccept(ignore -> assertFromAllCaches("contains-test", Map.of("oihana", OIHANA))) .thenCompose(ignore -> multimap.contains("contains-test", toBytes("oihana")) .thenCompose(b -> { assertThat(b).isTrue(); return multimap.contains("contains-test", toBytes("unknown")); }) .thenCompose(b -> { assertThat(b).isFalse(); return multimap.contains("unknown", toBytes("unknown")); }) .thenAccept(b -> assertThat(b).isFalse()))); } public void testCompute() { EmbeddedMultimapPairCache<String, byte[], Person> multimap = getMultimapMember(); byte[] oihana = toBytes("oihana"); await(multimap.set("compute-test", Map.entry(oihana, OIHANA)) .thenAccept(ignore -> assertFromAllCaches("compute-test", Map.of("oihana", OIHANA))) .thenCompose(ignore -> multimap.compute("compute-test", oihana, (k, v) -> { assertThat(k).isEqualTo(oihana); assertThat(v).isEqualTo(OIHANA); return FELIX; })) .thenAccept(ignore -> assertFromAllCaches("compute-test", Map.of("oihana", FELIX)))); } public void testSubSelect() { // Not existent key. assertFromAllCaches(m -> m.subSelect("something-not-existent", 10) .thenAccept(v -> assertThat(v).isNull())); assertFromAllCaches(multimap -> multimap.set("sub-select-test", Map.entry(toBytes("oihana"), OIHANA), Map.entry(toBytes("koldo"), KOLDO)) .thenCompose(ignore -> multimap.subSelect("sub-select-test", 1)) .thenAccept(m -> assertThat(convertKeys(m)) .hasSize(1) .containsAnyOf(Map.entry("oihana", OIHANA), Map.entry("koldo", KOLDO)))); } public void testGetMultiple() { assertFromAllCaches(multimap -> multimap.set("get-multiple-test", Map.entry(toBytes("oihana"), OIHANA), Map.entry(toBytes("koldo"), KOLDO)) .thenCompose(ignore -> multimap.get("get-multiple-test", toBytes("oihana"), toBytes("koldo"))) .thenAccept(m -> assertThat(convertKeys(m)) .hasSize(2) .containsEntry("oihana", OIHANA) .containsEntry("koldo", KOLDO))); } }
8,783
47
148
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/EmbeddedMultimapPairCacheTest.java
package org.infinispan.multimap.impl; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.infinispan.functional.FunctionalTestUtils.await; import java.util.Map; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; @Test(groups = "functional", testName = "multimap.impl.EmbeddedMultimapPairCacheTest") public class EmbeddedMultimapPairCacheTest extends SingleCacheManagerTest { EmbeddedMultimapPairCache<String, String, String> embeddedPairCache; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(MultimapSCI.INSTANCE); ConfigurationBuilder builder = new ConfigurationBuilder(); cm.createCache("test", builder.build()); embeddedPairCache = new EmbeddedMultimapPairCache<>(cm.getCache("test")); return cm; } public void testSetGetOperations() { assertThat(await(embeddedPairCache.set("person1", Map.entry("name", "Oihana")))) .isEqualTo(1); assertThat(await(embeddedPairCache.set("person1", Map.entry("age", "1"), Map.entry("birthday", "2023-05-26")))) .isEqualTo(2); assertThat(await(embeddedPairCache.set("person1", Map.entry("name", "Ramon")))) .isEqualTo(0); Map<String, String> person1 = await(embeddedPairCache.get("person1")); assertThat(person1) .containsEntry("name", "Ramon") .containsEntry("age", "1") .containsEntry("birthday", "2023-05-26") .hasSize(3); assertThat(await(embeddedPairCache.get("person1", "name"))).isEqualTo("Ramon"); assertThat(await(embeddedPairCache.get("person1", "unknown"))).isNull(); assertThat(await(embeddedPairCache.get("unknown", "unknown"))).isNull(); assertThatThrownBy(() -> await(embeddedPairCache.get(null, "property"))) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> await(embeddedPairCache.get("person1", (String) null))) .isInstanceOf(NullPointerException.class); } public void testSizeOperation() { assertThat(await(embeddedPairCache.set("size-test", Map.entry("name", "Oihana"), Map.entry("age", "1")))) .isEqualTo(2); assertThat(await(embeddedPairCache.size("size-test"))).isEqualTo(2); assertThat(await(embeddedPairCache.size("unknown"))).isEqualTo(0); assertThatThrownBy(() -> await(embeddedPairCache.size(null))) .isInstanceOf(NullPointerException.class); } public void testKeySetOperation() { assertThat(await(embeddedPairCache.set("keyset-test", Map.entry("name", "Oihana"), Map.entry("age", "1")))) .isEqualTo(2); assertThat(await(embeddedPairCache.keySet("keyset-test"))).contains("name", "age"); assertThat(await(embeddedPairCache.keySet("unknown-entry"))).isEmpty(); assertThatThrownBy(() -> await(embeddedPairCache.keySet(null))) .isInstanceOf(NullPointerException.class); } public void testValuesOperation() { assertThat(await(embeddedPairCache.set("values-test", Map.entry("name", "Oihana"), Map.entry("age", "1")))) .isEqualTo(2); assertThat(await(embeddedPairCache.values("values-test"))).contains("Oihana", "1"); assertThat(await(embeddedPairCache.values("unknown-entry"))).isEmpty(); assertThatThrownBy(() -> await(embeddedPairCache.values(null))) .isInstanceOf(NullPointerException.class); } public void testContainsProperty() { assertThat(await(embeddedPairCache.set("contains-test", Map.entry("name", "Oihana")))) .isEqualTo(1); assertThat(await(embeddedPairCache.contains("contains-test", "name"))) .isTrue(); assertThat(await(embeddedPairCache.contains("contains-test", "age"))) .isFalse(); assertThat(await(embeddedPairCache.contains("unknown-entry", "name"))) .isFalse(); assertThatThrownBy(() -> await(embeddedPairCache.contains(null, "name"))) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> await(embeddedPairCache.contains("contains-test", null))) .isInstanceOf(NullPointerException.class); } public void testSetAndRemove() { // Does not exist assertThat(await(embeddedPairCache.remove("some-unknown-key", "name"))).isZero(); assertThat(await(embeddedPairCache.set("set-and-remove", Map.entry("k1", "v1"), Map.entry("k2", "v2"), Map.entry("k3", "v3")))) .isEqualTo(3); assertThat(await(embeddedPairCache.remove("set-and-remove", "k1"))).isEqualTo(1); assertThat(await(embeddedPairCache.remove("set-and-remove", "k2", "k3", "k4"))).isEqualTo(2); assertThat(await(embeddedPairCache.get("set-and-remove"))).isEmpty(); assertThatThrownBy(() -> await(embeddedPairCache.remove("set-and-remove", null))) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> await(embeddedPairCache.remove(null, "k1"))) .isInstanceOf(NullPointerException.class); } public void testCompute() { assertThat(await(embeddedPairCache.compute("compute-test", "name", (k, v) -> { assertThat(k).isEqualTo("name"); assertThat(v).isNull(); return "Oihana"; }))).isEqualTo("Oihana"); assertThat(await(embeddedPairCache.compute("compute-test", "name", (k, v) -> { assertThat(k).isEqualTo("name"); assertThat(v).isEqualTo("Oihana"); return "Ramon"; }))).isEqualTo("Ramon"); assertThat(await(embeddedPairCache.get("compute-test", "name"))).isEqualTo("Ramon"); } public void testSubSelect() { assertThat(await(embeddedPairCache.subSelect("unknown-subselect", 10))).isNull(); Map<String, String> map = Map.of("name", "Oihana", "age", "1", "birthday", "2023-05-26"); assertThat(await(embeddedPairCache.set("subselect-test", map.entrySet().toArray(new Map.Entry[0])))) .isEqualTo(3); assertThat(await(embeddedPairCache.subSelect("subselect-test", 2))) .hasSize(2) .satisfies(m -> assertThat(map).containsAllEntriesOf(m)); assertThat(await(embeddedPairCache.subSelect("subselect-test", 30))) .containsAllEntriesOf(map) .hasSize(map.size()); assertThatThrownBy(() -> await(embeddedPairCache.subSelect(null, 10))) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> await(embeddedPairCache.subSelect("subselect-test", -1))) .isInstanceOf(IllegalArgumentException.class); } public void testGetMultipleProperties() { // ENTRY not exist, so an empty map. assertThat(await(embeddedPairCache.get("unknown-multiple", "k1", "k2"))).isEmpty(); Map<String, String> map = Map.of("name", "Oihana", "age", "1", "birthday", "2023-05-26"); assertThat(await(embeddedPairCache.set("multiple-test", map.entrySet().toArray(new Map.Entry[0])))) .isEqualTo(3); assertThat(await(embeddedPairCache.get("multiple-test", "name", "age"))) .containsEntry("name", "Oihana") .containsEntry("age", "1") .hasSize(2); // An existing entry but with an unknown property. assertThat(await(embeddedPairCache.get("multiple-test", "name", "something-not-there", "age"))) .containsEntry("name", "Oihana") .containsEntry("age", "1") .containsEntry("something-not-there", null) .hasSize(3); assertThatThrownBy(() -> await(embeddedPairCache.get(null, "k1", "k2"))) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> await(embeddedPairCache.get(null, "k1", null))) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> await(embeddedPairCache.get("multiple-test", (String[]) null))) .isInstanceOf(NullPointerException.class); assertThatThrownBy(() -> await(embeddedPairCache.get("multiple-test", new String[0]))) .isInstanceOf(IllegalArgumentException.class); } }
8,411
43.273684
133
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/MultimapTestUtils.java
package org.infinispan.multimap.impl; import jakarta.transaction.TransactionManager; import org.infinispan.multimap.api.embedded.MultimapCache; import org.infinispan.remoting.transport.Address; import org.infinispan.test.data.Person; import java.util.Map; import static java.lang.String.format; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; public class MultimapTestUtils { public static final String NAMES_KEY = "names"; public static final String EMPTY_KEY = ""; public static final String NULL_KEY = null; public static final Person JULIEN = new Person("Julien"); public static final Person OIHANA = new Person("Oihana"); public static final Person RAMON = new Person("Ramon"); public static final Person KOLDO = new Person("Koldo"); public static final Person ELAIA = new Person("Elaia"); public static final Person FELIX = new Person("Felix"); public static final Person IGOR = new Person("Igor"); public static final Person IZARO = new Person("Izaro"); public static final SuperPerson PEPE = new SuperPerson("Pepe"); public static final SuperPerson NULL_USER = null; public static TransactionManager getTransactionManager(MultimapCache multimapCache) { EmbeddedMultimapCache embeddedMultimapCache = (EmbeddedMultimapCache) multimapCache; return embeddedMultimapCache == null ? null : embeddedMultimapCache.getCache().getAdvancedCache().getTransactionManager(); } public static void putValuesOnMultimapCache(MultimapCache<String, Person> multimapCache, String key, Person... values) { for (int i = 0; i < values.length; i++) { await(multimapCache.put(key, values[i])); } } public static void putValuesOnMultimapCache(Map<Address, MultimapCache<String, Person>> cluster, String key, Person... values) { for (MultimapCache mc : cluster.values()) { putValuesOnMultimapCache(mc, key, values); } } public static void assertMultimapCacheSize(MultimapCache<String, Person> multimapCache, int expectedSize) { assertEquals(expectedSize, await(multimapCache.size()).intValue()); } public static void assertMultimapCacheSize(Map<Address, MultimapCache<String, Person>> cluster, int expectedSize) { for (MultimapCache mc : cluster.values()) { assertMultimapCacheSize(mc, expectedSize); } } public static void assertContaisKeyValue(MultimapCache<String, Person> multimapCache, String key, Person value) { Address address = ((EmbeddedMultimapCache) multimapCache).getCache().getCacheManager().getAddress(); await(multimapCache.get(key).thenAccept(v -> { assertTrue(format("get method call : multimap '%s' must contain key '%s' value '%s' pair", address, key, value), v.contains(value)); })); await(multimapCache.containsEntry(key, value).thenAccept(v -> { assertTrue(format("containsEntry method call : multimap '%s' must contain key '%s' value '%s' pair", address, key, value), v); })); } }
3,119
44.882353
141
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/DistributedMultimapSortedSetCacheTest.java
package org.infinispan.multimap.impl; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.distribution.BaseDistFunctionalTest; import org.infinispan.functional.FunctionalTestUtils; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.multimap.api.embedded.EmbeddedMultimapCacheManagerFactory; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.remoting.transport.Address; import org.infinispan.test.data.Person; import org.testng.annotations.Test; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.multimap.impl.MultimapTestUtils.ELAIA; import static org.infinispan.multimap.impl.MultimapTestUtils.FELIX; import static org.infinispan.multimap.impl.MultimapTestUtils.IGOR; import static org.infinispan.multimap.impl.MultimapTestUtils.IZARO; import static org.infinispan.multimap.impl.MultimapTestUtils.JULIEN; import static org.infinispan.multimap.impl.MultimapTestUtils.NAMES_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.OIHANA; import static org.infinispan.multimap.impl.MultimapTestUtils.PEPE; import static org.infinispan.multimap.impl.MultimapTestUtils.RAMON; import static org.infinispan.multimap.impl.SortedSetBucket.ScoredValue.of; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; @Test(groups = "functional", testName = "distribution.DistributedMultimapSortedSetCacheTest") public class DistributedMultimapSortedSetCacheTest extends BaseDistFunctionalTest<String, Collection<Person>> { protected Map<Address, EmbeddedMultimapSortedSetCache<String, Person>> sortedSetCluster = new HashMap<>(); protected boolean fromOwner; public DistributedMultimapSortedSetCacheTest fromOwner(boolean fromOwner) { this.fromOwner = fromOwner; return this; } @Override protected void createCacheManagers() throws Throwable { super.createCacheManagers(); for (EmbeddedCacheManager cacheManager : cacheManagers) { EmbeddedMultimapCacheManager multimapCacheManager = (EmbeddedMultimapCacheManager) EmbeddedMultimapCacheManagerFactory.from(cacheManager); sortedSetCluster.put(cacheManager.getAddress(), multimapCacheManager.getMultimapSortedSet(cacheName)); } } @Override protected SerializationContextInitializer getSerializationContext() { return MultimapSCI.INSTANCE; } @Override protected String[] parameterNames() { return concat(super.parameterNames(), "fromOwner"); } @Override protected Object[] parameterValues() { return concat(super.parameterValues(), fromOwner ? Boolean.TRUE : Boolean.FALSE); } @Override public Object[] factory() { return new Object[]{ new DistributedMultimapSortedSetCacheTest().fromOwner(false).cacheMode(CacheMode.DIST_SYNC).transactional(false), new DistributedMultimapSortedSetCacheTest().fromOwner(true).cacheMode(CacheMode.DIST_SYNC).transactional(false), }; } @Override protected void initAndTest() { for (EmbeddedMultimapSortedSetCache sortedSet : sortedSetCluster.values()) { assertThat(await(sortedSet.size(NAMES_KEY))).isEqualTo(0L); } } protected EmbeddedMultimapSortedSetCache<String, Person> getMultimapCacheMember() { return sortedSetCluster. values().stream().findFirst().orElseThrow(() -> new IllegalStateException("Cluster is empty")); } public void testAddMany() { initAndTest(); EmbeddedMultimapSortedSetCache<String, Person> sortedSet = getMultimapCacheMember(); await(sortedSet.addMany(NAMES_KEY, new double[] { 1.1, 9.1 }, new Person[] { OIHANA, ELAIA }, SortedSetAddArgs.create().build())); assertValuesAndOwnership(NAMES_KEY, of(1.1, OIHANA)); assertValuesAndOwnership(NAMES_KEY, of(9.1, ELAIA)); } public void testCount() { initAndTest(); EmbeddedMultimapSortedSetCache<String, Person> sortedSet = getMultimapCacheMember(); await(sortedSet.addMany(NAMES_KEY, new double[] { 1, 1, 2, 2, 2, 3, 3, 3 }, new Person[] { OIHANA, ELAIA, FELIX, RAMON, JULIEN, PEPE, IGOR, IZARO }, SortedSetAddArgs.create().build())); assertThat(await(sortedSet.size(NAMES_KEY))).isEqualTo(8); assertThat(await(sortedSet.count(NAMES_KEY, 1, true, 3, true))).isEqualTo(8); } public void testPop() { initAndTest(); EmbeddedMultimapSortedSetCache<String, Person> sortedSet = getMultimapCacheMember(); await(sortedSet.addMany(NAMES_KEY, new double[] { 1, 1, 2, 2, 2, 3, 3, 3 }, new Person[] { OIHANA, ELAIA, FELIX, RAMON, JULIEN, IGOR, IZARO, PEPE }, SortedSetAddArgs.create().build())); assertThat(await(sortedSet.size(NAMES_KEY))).isEqualTo(8); assertThat(await(sortedSet.pop(NAMES_KEY, false, 3))) .containsExactly(of(3, PEPE), of(3, IZARO), of(3, IGOR)); } public void testScore() { initAndTest(); EmbeddedMultimapSortedSetCache<String, Person> sortedSet = getMultimapCacheMember(); await(sortedSet.addMany(NAMES_KEY, new double[] { 1.1, 9.1 }, new Person[] { OIHANA, ELAIA }, SortedSetAddArgs.create().build())); assertThat(await(sortedSet.score(NAMES_KEY, OIHANA))).isEqualTo(1.1); assertThat(await(sortedSet.score(NAMES_KEY, ELAIA))).isEqualTo(9.1); } protected void assertValuesAndOwnership(String key, SortedSetBucket.ScoredValue<Person> value) { assertOwnershipAndNonOwnership(key, l1CacheEnabled); assertOnAllCaches(key, value); } protected void assertOnAllCaches(Object key, SortedSetBucket.ScoredValue<Person> value) { for (Map.Entry<Address, EmbeddedMultimapSortedSetCache<String, Person>> entry : sortedSetCluster.entrySet()) { FunctionalTestUtils.await(entry.getValue().get((String) key).thenAccept(v -> { assertNotNull(format("values on the key %s must be not null", key), v); assertTrue(format("values on the key '%s' must contain '%s' on node '%s'", key, value, entry.getKey()), v.contains(value)); }) ); } } }
6,410
43.520833
147
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/TxDistributedMultimapCacheTest.java
package org.infinispan.multimap.impl; import static java.util.Arrays.asList; import static org.infinispan.multimap.impl.MultimapTestUtils.JULIEN; import static org.infinispan.multimap.impl.MultimapTestUtils.NAMES_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.assertContaisKeyValue; import static org.infinispan.multimap.impl.MultimapTestUtils.assertMultimapCacheSize; import static org.infinispan.multimap.impl.MultimapTestUtils.putValuesOnMultimapCache; import static org.infinispan.transaction.LockingMode.OPTIMISTIC; import static org.infinispan.transaction.LockingMode.PESSIMISTIC; import static org.testng.AssertJUnit.fail; import java.util.ArrayList; import java.util.List; import jakarta.transaction.NotSupportedException; import jakarta.transaction.SystemException; import jakarta.transaction.TransactionManager; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.multimap.api.embedded.MultimapCache; import org.infinispan.test.data.Person; import org.infinispan.transaction.LockingMode; import org.infinispan.util.concurrent.IsolationLevel; import org.testng.annotations.Test; @Test(groups = "functional", testName = "distribution.TxDistributedMultimapCacheTest") public class TxDistributedMultimapCacheTest extends DistributedMultimapCacheTest { public TxDistributedMultimapCacheTest() { transactional = true; cleanup = CleanupPhase.AFTER_TEST; cacheMode = CacheMode.DIST_SYNC; } @Override protected String[] parameterNames() { return concat(super.parameterNames(), "fromOwner"); } @Override protected Object[] parameterValues() { return concat(super.parameterValues(), fromOwner ? Boolean.TRUE : Boolean.FALSE); } @Override public Object[] factory() { List testsToRun = new ArrayList(); testsToRun.addAll(txTests(OPTIMISTIC)); testsToRun.addAll(txTests(PESSIMISTIC)); return testsToRun.toArray(); } public void testExplicitTx() throws SystemException, NotSupportedException { initAndTest(); MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); TransactionManager tm1 = MultimapTestUtils.getTransactionManager(multimapCache); assertMultimapCacheSize(multimapCache, 1); tm1.begin(); try { putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN); if (fromOwner) { assertContaisKeyValue(multimapCache, NAMES_KEY, JULIEN); } tm1.commit(); } catch (Exception e) { fail(e.getMessage()); } assertValuesAndOwnership(NAMES_KEY, JULIEN); assertMultimapCacheSize(multimapCache, 2); } public void testExplicitTxWithRollback() throws SystemException, NotSupportedException { initAndTest(); MultimapCache<String, Person> multimapCache = getMultimapCacheMember(NAMES_KEY); TransactionManager tm1 = MultimapTestUtils.getTransactionManager(multimapCache); assertMultimapCacheSize(multimapCache, 1); tm1.begin(); try { putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN); if (fromOwner) { assertContaisKeyValue(multimapCache, NAMES_KEY, JULIEN); } } finally { tm1.rollback(); } assertKeyValueNotFoundInAllCaches(NAMES_KEY, JULIEN); assertMultimapCacheSize(multimapCache, 1); } private List txTests(LockingMode lockingMode) { return asList( new TxDistributedMultimapCacheTest() .fromOwner(false) .lockingMode(lockingMode) .isolationLevel(IsolationLevel.READ_COMMITTED), new TxDistributedMultimapCacheTest() .fromOwner(true) .lockingMode(lockingMode) .isolationLevel(IsolationLevel.READ_COMMITTED), new TxDistributedMultimapCacheTest() .fromOwner(false) .lockingMode(lockingMode). isolationLevel(IsolationLevel.REPEATABLE_READ), new TxDistributedMultimapCacheTest() .fromOwner(true) .lockingMode(lockingMode). isolationLevel(IsolationLevel.REPEATABLE_READ) ); } }
4,259
35.410256
91
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/TxEmbeddedMultimapCacheTest.java
package org.infinispan.multimap.impl; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.multimap.impl.MultimapTestUtils.JULIEN; import static org.infinispan.multimap.impl.MultimapTestUtils.KOLDO; import static org.infinispan.multimap.impl.MultimapTestUtils.NAMES_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.OIHANA; import static org.infinispan.multimap.impl.MultimapTestUtils.RAMON; import static org.infinispan.multimap.impl.MultimapTestUtils.assertMultimapCacheSize; import static org.infinispan.multimap.impl.MultimapTestUtils.getTransactionManager; import static org.infinispan.multimap.impl.MultimapTestUtils.putValuesOnMultimapCache; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import jakarta.transaction.NotSupportedException; import jakarta.transaction.SystemException; import jakarta.transaction.TransactionManager; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.multimap.api.embedded.EmbeddedMultimapCacheManagerFactory; import org.infinispan.multimap.api.embedded.MultimapCacheManager; import org.infinispan.test.data.Person; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.concurrent.IsolationLevel; import org.infinispan.util.function.SerializablePredicate; import org.testng.annotations.Test; /** * Multimap Cache with transactions in single cache * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ @Test(groups = "functional", testName = "multimap.TxEmbeddedMultimapCacheTest") public class TxEmbeddedMultimapCacheTest extends EmbeddedMultimapCacheTest { @Override protected EmbeddedCacheManager createCacheManager() throws Exception { // start a single multimapCache instance ConfigurationBuilder c = getDefaultStandaloneCacheConfig(true); c.locking().isolationLevel(IsolationLevel.READ_COMMITTED); EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(false); MultimapCacheManager multimapCacheManager = EmbeddedMultimapCacheManagerFactory.from(cm); multimapCacheManager.defineConfiguration("test", c.build()); multimapCache = multimapCacheManager.get("test"); return cm; } public void testSizeInExplicitTx() throws SystemException, NotSupportedException { assertMultimapCacheSize(multimapCache, 0); TransactionManager tm1 = getTransactionManager(multimapCache); tm1.begin(); try { putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN, OIHANA); assertMultimapCacheSize(multimapCache, 2); } finally { tm1.rollback(); } assertMultimapCacheSize(multimapCache, 0); } public void testSizeInExplicitTxWithRemoveNonExistentAndPut() throws SystemException, NotSupportedException { assertMultimapCacheSize(multimapCache, 0); putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN); assertMultimapCacheSize(multimapCache, 1); TransactionManager tm1 = getTransactionManager(multimapCache); tm1.begin(); try { await(multimapCache.remove("firstnames")); assertMultimapCacheSize(multimapCache, 1); putValuesOnMultimapCache(multimapCache, "firstnames", JULIEN, OIHANA, RAMON); assertMultimapCacheSize(multimapCache, 4); } finally { tm1.rollback(); } assertMultimapCacheSize(multimapCache, 1); } public void testSizeInExplicitTxWithRemoveKeyValue() throws SystemException, NotSupportedException { assertMultimapCacheSize(multimapCache, 0); putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN, OIHANA); assertMultimapCacheSize(multimapCache, 2); TransactionManager tm1 = getTransactionManager(multimapCache); tm1.begin(); try { await(multimapCache.remove(MultimapTestUtils.NAMES_KEY, JULIEN)); assertMultimapCacheSize(multimapCache, 1); } finally { tm1.rollback(); } assertMultimapCacheSize(multimapCache, 2); } public void testSizeInExplicitTxWithRemoveExistent() throws SystemException, NotSupportedException { assertMultimapCacheSize(multimapCache, 0); putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN); assertMultimapCacheSize(multimapCache, 1); TransactionManager tm1 = getTransactionManager(multimapCache); tm1.begin(); try { putValuesOnMultimapCache(multimapCache, NAMES_KEY, OIHANA); assertMultimapCacheSize(multimapCache, 2); await(multimapCache.remove(MultimapTestUtils.NAMES_KEY)); assertTrue(await(multimapCache.get(MultimapTestUtils.NAMES_KEY)).isEmpty()); } finally { tm1.rollback(); } assertMultimapCacheSize(multimapCache, 1); } public void testSizeInExplicitTxWithRemoveWithPredicate() throws SystemException, NotSupportedException { assertMultimapCacheSize(multimapCache, 0); putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN, OIHANA); assertMultimapCacheSize(multimapCache, 2); TransactionManager tm1 = getTransactionManager(multimapCache); tm1.begin(); try { await(multimapCache.remove(v -> v.getName().contains("Ju")) .thenCompose(r1 -> multimapCache.get(NAMES_KEY)) .thenAccept(values -> { assertTrue(values.contains(OIHANA)); assertFalse(values.contains(JULIEN)); } )); assertMultimapCacheSize(multimapCache, 1); } finally { tm1.rollback(); } assertMultimapCacheSize(multimapCache, 2); } public void testSizeInExplicitTxWithRemoveAllWithPredicate() throws SystemException, NotSupportedException { assertMultimapCacheSize(multimapCache, 0); putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN, OIHANA, KOLDO); assertMultimapCacheSize(multimapCache, 3); TransactionManager tm1 = getTransactionManager(multimapCache); tm1.begin(); try { SerializablePredicate<Person> removePredicate = v -> v.getName().contains("ih") || v.getName().contains("ol"); multimapCache.remove(removePredicate).thenAccept(r -> { assertMultimapCacheSize(multimapCache, 1); }).join(); } finally { tm1.rollback(); } assertMultimapCacheSize(multimapCache, 3); } public void testSizeInExplicitTxWithModification() throws SystemException, NotSupportedException { assertMultimapCacheSize(multimapCache, 0); putValuesOnMultimapCache(multimapCache, NAMES_KEY, OIHANA); assertMultimapCacheSize(multimapCache, 1); TransactionManager tm1 = getTransactionManager(multimapCache); tm1.begin(); try { putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN); putValuesOnMultimapCache(multimapCache, "morenames", RAMON); assertMultimapCacheSize(multimapCache, 3); } finally { tm1.rollback(); } assertMultimapCacheSize(multimapCache, 1); } public void testContainsMethodsInExplicitTxWithModification() throws SystemException, NotSupportedException { TransactionManager tm1 = getTransactionManager(multimapCache); tm1.begin(); await(multimapCache.containsKey(NAMES_KEY).thenAccept(c -> assertFalse(c))); await(multimapCache.containsValue(JULIEN).thenAccept(c -> assertFalse(c))); await(multimapCache.containsEntry(NAMES_KEY, JULIEN).thenAccept(c -> assertFalse(c))); try { putValuesOnMultimapCache(multimapCache, NAMES_KEY, JULIEN); await(multimapCache.containsKey(NAMES_KEY).thenAccept(c -> assertTrue(c))); await(multimapCache.containsValue(JULIEN).thenAccept(c -> assertTrue(c))); await(multimapCache.containsEntry(NAMES_KEY, JULIEN).thenAccept(c -> assertTrue(c))); } finally { tm1.rollback(); } await(multimapCache.containsKey(NAMES_KEY).thenAccept(c -> assertFalse(c))); await(multimapCache.containsValue(JULIEN).thenAccept(c -> assertFalse(c))); await(multimapCache.containsEntry(NAMES_KEY, JULIEN).thenAccept(c -> assertFalse(c))); } }
8,314
41.208122
119
java
null
infinispan-main/multimap/src/test/java/org/infinispan/multimap/impl/EmbeddedMultimapSortedSetCacheTest.java
package org.infinispan.multimap.impl; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.data.Person; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.infinispan.functional.FunctionalTestUtils.await; import static org.infinispan.multimap.impl.EmbeddedMultimapSortedSetCache.ERR_KEY_CAN_T_BE_NULL; import static org.infinispan.multimap.impl.EmbeddedMultimapSortedSetCache.ERR_MEMBER_CAN_T_BE_NULL; import static org.infinispan.multimap.impl.EmbeddedMultimapSortedSetCache.ERR_SCORES_CAN_T_BE_NULL; import static org.infinispan.multimap.impl.EmbeddedMultimapSortedSetCache.ERR_SCORES_VALUES_MUST_HAVE_SAME_SIZE; import static org.infinispan.multimap.impl.EmbeddedMultimapSortedSetCache.ERR_VALUES_CAN_T_BE_NULL; import static org.infinispan.multimap.impl.MultimapTestUtils.ELAIA; import static org.infinispan.multimap.impl.MultimapTestUtils.FELIX; import static org.infinispan.multimap.impl.MultimapTestUtils.IGOR; import static org.infinispan.multimap.impl.MultimapTestUtils.IZARO; import static org.infinispan.multimap.impl.MultimapTestUtils.JULIEN; import static org.infinispan.multimap.impl.MultimapTestUtils.KOLDO; import static org.infinispan.multimap.impl.MultimapTestUtils.NAMES_KEY; import static org.infinispan.multimap.impl.MultimapTestUtils.OIHANA; import static org.infinispan.multimap.impl.MultimapTestUtils.PEPE; import static org.infinispan.multimap.impl.MultimapTestUtils.RAMON; import static org.infinispan.multimap.impl.SortedSetBucket.ScoredValue.of; /** * Single Multimap Cache Test with Linked List * * @since 15.0 */ @Test(groups = "functional", testName = "multimap.EmbeddedMultimapSortedSetCacheTest") public class EmbeddedMultimapSortedSetCacheTest extends SingleCacheManagerTest { EmbeddedMultimapSortedSetCache<String, Person> sortedSetCache; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { // start a single cache instance EmbeddedCacheManager cm = TestCacheManagerFactory.createCacheManager(MultimapSCI.INSTANCE); ConfigurationBuilder builder = new ConfigurationBuilder(); cm.createCache("test", builder.build()); cm.getClassAllowList().addClasses(Person.class); sortedSetCache = new EmbeddedMultimapSortedSetCache<>(cm.getCache("test")); return cm; } public void validateSortedSetAddArgs() { SortedSetAddArgs emptyArgs = SortedSetAddArgs.create().build(); assertThat(emptyArgs).isNotNull(); assertThat(emptyArgs.addOnly).isFalse(); assertThat(emptyArgs.updateOnly).isFalse(); assertThat(emptyArgs.updateGreaterScoresOnly).isFalse(); assertThat(emptyArgs.updateLessScoresOnly).isFalse(); assertThat(emptyArgs.returnChangedCount).isFalse(); // updateOnly and addOnly can't both be true assertThat(SortedSetAddArgs.create().addOnly().build().addOnly).isTrue(); assertThat(SortedSetAddArgs.create().updateOnly().build().updateOnly).isTrue(); assertThatThrownBy(() -> SortedSetAddArgs.create().addOnly().updateOnly().build()).isInstanceOf( IllegalStateException.class).hasMessageContaining(SortedSetAddArgs.ADD_AND_UPDATE_ONLY_INCOMPATIBLE_ERROR); // updateGt, updateLt and addOnly can't be all true assertThat(SortedSetAddArgs.create().updateGreaterScoresOnly().build().updateGreaterScoresOnly).isTrue(); assertThat(SortedSetAddArgs.create().updateLessScoresOnly().build().updateLessScoresOnly).isTrue(); assertThatThrownBy(() -> SortedSetAddArgs.create().addOnly().updateLessScoresOnly().build()).isInstanceOf( IllegalStateException.class).hasMessageContaining(SortedSetAddArgs.ADD_AND_UPDATE_OPTIONS_INCOMPATIBLE_ERROR); assertThatThrownBy(() -> SortedSetAddArgs.create().addOnly().updateGreaterScoresOnly().build()).isInstanceOf( IllegalStateException.class).hasMessageContaining(SortedSetAddArgs.ADD_AND_UPDATE_OPTIONS_INCOMPATIBLE_ERROR); assertThatThrownBy(() -> SortedSetAddArgs.create().updateLessScoresOnly().updateGreaterScoresOnly().build()).isInstanceOf( IllegalStateException.class).hasMessageContaining(SortedSetAddArgs.ADD_AND_UPDATE_OPTIONS_INCOMPATIBLE_ERROR); } public void testAddMany() { SortedSetAddArgs emptyArgs = SortedSetAddArgs.create().build(); assertThat(await(sortedSetCache.addMany(NAMES_KEY, new double[] {}, new Person[] {}, emptyArgs))).isEqualTo(0); assertThat(await(sortedSetCache.addMany(NAMES_KEY, new double[] { 2, 4.2 }, new Person[] { OIHANA, ELAIA }, emptyArgs))).isEqualTo(2); assertThat(await(sortedSetCache.getValue(NAMES_KEY))).containsExactly(of(2, OIHANA), of(4.2, ELAIA) ); assertThat(await(sortedSetCache.addMany(NAMES_KEY, new double[] { 9 }, new Person[] { OIHANA }, emptyArgs))).isEqualTo(0); assertThat(await(sortedSetCache.getValue(NAMES_KEY))).containsExactly(of(4.2, ELAIA), of(9, OIHANA) ); assertThat(await(sortedSetCache.addMany(NAMES_KEY, new double[] { 10, 90 }, new Person[] { OIHANA, KOLDO }, emptyArgs))).isEqualTo(1); assertThat(await(sortedSetCache.getValue(NAMES_KEY))).containsExactly(of(4.2, ELAIA), of(10, OIHANA), of(90, KOLDO) ); // count updates assertThat(await(sortedSetCache.addMany(NAMES_KEY, new double[] { 7.9 }, new Person[] { ELAIA }, SortedSetAddArgs.create().returnChangedCount().build()))).isEqualTo(1); assertThat(await(sortedSetCache.getValue(NAMES_KEY))).containsExactly(of(7.9, ELAIA), of(10, OIHANA), of(90, KOLDO) ); // add only assertThat(await(sortedSetCache.addMany(NAMES_KEY, new double[] { 9.9, 1 }, new Person[] { ELAIA, JULIEN }, SortedSetAddArgs.create().addOnly().build()))).isEqualTo(1); assertThat(await(sortedSetCache.getValue(NAMES_KEY))).containsExactly(of(1, JULIEN), of(7.9, ELAIA), of(10, OIHANA), of(90, KOLDO) ); // update only (does not create) assertThat(await(sortedSetCache.addMany(NAMES_KEY, new double[] { 9.9, 2.2 }, new Person[] { ELAIA, RAMON }, SortedSetAddArgs.create().updateOnly().build()))).isEqualTo(0); assertThat(await(sortedSetCache.getValue(NAMES_KEY))).containsExactly(of(1, JULIEN), of(9.9, ELAIA), of(10, OIHANA), of(90, KOLDO) ); // update less than provided scores and create new ones assertThat(await(sortedSetCache.addMany(NAMES_KEY, new double[] { 8.9, 11.1, 0.8 }, new Person[] { ELAIA, OIHANA, RAMON }, SortedSetAddArgs.create().updateLessScoresOnly().build()))).isEqualTo(1); assertThat(await(sortedSetCache.getValue(NAMES_KEY))).containsExactly(of(0.8, RAMON), of(1, JULIEN), of(8.9, ELAIA), of(10, OIHANA), of(90, KOLDO) ); // update greater than provided scores and create new ones assertThat(await(sortedSetCache.addMany(NAMES_KEY, new double[] { 6.9, 12.1, 32.98 }, new Person[] { ELAIA, OIHANA, FELIX }, SortedSetAddArgs.create().updateGreaterScoresOnly().build()))).isEqualTo(1); assertThat(await(sortedSetCache.getValue(NAMES_KEY))).containsExactly(of(0.8, RAMON), of(1, JULIEN), of(8.9, ELAIA), of(12.1, OIHANA), of(32.98, FELIX), of(90, KOLDO) ); // add a new value with the same score as other assertThat(await(sortedSetCache.addMany(NAMES_KEY, new double[] { 1 }, new Person[] { PEPE }, emptyArgs))).isEqualTo(1); assertThat(await(sortedSetCache.getValue(NAMES_KEY))).containsExactly(of(0.8, RAMON), of(1, JULIEN), of(1, PEPE), of(8.9, ELAIA), of(12.1, OIHANA), of(32.98, FELIX), of(90, KOLDO) ); // Errors assertThatThrownBy(() -> await(sortedSetCache.addMany(NAMES_KEY, new double[] { 1 }, new Person[] {}, emptyArgs))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ERR_SCORES_VALUES_MUST_HAVE_SAME_SIZE); assertThatThrownBy(() -> await(sortedSetCache.addMany(NAMES_KEY, new double[] {}, new Person[] { OIHANA }, emptyArgs))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(ERR_SCORES_VALUES_MUST_HAVE_SAME_SIZE); assertThatThrownBy(() -> await(sortedSetCache.addMany(null, null, null, emptyArgs))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); assertThatThrownBy(() -> await(sortedSetCache.addMany(null, null, null, emptyArgs))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); assertThatThrownBy(() -> await(sortedSetCache.addMany(NAMES_KEY, null, null, emptyArgs))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_SCORES_CAN_T_BE_NULL); assertThatThrownBy(() -> await(sortedSetCache.addMany(NAMES_KEY, new double[0], null, emptyArgs))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_VALUES_CAN_T_BE_NULL); } public void testCount() { assertThat(await(sortedSetCache.count(NAMES_KEY, 0, false, 0, false))).isEqualTo(0); await(sortedSetCache.addMany(NAMES_KEY, new double[] {-5, 1, 2, 5, 8, 8, 8, 9, 10}, new Person[] {OIHANA, ELAIA, KOLDO, RAMON, JULIEN, FELIX, PEPE, IGOR, IZARO}, SortedSetAddArgs.create().build())); assertThat(await(sortedSetCache.count(NAMES_KEY, 8, true, 8, true))).isEqualTo(3); assertThat(await(sortedSetCache.count(NAMES_KEY, 8, false, 8, false))).isEqualTo(0); assertThat(await(sortedSetCache.count(NAMES_KEY, 8, true, 8, false))).isEqualTo(0); assertThat(await(sortedSetCache.count(NAMES_KEY, 8, false, 8, true))).isEqualTo(0); assertThat(await(sortedSetCache.count(NAMES_KEY, 1, true, 9, true))).isEqualTo(7); assertThat(await(sortedSetCache.count(NAMES_KEY, 1, true, 9, false))).isEqualTo(6); assertThat(await(sortedSetCache.count(NAMES_KEY, 1, false, 9, false))).isEqualTo(5); assertThat(await(sortedSetCache.count(NAMES_KEY, 1, false, 9, true))).isEqualTo(6); assertThatThrownBy(() -> await(sortedSetCache.count(null, 0, false, 0, false))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); } public void testPop() { assertThat(await(sortedSetCache.pop(NAMES_KEY, false, 10))).isEmpty(); await(sortedSetCache.addMany(NAMES_KEY, new double[] {-5, 1}, new Person[] {OIHANA, ELAIA}, SortedSetAddArgs.create().build())); assertThat(await(sortedSetCache.pop(NAMES_KEY, true, 1))).containsExactly(of(-5, OIHANA)); assertThat(await(sortedSetCache.pop(NAMES_KEY, true, 10))).containsExactly(of(1, ELAIA)); assertThat(await(sortedSetCache.getValue(NAMES_KEY))).isNull(); await(sortedSetCache.addMany(NAMES_KEY, new double[] {-5, 1, 2, 5, 8, 8, 8, 9, 10}, new Person[] {OIHANA, ELAIA, KOLDO, RAMON, FELIX, JULIEN, PEPE, IGOR, IZARO}, SortedSetAddArgs.create().build())); assertThat(await(sortedSetCache.pop(NAMES_KEY, true, 2))) .containsExactly(of(-5, OIHANA), of(1, ELAIA)); assertThat(await(sortedSetCache.pop(NAMES_KEY, false, 2))) .containsExactly(of(10, IZARO), of(9, IGOR)); assertThatThrownBy(() -> await(sortedSetCache.pop(null, true, 1))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); } public void testScore() { assertThat(await(sortedSetCache.score(NAMES_KEY, OIHANA))).isNull(); await(sortedSetCache.addMany(NAMES_KEY, new double[] {-5, 1}, new Person[] {OIHANA, ELAIA}, SortedSetAddArgs.create().build())); assertThat(await(sortedSetCache.score(NAMES_KEY, OIHANA))).isEqualTo(-5); assertThat(await(sortedSetCache.score(NAMES_KEY, OIHANA))).isEqualTo(-5); assertThat(await(sortedSetCache.score(NAMES_KEY, FELIX))).isNull(); assertThatThrownBy(() -> await(sortedSetCache.score(null, null))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_KEY_CAN_T_BE_NULL); assertThatThrownBy(() -> await(sortedSetCache.score(NAMES_KEY, null))) .isInstanceOf(NullPointerException.class) .hasMessageContaining(ERR_MEMBER_CAN_T_BE_NULL); } }
12,554
61.775
189
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/api/embedded/package-info.java
/** * Embedded Multimap Cache. * * @api.public */ package org.infinispan.multimap.api.embedded;
100
13.428571
45
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/api/embedded/MultimapCacheManager.java
package org.infinispan.multimap.api.embedded; import org.infinispan.commons.util.Experimental; import org.infinispan.configuration.cache.Configuration; @Experimental public interface MultimapCacheManager<K, V> { /** * Defines a named multimap cache's configuration by using the provided configuration * If this cache was already configured, either declaratively or programmatically, this method will throw a * {@link org.infinispan.commons.CacheConfigurationException}. * Currently, the MultimapCache with the given name "foo" can be also accessed as a regular cache named "foo". * * @param name name of multimap cache whose configuration is being defined * @param configuration configuration overrides to use * @return a cloned configuration instance */ Configuration defineConfiguration(String name, Configuration configuration); /** * Retrieves a named multimap cache from the system. * * @param name, name of multimap cache to retrieve * @return null if no configuration exists as per rules set above, otherwise returns a multimap cache instance * identified by cacheName and doesn't support duplicates */ default MultimapCache<K, V> get(String name) { return get(name, false); } /** * Retrieves a named multimap cache from the system. * * @param name, name of multimap cache to retrieve * @param supportsDuplicates, boolean check to see whether duplicates are supported or not * @return null if no configuration exists as per rules set above, otherwise returns a multimap cache instance * identified by cacheName */ MultimapCache<K, V> get(String name, boolean supportsDuplicates); }
1,718
39.928571
113
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/api/embedded/MultimapCache.java
package org.infinispan.multimap.api.embedded; import java.util.Collection; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Predicate; import org.infinispan.commons.util.Experimental; import org.infinispan.container.entries.CacheEntry; import org.infinispan.multimap.api.BasicMultimapCache; import org.infinispan.util.function.SerializablePredicate; /** * {@inheritDoc} * * Embedded version of MultimapCache. * * @author Katia Aresti, karesti@redhat.com * @see <a href="http://infinispan.org/documentation/">Infinispan documentation</a> * @since 9.2 */ @Experimental public interface MultimapCache<K, V> extends BasicMultimapCache<K, V> { /** * Retrieves a CacheEntry corresponding to a specific key in this multimap cache. * * @param key the key whose associated cache entry is to be returned * @return the cache entry to which the specified key is mapped, or {@link Optional#empty()} if this multimap * contains no mapping for the key * @since 9.2 */ CompletableFuture<Optional<CacheEntry<K, Collection<V>>>> getEntry(K key); /** * Asynchronous method. Removes every value that match the {@link Predicate}. * <p> * This method <b>is blocking</b> used in a explicit transaction context. * * @param p the predicate to be tested on every value in this multimap cache * @return {@link CompletableFuture} containing a {@link Void} * @since 9.2 */ CompletableFuture<Void> remove(Predicate<? super V> p); /** * Overloaded method of {@link MultimapCache#remove(Predicate)} with {@link SerializablePredicate}. The compiler will * pick up this method and make the given predicate {@link java.io.Serializable}. * * @param p the predicate to be tested on every value in this multimap cache * @return {@link CompletableFuture} containing a {@link Void} * @since 9.2 */ default CompletableFuture<Void> remove(SerializablePredicate<? super V> p) { return this.remove((Predicate) p); } }
2,055
33.847458
120
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/api/embedded/EmbeddedMultimapCacheManagerFactory.java
package org.infinispan.multimap.api.embedded; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.multimap.impl.EmbeddedMultimapCacheManager; /** * A {@link MultimapCache} factory for embedded cached. * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public final class EmbeddedMultimapCacheManagerFactory { private EmbeddedMultimapCacheManagerFactory() { } public static MultimapCacheManager from(EmbeddedCacheManager cacheManager) { return new EmbeddedMultimapCacheManager(cacheManager); } }
554
25.428571
79
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/SetBucket.java
package org.infinispan.multimap.impl; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.commons.util.Util; import org.infinispan.marshall.protostream.impl.MarshallableUserObject; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; /** * Bucket used to store Set data type. * * @author Vittorio Rigamonti * @since 15.0 */ @ProtoTypeId(ProtoStreamTypeIds.MULTIMAP_SET_BUCKET) public class SetBucket<V> { final Set<V> values; public SetBucket() { this.values = new HashSet<>(); } public SetBucket(V value) { var set = new HashSet<V>(1); set.add(value); this.values = set; } public SetBucket(HashSet<V> values) { this.values = values; } public static <V> SetBucket<V> create(V value) { return new SetBucket<>(value); } @ProtoFactory SetBucket(Collection<MarshallableUserObject<V>> wrappedValues) { this((HashSet<V>) wrappedValues.stream().map(MarshallableUserObject::get) .collect(Collectors.toCollection(HashSet::new))); } @ProtoField(number = 1, collectionImplementation = ArrayList.class) Collection<MarshallableUserObject<V>> getWrappedValues() { return this.values.stream().map(MarshallableUserObject::new).collect(Collectors.toList()); } public Set<V> values() { return new HashSet<>(values); } public boolean contains(V value) { for (V v : values) { if (Objects.deepEquals(v, value)) { return Boolean.TRUE; } } return Boolean.FALSE; } public boolean isEmpty() { return values.isEmpty(); } public int size() { return values.size(); } /** * @return a defensive copy of the {@link #values} collection. */ public Set<V> toSet() { return new HashSet<>(values); } @Override public String toString() { return "SetBucket{values=" + Util.toStr(values) + '}'; } public boolean add(V value) { return values.add(value); } public boolean addAll(Collection<V> values) { return this.values.addAll(values); } }
2,400
23.752577
96
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/PersistenceContextInitializer.java
package org.infinispan.multimap.impl; import org.infinispan.multimap.impl.internal.MultimapObjectWrapper; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; @AutoProtoSchemaBuilder( dependsOn = org.infinispan.marshall.persistence.impl.PersistenceContextInitializer.class, includeClasses = { Bucket.class, ListBucket.class, HashMapBucket.class, HashMapBucket.BucketEntry.class, MultimapObjectWrapper.class, SetBucket.class, SortedSetBucket.class, SortedSetBucket.ScoredValue.class }, schemaFileName = "persistence.multimap.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.persistence.multimap", service = false ) interface PersistenceContextInitializer extends SerializationContextInitializer { }
953
35.692308
95
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/ExternalizerIds.java
package org.infinispan.multimap.impl; /** * Ids range: 2050 - 2099 * Externalizer Ids that identity the functions used in {@link EmbeddedMultimapCache} * * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @author Katia Aresti - karesti@redhat.com * @since 9.2 */ public interface ExternalizerIds { Integer PUT_KEY_VALUE_FUNCTION = 2050; Integer REMOVE_KEY_VALUE_FUNCTION = 2051; Integer CONTAINS_KEY_VALUE_FUNCTION = 2052; Integer GET_FUNCTION = 2053; Integer OFFER_FUNCTION = 2054; Integer INDEX_FUNCTION = 2055; Integer POLL_FUNCTION = 2056; Integer SET_FUNCTION = 2057; Integer SUBLIST_FUNCTION = 2058; Integer INDEXOF_FUNCTION = 2059; Integer INSERT_FUNCTION = 2060; Integer REMOVE_COUNT_FUNCTION = 2061; Integer HASH_MAP_PUT_FUNCTION = 2062; Integer MULTIMAP_CONVERTER = 2063; Integer SET_ADD_FUNCTION = 2064; Integer TRIM_FUNCTION = 2065; Integer ROTATE_FUNCTION = 2066; Integer SORTED_SET_ADD_MANY_FUNCTION = 2067; Integer HASH_MAP_KEYSET_FUNCTION = 2068; Integer HASH_MAP_VALUES_FUNCTION = 2069; Integer SORTED_SET_COUNT_FUNCTION = 2070; Integer SORTED_SET_POP_FUNCTION = 2071; Integer SET_GET_FUNCTION = 2072; Integer SET_SET_FUNCTION = 2073; Integer HASH_MAP_REMOVE_FUNCTION = 2074; Integer SORTED_SET_SCORE_FUNCTION = 2075; Integer HASH_MAP_REPLACE_FUNCTION = 2076; }
1,402
34.075
85
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/EmbeddedMultimapCache.java
package org.infinispan.multimap.impl; import static java.util.Objects.requireNonNull; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.concurrent.CompletableFuture.runAsync; import static java.util.concurrent.CompletableFuture.supplyAsync; import java.util.Collection; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.Predicate; import jakarta.transaction.SystemException; import jakarta.transaction.TransactionManager; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.functional.FunctionalMap; import org.infinispan.functional.impl.FunctionalMapImpl; import org.infinispan.functional.impl.ReadWriteMapImpl; import org.infinispan.multimap.api.BasicMultimapCache; import org.infinispan.multimap.api.embedded.MultimapCache; import org.infinispan.multimap.impl.function.multimap.ContainsFunction; import org.infinispan.multimap.impl.function.multimap.GetFunction; import org.infinispan.multimap.impl.function.multimap.PutFunction; import org.infinispan.multimap.impl.function.multimap.RemoveFunction; import org.infinispan.commons.util.concurrent.CompletableFutures; /** * Embedded implementation of {@link MultimapCache} * * <h2>Transactions</h2> * * EmbeddedMultimapCache supports implicit transactions without blocking. The following methods block when * they are called in a explicit transaction context. This limitation could be improved in the following versions if * technically possible : * * <ul> * <li>{@link BasicMultimapCache#size()} </li> * <li>{@link BasicMultimapCache#containsEntry(Object, Object)}</li> * </ul> * * More about transactions in : * <a href="http://infinispan.org/docs/dev/user_guide/user_guide.html#transactions">the Infinispan Documentation</a>. * * <h2>Duplicates</h2> * MultimapCache can optionally support duplicate values on keys. {@link * * <pre> * multimapCache.put("k", "v1").join(); * multimapCache.put("k", "v2").join(); * multimapCache.put("k", "v2").join(); * multimapCache.put("k", "v2").join(); * * multimapCache.get("k").thenAccept(values -> System.out.println(values.size())); * // prints the value 4. "k" -> ["v1", "v2", "v2", "v2"] * </pre> * * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public class EmbeddedMultimapCache<K, V> implements MultimapCache<K, V> { private final FunctionalMap.ReadWriteMap<K, Bucket<V>> readWriteMap; private final AdvancedCache<K, Bucket<V>> cache; private final InternalEntryFactory entryFactory; private final boolean supportsDuplicates; public EmbeddedMultimapCache(Cache<K, Bucket<V>> cache, boolean supportsDuplicates) { //TODO: ISPN-11452 Multimaps don't support transcoding, so disable data conversions this.cache = cache.getAdvancedCache(); FunctionalMapImpl<K, Bucket<V>> functionalMap = FunctionalMapImpl.create(this.cache); this.readWriteMap = ReadWriteMapImpl.create(functionalMap); this.entryFactory = this.cache.getComponentRegistry().getInternalEntryFactory().running(); this.supportsDuplicates = supportsDuplicates; } @Override public CompletableFuture<Void> put(K key, V value) { requireNonNull(key, "key can't be null"); requireNonNull(value, "value can't be null"); return readWriteMap.eval(key, new PutFunction<>(value, supportsDuplicates)); } @Override public CompletableFuture<Collection<V>> get(K key) { requireNonNull(key, "key can't be null"); return readWriteMap.eval(key, new GetFunction<>(supportsDuplicates)); } @Override public CompletableFuture<Optional<CacheEntry<K, Collection<V>>>> getEntry(K key) { requireNonNull(key, "key can't be null"); return cache.getAdvancedCache().getCacheEntryAsync(key) .thenApply(entry -> { if (entry == null) return Optional.empty(); return Optional.of(entryFactory.create(entry.getKey(),(supportsDuplicates ? entry.getValue().toList(): entry.getValue().toSet()) , entry.getMetadata())); }); } @Override public CompletableFuture<Boolean> remove(K key) { requireNonNull(key, "key can't be null"); return readWriteMap.eval(key, new RemoveFunction<>()); } @Override public CompletableFuture<Boolean> remove(K key, V value) { requireNonNull(key, "key can't be null"); requireNonNull(value, "value can't be null"); return readWriteMap.eval(key, new RemoveFunction<>(value, supportsDuplicates)); } @Override public CompletableFuture<Void> remove(Predicate<? super V> p) { requireNonNull(p, "predicate can't be null"); try { // block on explicit tx return isExplicitTxContext() ? completedFuture(this.removeInternal(p)) : runAsync(() -> this.removeInternal(p)); } catch (SystemException e) { throw CompletableFutures.asCompletionException(e); } } @Override public CompletableFuture<Boolean> containsKey(K key) { requireNonNull(key, "key can't be null"); return readWriteMap.eval(key, new ContainsFunction<>()); } @Override public CompletableFuture<Boolean> containsValue(V value) { requireNonNull(value, "value can't be null"); try { // block on explicit tx return isExplicitTxContext() ? completedFuture(containsEntryInternal(value)) : supplyAsync(() -> containsEntryInternal(value)); } catch (SystemException e) { throw CompletableFutures.asCompletionException(e); } } @Override public CompletableFuture<Boolean> containsEntry(K key, V value) { requireNonNull(key, "key can't be null"); requireNonNull(value, "value can't be null"); return readWriteMap.eval(key, new ContainsFunction<>(value)); } @Override public CompletableFuture<Long> size() { try { // block on explicit tx return isExplicitTxContext() ? completedFuture(sizeInternal()) : supplyAsync(this::sizeInternal); } catch (SystemException e) { throw CompletableFutures.asCompletionException(e); } } private boolean isExplicitTxContext() throws SystemException { TransactionManager transactionManager = cache.getAdvancedCache().getTransactionManager(); return transactionManager != null && transactionManager.getTransaction() != null; } private Void removeInternal(Predicate<? super V> p) { // Iterate over keys on the caller thread so that compute operations join the running transaction (if any) cache.keySet().forEach(key -> cache.computeIfPresent(key, (k, bucket) -> { Bucket<V> newBucket = bucket.removeIf(p); if (newBucket == null) { return bucket; } return newBucket.isEmpty() ? null : newBucket; })); return null; } private Boolean containsEntryInternal(V value) { return cache.values().stream().anyMatch(bucket -> bucket.contains(value)); } private Long sizeInternal() { return cache.values().stream().mapToLong(Bucket::size).sum(); } @Override public boolean supportsDuplicates() { return supportsDuplicates; } public Cache<K, Bucket<V>> getCache() { return cache; } }
7,509
35.813725
167
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/EmbeddedMultimapPairCache.java
package org.infinispan.multimap.impl; import static java.util.Objects.requireNonNull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.ThreadLocalRandom; import java.util.function.BiFunction; import java.util.stream.Collectors; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.functional.FunctionalMap; import org.infinispan.functional.impl.FunctionalMapImpl; import org.infinispan.functional.impl.ReadWriteMapImpl; import org.infinispan.multimap.impl.function.hmap.HashMapKeySetFunction; import org.infinispan.multimap.impl.function.hmap.HashMapPutFunction; import org.infinispan.multimap.impl.function.hmap.HashMapRemoveFunction; import org.infinispan.multimap.impl.function.hmap.HashMapReplaceFunction; import org.infinispan.multimap.impl.function.hmap.HashMapValuesFunction; /** * Multimap which holds a collection of key-values pairs. * <p> * This multimap can create arbitrary objects by holding a collection of key-value pairs under a single cache * entry. It is possible to add or remove attributes dynamically, varying the structure format between keys. * </p> * Note that the structure is not distributed, it is under a single key, and the distribution happens per key. * * @param <K>: The type of key to identify the structure. * @param <HK>: The structure type for keys. * @param <HV>: The structure type for values. * @since 15.0 * @author José Bolina */ public class EmbeddedMultimapPairCache<K, HK, HV> { public static final String ERR_KEY_CAN_T_BE_NULL = "key can't be null"; public static final String ERR_PROPERTY_CANT_BE_NULL = "property can't be null"; public static final String ERR_PROPERTIES_CANT_BE_EMPTY = "properties can't be empty"; public static final String ERR_COUNT_MUST_BE_POSITIVE = "count must be positive"; private final FunctionalMap.ReadWriteMap<K, HashMapBucket<HK, HV>> readWriteMap; private final AdvancedCache<K, HashMapBucket<HK, HV>> cache; public EmbeddedMultimapPairCache(Cache<K, HashMapBucket<HK, HV>> cache) { this.cache = cache.getAdvancedCache(); FunctionalMapImpl<K, HashMapBucket<HK, HV>> functionalMap = FunctionalMapImpl.create(this.cache); this.readWriteMap = ReadWriteMapImpl.create(functionalMap); } /** * Set the given key-value pair in the multimap under the given key. * </p> * If the key is not present, a new multimap is created. * * @param key: Cache key to store the values. * @param entries: Key-value pairs to store. * @return {@link CompletionStage} with the number of created entries. */ @SafeVarargs public final CompletionStage<Integer> set(K key, Map.Entry<HK, HV>... entries) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); List<Map.Entry<HK, HV>> values = new ArrayList<>(Arrays.asList(entries)); return readWriteMap.eval(key, new HashMapPutFunction<>(values)); } /** * Get the key-value pairs under the given key. * * @param key: Cache key to retrieve the values. * @return {@link CompletionStage} containing a {@link Map} with the key-value pairs or an empty map if the key * is not found. */ public CompletionStage<Map<HK, HV>> get(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return cache.getCacheEntryAsync(key) .thenApply(entry -> { if (entry == null) { return Map.of(); } HashMapBucket<HK, HV> bucket = entry.getValue(); return bucket.converted(); }); } public CompletionStage<HV> get(K key, HK property) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(property, ERR_KEY_CAN_T_BE_NULL); return cache.getCacheEntryAsync(key) .thenApply(entry -> { if (entry == null) { return null; } HashMapBucket<HK, HV> bucket = entry.getValue(); return bucket.get(property); }); } /** * Return the values of the given {@param properties} stored under the given {@param key}. * * @param key: Cache key to retrieve the hash map. * @param properties: Properties to retrieve. * @return {@link CompletionStage} containing a {@link Map} with the key-value pairs or an empty map if the key * is not found. */ @SafeVarargs public final CompletionStage<Map<HK, HV>> get(K key, HK ... properties) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(properties, ERR_PROPERTY_CANT_BE_NULL); requireTrue(properties.length > 0, ERR_PROPERTIES_CANT_BE_EMPTY); Set<HK> propertySet = Set.of(properties); requireNonNullArgument(propertySet, ERR_PROPERTY_CANT_BE_NULL); return cache.getCacheEntryAsync(key) .thenApply(entry -> { if (entry == null) { return Map.of(); } HashMapBucket<HK, HV> bucket = entry.getValue(); return bucket.getAll(propertySet); }); } /** * Get the size of the hash map stored under key. * * @param key: Cache key to retrieve the hash map. * @return {@link CompletionStage} containing the size of the hash map or 0 if the key is not found. */ public CompletionStage<Integer> size(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return cache.getCacheEntryAsync(key) .thenApply(entry -> { if (entry == null) { return 0; } HashMapBucket<HK, HV> bucket = entry.getValue(); return bucket.size(); }); } /** * Get the key set from the hash map stored under the given key. * * @param key: Cache key to retrieve the hash map. * @return {@link CompletionStage} containing a {@link Set} with the keys or an empty set if the key is not found. */ public CompletionStage<Set<HK>> keySet(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return readWriteMap.eval(key, new HashMapKeySetFunction<>()); } /** * Get the values from the hash map stored under the given key. * * @param key: Cache key to retrieve the hash map. * @return {@link CompletionStage} containing a {@link Collection} with the values or an empty collection if the key * is not found. */ public CompletionStage<Collection<HV>> values(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return readWriteMap.eval(key, new HashMapValuesFunction<>()); } /** * Verify if the property is present in the hash map stored under the given key. * * @param key: Cache key to retrieve the hash map. * @param property: Property to verify in the hash map. * @return {@link CompletionStage} with {@code true} if the property is present or {@code false} otherwise. */ public CompletionStage<Boolean> contains(K key, HK property) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(property, ERR_PROPERTY_CANT_BE_NULL); return cache.getCacheEntryAsync(key) .thenApply(entry -> { if (entry == null) { return false; } HashMapBucket<HK, HV> bucket = entry.getValue(); return bucket.containsKey(property); }); } /** * Remove the properties in the hash map under the given key. * * @param key: Cache key to remove the properties. * @param property: Property to remove. * @param properties: Additional properties to remove. * @return {@link CompletionStage} with the number of removed properties. */ @SafeVarargs public final CompletionStage<Integer> remove(K key, HK property, HK ...properties) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(property, ERR_PROPERTY_CANT_BE_NULL); List<HK> propertiesList = new ArrayList<>(); propertiesList.add(property); propertiesList.addAll(Arrays.asList(properties)); return readWriteMap.eval(key, new HashMapRemoveFunction<>(propertiesList)); } /** * Remove the given properties in the hash map stored under the given key. * * @param key: Cache key to remove the properties. * @param properties: Properties to remove. * @return {@link CompletionStage} with the number of removed properties. */ public final CompletionStage<Integer> remove(K key, Collection<HK> properties) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(properties, ERR_PROPERTY_CANT_BE_NULL); if (properties.isEmpty()) return CompletableFuture.completedFuture(0); return readWriteMap.eval(key, new HashMapRemoveFunction<>(properties)); } /** * Execute the given {@param biConsumer} on the value mapped to the {@param property} stored under {@param key}. * <p> * If the key is not present, a new entry is created. The {@param biConsumer} is executed until the value is * replaced with the new value. This is implementation behaves like {@link Map#compute(Object, BiFunction)}. * * @param key: The key to retrieve the {@link HashMapBucket}. * @param property: The property to be updated. * @param biConsumer: Receives the key and previous value and returns the new value. * @return A {@link CompletionStage} with the new value returned from {@param biConsumer}. * @see Map#compute(Object, BiFunction) */ public CompletionStage<HV> compute(K key, HK property, BiFunction<HK, HV, HV> biConsumer) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(property, ERR_PROPERTY_CANT_BE_NULL); return cache.getCacheEntryAsync(key) .thenCompose(entry -> { HV newValue; HV oldValue = null; if (entry != null) { oldValue = entry.getValue().get(property); } newValue = biConsumer.apply(property, oldValue); CompletionStage<Boolean> done = readWriteMap.eval(key, new HashMapReplaceFunction<>(property, oldValue, newValue)); return done.thenCompose(replaced -> { if (replaced) return CompletableFuture.completedFuture(newValue); return compute(key, property, biConsumer); }); }); } /** * Select {@param count} key-value pairs from the hash map stored under the given key. * <p> * The returned values are randomly selected from the underlying map. An {@param count} bigger than the * size of the stored map does not raise an exception. * * @param key: Cache key to retrieve the stored hash map. * @param count: Number of key-value pairs to select. * @return {@link CompletionStage} containing a {@link Map} with the key-value pairs or null if not found. */ public CompletionStage<Map<HK, HV>> subSelect(K key, int count) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requirePositive(count, ERR_COUNT_MUST_BE_POSITIVE); return cache.getCacheEntryAsync(key) .thenApply(entry -> { if (entry == null) return null; Map<HK, HV> converted = entry.getValue().converted(); if (count >= converted.size()) return converted; List<Map.Entry<HK, HV>> entries = new ArrayList<>(converted.entrySet()); Collections.shuffle(entries, ThreadLocalRandom.current()); return entries.stream() .limit(count) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); }); } private static void requirePositive(int value, String message) { if (value <= 0) { throw new IllegalArgumentException(message); } } private static void requireTrue(boolean condition, String message) { if (!condition) { throw new IllegalArgumentException(message); } } private static void requireNonNullArgument(Collection<?> arguments, String message) { for (Object argument : arguments) { requireNonNull(argument, message); } } }
12,483
38.757962
130
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/EmbeddedMultimapListCache.java
package org.infinispan.multimap.impl; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.functional.FunctionalMap; import org.infinispan.functional.impl.FunctionalMapImpl; import org.infinispan.functional.impl.ReadWriteMapImpl; import org.infinispan.multimap.impl.function.list.RotateFunction; import org.infinispan.multimap.impl.function.list.IndexFunction; import org.infinispan.multimap.impl.function.list.IndexOfFunction; import org.infinispan.multimap.impl.function.list.InsertFunction; import org.infinispan.multimap.impl.function.list.OfferFunction; import org.infinispan.multimap.impl.function.list.PollFunction; import org.infinispan.multimap.impl.function.list.RemoveCountFunction; import org.infinispan.multimap.impl.function.list.SetFunction; import org.infinispan.multimap.impl.function.list.SubListFunction; import org.infinispan.multimap.impl.function.list.TrimFunction; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import static java.util.Objects.requireNonNull; /** * Multimap with Linked List Implementation methods * * @author Katia Aresti * @since 15.0 */ public class EmbeddedMultimapListCache<K, V> { public static final String ERR_KEY_CAN_T_BE_NULL = "key can't be null"; public static final String ERR_ELEMENT_CAN_T_BE_NULL = "element can't be null"; public static final String ERR_VALUE_CAN_T_BE_NULL = "value can't be null"; public static final String ERR_PIVOT_CAN_T_BE_NULL = "pivot can't be null"; protected final FunctionalMap.ReadWriteMap<K, ListBucket<V>> readWriteMap; protected final AdvancedCache<K, ListBucket<V>> cache; protected final InternalEntryFactory entryFactory; public EmbeddedMultimapListCache(Cache<K, ListBucket<V>> cache) { this.cache = cache.getAdvancedCache(); FunctionalMapImpl<K, ListBucket<V>> functionalMap = FunctionalMapImpl.create(this.cache); this.readWriteMap = ReadWriteMapImpl.create(functionalMap); this.entryFactory = this.cache.getComponentRegistry().getInternalEntryFactory().running(); } /** * Get the value as a collection * * @param key, the name of the list * @return the collection with values if such exist, or an empty collection if the key is not present */ public CompletionStage<Collection<V>> get(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return getEntry(key).thenApply(entry -> { if (entry != null) { return entry.getValue(); } return List.of(); }); } private CompletionStage<CacheEntry<K, Collection<V>>> getEntry(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return cache.getAdvancedCache().getCacheEntryAsync(key) .thenApply(entry -> { if (entry == null) return null; return entryFactory.create(entry.getKey(),(entry.getValue().toDeque()) , entry.getMetadata()); }); } /** * Inserts the specified element at the front of the specified list. * * @param key, the name of the list * @param value, the element to be inserted * @return {@link CompletionStage} containing a {@link Void} */ public CompletionStage<Void> offerFirst(K key, V value) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(value, ERR_VALUE_CAN_T_BE_NULL); return readWriteMap.eval(key, new OfferFunction<>(value, true)); } /** * Inserts the specified element at the end of the specified list. * * @param key, the name of the list * @param value, the element to be inserted * @return {@link CompletionStage} containing a {@link Void} */ public CompletionStage<Void> offerLast(K key, V value) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(value, ERR_VALUE_CAN_T_BE_NULL); return readWriteMap.eval(key, new OfferFunction<>(value, false)); } /** * Returns true if the list associated with the key exists. * * @param key, the name of the list * @return {@link CompletionStage} containing a {@link Boolean} */ public CompletionStage<Boolean> containsKey(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return cache.containsKeyAsync(key); } /** * Returns the number of elements in the list. * If the entry does not exit, returns size 0. * * @param key, the name of the list * @return {@link CompletionStage} containing a {@link Long} */ public CompletionStage<Long> size(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return cache.getAsync(key).thenApply(b -> b == null ? 0 : (long) b.size()); } /** * Returns the element at the given index. Index is zero-based. * 0 means fist element. Negative index counts index from the tail. For example -1 is the last element. * * @param key, the name of the list * @param index, the position of the element. * @return The existing value. Returns null if the key does not exist or the index is out of bounds. */ public CompletionStage<V> index(K key, long index) { requireNonNull(key, "key can't be null"); return readWriteMap.eval(key, new IndexFunction<>(index)); } /** * Retrieves a sub list of elements, starting from 0. * Negative indexes point positions counting from the tail of the list. * For example 0 is the first element, 1 is the second element, -1 the last element. * * @param key, the name of the list * @param from, the starting offset * @param to, the final offset * @return The subList. Returns null if the key does not exist. */ public CompletionStage<Collection<V>> subList(K key, long from, long to) { requireNonNull(key, "key can't be null"); return readWriteMap.eval(key, new SubListFunction<>(from, to)); } /** * Removes the given count of elements from the head of the list. * * @param key, the name of the list * @param count, the number of elements. Must be positive. * @return {@link CompletionStage} containing a {@link Collection<V>} of values removed, * or null if the key does not exit */ public CompletionStage<Collection<V>> pollFirst(K key, long count) { return poll(key, count, true); } /** * Removes the given count of elements from the tail of the list. * * @param key, the name of the list * @param count, the number of elements. Must be positive. * @return {@link CompletionStage} containing a {@link Collection<V>} of values removed, * or null if the key does not exit */ public CompletionStage<Collection<V>> pollLast(K key, long count) { return poll(key, count, false); } /** * Removes the given count of elements from the tail or the head of the list * @param key, the name of the list * @param count, the number of elements * @param first, true if it's the head, false for the tail * @return {@link CompletionStage} containing a {@link Collection<V>} of values removed, * or null if the key does not exit */ public CompletableFuture<Collection<V>> poll(K key, long count, boolean first) { requireNonNull(key, "key can't be null"); requirePositive(count, "count can't be negative"); return readWriteMap.eval(key, new PollFunction<>(first, count)); } /** * Sets a value in the given index. * 0 means fist element. Negative index counts index from the tail. For example -1 is the last element. * @param key, the name of the list * @param index, the position of the element to be inserted. Can be negative * @param value, the element to be inserted in the index position * @return {@link CompletionStage} with true if the value was set, false if the key does not exist * @throws org.infinispan.commons.CacheException when the index is out of range */ public CompletionStage<Boolean> set(K key, long index, V value) { requireNonNull(key, "key can't be null"); return readWriteMap.eval(key, new SetFunction<>(index, value)); } /** * Retrieves indexes of matching elements inside a list. * Scans the list looking for the elements that match the provided element. * * @param key, the name of the list, can't be null. * @param element, the element to compare, can't be null. * @param count, number of matches. If null, count is 1 by default. Can't be negative. * If count is 0, means all the matches. * @param rank, the "rank" of the first element to return, in case there are multiple matches. * A rank of 1 means the first match, 2 the second match, and so forth. Negative rank iterates * from the tail. If null, rank is 1 by default. Can't be 0. * @param maxlen, compares the provided element only with a given maximum number of list items. * If null, defaults to 0 that means all the elements. Can't be negative. * @return {@link Collection<Long>} containing the zero-based positions in the list counting from the head of the list. * Returns null when the list does not exist or empty list when matches are not found. * */ public CompletionStage<Collection<Long>> indexOf(K key, V element, Long count, Long rank, Long maxlen) { requireNonNull(key, "key can't be null"); requireNonNull(element, ERR_ELEMENT_CAN_T_BE_NULL); long requestedCount = 1; long requestedRank = 1; long requestedMaxLen = 0; if (count != null) { requirePositive(count, "count can't be negative"); requestedCount = count; } if (rank != null) { requireNotZero(rank, "rank can't be zero"); requestedRank = rank; } if (maxlen != null) { requirePositive(maxlen, "maxLen can't be negative"); requestedMaxLen = maxlen; } return readWriteMap.eval(key, new IndexOfFunction<>(element, requestedCount, requestedRank, requestedMaxLen)); } /** * Inserts an element before or after the pivot element. * If the key does not exist, returns 0. * If the pivot does not exist, returns -1. * If the element was inserted, returns the size of the list. * The list is traversed from head to tail, the insertion is done before or after the first element found. * * @param key, the name of the list * @param isBefore, insert before true, after false * @param pivot, the element to compare * @param element, the element to insert * @return, the size of the list after insertion, 0 or -1 */ public CompletionStage<Long> insert(K key, boolean isBefore, V pivot, V element) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(pivot, ERR_PIVOT_CAN_T_BE_NULL); requireNonNull(element, ERR_ELEMENT_CAN_T_BE_NULL); return readWriteMap.eval(key, new InsertFunction<>(isBefore, pivot, element)); } /** * Removes from the list the provided element. The number of copies to be removed is * provided by the count parameter. When count is 0, all the elements that match the * provided element will be removed. If count is negative, the iteration will be done * from the tail of the list instead of the head. * count = 0, removes all, iterates over the whole list * count = 1, removes one match, starts iteration from the head * count = -1, removed one match, starts iteration from the tail * * @param key, the name of the list * @param count, number of elements to remove * @param element, the element to remove * @return how many elements have actually been removed, 0 if the list does not exist */ public CompletionStage<Long> remove(K key, long count, V element) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(element, ERR_ELEMENT_CAN_T_BE_NULL); return readWriteMap.eval(key, new RemoveCountFunction<>(count, element)); } /** * Trims the list removing the elements with the provided indexes 'from' and 'to'. * Negative indexes point positions counting from the tail of the list. * For example 0 is the first element, 1 is the second element, -1 the last element. * Iteration is done from head to tail. * * @param key, the name of the list * @param from, the starting offset * @param to, the final offset * @return {@link CompletionStage<Boolean>} true when the list exist and the trim has been done. */ public CompletionStage<Boolean> trim(K key, long from, long to) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return readWriteMap.eval(key, new TrimFunction<>(from, to)); } /** * Rotates an element in the list from head to tail or tail to head, depending on the rotateRight parameter. * @param key, the name of the list * @param rotateRight, true to rotate an element from the left to the right (head -> tail) * @return the rotated element value, null if the list does not exist */ public CompletionStage<V> rotate(K key, boolean rotateRight) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return readWriteMap.eval(key, new RotateFunction<>(rotateRight)); } private static void requirePositive(long number, String message) { if (number < 0) { throw new IllegalArgumentException(message); } } private static void requireNotZero(long number, String message) { if (number == 0) { throw new IllegalArgumentException(message); } } }
13,733
41.258462
122
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/ListBucket.java
package org.infinispan.multimap.impl; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.commons.util.Util; import org.infinispan.marshall.protostream.impl.MarshallableUserObject; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * Bucket used to store ListMultimap values. * * @author Katia Aresti * @since 15.0 */ @ProtoTypeId(ProtoStreamTypeIds.MULTIMAP_LIST_BUCKET) public class ListBucket<V> { final Deque<V> values; public ListBucket() { this.values = new ArrayDeque<>(0); } public ListBucket(V value) { Deque<V> deque = new ArrayDeque<>(1); deque.add(value); this.values = deque; } private ListBucket(Deque<V> values) { this.values = values; } public static <V> ListBucket<V> create(V value) { return new ListBucket<>(value); } @ProtoFactory ListBucket(Collection<MarshallableUserObject<V>> wrappedValues) { this((Deque<V>) wrappedValues.stream().map(MarshallableUserObject::get) .collect(Collectors.toCollection(ArrayDeque::new))); } @ProtoField(number = 1, collectionImplementation = ArrayList.class) Collection<MarshallableUserObject<V>> getWrappedValues() { return this.values.stream().map(MarshallableUserObject::new).collect(Collectors.toCollection(ArrayDeque::new)); } public boolean contains(V value) { for (V v : values) { if (Objects.deepEquals(v, value)) { return Boolean.TRUE; } } return Boolean.FALSE; } public boolean isEmpty() { return values.isEmpty(); } public int size() { return values.size(); } /** * @return a defensive copy of the {@link #values} collection. */ public Deque<V> toDeque() { return new ArrayDeque<>(values); } @Override public String toString() { return "ListBucket{values=" + Util.toStr(values) + '}'; } public ListBucket<V> offer(V value, boolean first) { if (first) { values.offerFirst(value); } else { values.offerLast(value); } return new ListBucket<>(values); } public ListBucket<V> set(long index, V value) { if ((index >= 0 && (values.size()-1 < index)) || (index < 0 && (values.size() + index < 0))) { return null; } // set head if (index == 0) { values.pollFirst(); values.offerFirst(value); return new ListBucket<>(values); } // set tail if (index == -1 || index == values.size() -1) { values.pollLast(); values.offerLast(value); return new ListBucket<>(values); } ArrayDeque<V> newBucket = new ArrayDeque<>(values.size()); if (index > 0) { Iterator<V> ite = values.iterator(); int currentIndex = 0; while(ite.hasNext()) { V element = ite.next(); if (index == currentIndex) { newBucket.offerLast(value); } else { newBucket.offerLast(element); } currentIndex++; } } if (index < -1) { Iterator<V> ite = values.descendingIterator(); int currentIndex = -1; while(ite.hasNext()) { V element = ite.next(); if (index == currentIndex) { newBucket.offerFirst(value); } else { newBucket.offerFirst(element); } currentIndex--; } } return new ListBucket<>(newBucket); } public Collection<V> sublist(long from, long to) { // from and to are + but from is bigger // example: from 2 > to 1 -> empty result // from and to are - and to is smaller // example: from -1 > to -2 -> empty result if ((from > 0 && to > 0 && from > to) || (from < 0 && to < 0 && from > to)) { return Collections.emptyList(); } // index request if (from == to) { V element = index(from); if (element != null) { return Collections.singletonList(element); } return Collections.emptyList(); } List<V> result = new ArrayList<>(); long fromIte = from < 0 ? values.size() + from : from; long toIte = to < 0 ? values.size() + to : to; Iterator<V> ite = values.iterator(); int offset = 0; while (ite.hasNext()) { V element = ite.next(); if (offset < fromIte){ offset++; continue; } if (offset > toIte){ break; } result.add(element); offset++; } return result; } public void trim(long from, long to) { // from and to are + but from is bigger // example: from 2 > to 1 -> empty // from and to are - and to is smaller // example: from -1 > to -2 -> empty if ((from > 0 && to > 0 && from > to) || (from < 0 && to < 0 && from > to)) { values.clear(); return; } // index request if (from == to) { V element = index(from); if (element != null) { values.clear(); values.add(element); } return; } long startRemoveCount = from < 0 ? values.size() + from : from; long keepCount = (to < 0 ? values.size() + to : to) - startRemoveCount; Iterator<V> ite = values.iterator(); while(ite.hasNext() && startRemoveCount > 0) { ite.next(); ite.remove(); startRemoveCount--; } // keep elements while(ite.hasNext() && keepCount >= 0) { ite.next(); keepCount--; } // remove remaining elements while(ite.hasNext()) { ite.next(); ite.remove(); } } public Collection<Long> indexOf(V element, long count, long rank, long maxLen) { long matches = count == 0 ? values.size() : count; long rankCount = Math.abs(rank); long comparisons = maxLen == 0 ? values.size() : maxLen; Iterator<V> ite; if (rank > 0) { ite = values.iterator(); } else { ite = values.descendingIterator(); } long pos = 0; List<Long> positions = new ArrayList<>(); while (ite.hasNext() && comparisons > 0 && matches > 0) { V current = ite.next(); if (Objects.deepEquals(element, current)) { if (rankCount == 1) { matches--; if (rank < 0) { positions.add(values.size() - pos - 1); } else { positions.add(pos); } } else { rankCount--; } } comparisons--; pos++; } return positions; } public ListBucket<V> insert(boolean before, V pivot, V element) { Deque<V> newValues = new ArrayDeque<>(values.size() +1); Iterator<V> iterator = values.iterator(); boolean found = false; while (iterator.hasNext()) { V next = iterator.next(); if (found) { newValues.offerLast(next); } else { if (Objects.deepEquals(pivot, next)) { found = true; if (before) { newValues.offerLast(element); newValues.offerLast(next); } else { newValues.offerLast(next); newValues.offerLast(element); } } else { newValues.offerLast(next); } } } if (!found) { return null; } return new ListBucket<>(newValues); } public long remove(long count, V element) { Iterator<V> ite; if (count < 0) { ite = values.descendingIterator(); } else { ite = values.iterator(); } long maxRemovalsCount = count == 0 ? values.size(): Math.abs(count); long removedElements = 0; while(ite.hasNext()) { V next = ite.next(); if (Objects.deepEquals(next, element)) { ite.remove(); removedElements++; if (removedElements == maxRemovalsCount) { break; } } } return removedElements; } public V rotate(boolean rotateRight) { V element; if (rotateRight) { // from head to tail element = values.pollFirst(); values.offerLast(element); } else { // from tail to head element = values.pollLast(); values.offerFirst(element); } return element; } public class ListBucketResult { private final Collection<V> result; private final ListBucket<V> bucketValue; public ListBucketResult(Collection<V> result, ListBucket<V> bucketValue) { this.result = result; this.bucketValue = bucketValue; } public ListBucket<V> bucketValue() { return bucketValue; } public Collection<V> opResult() { return result; } } public ListBucketResult poll(boolean first, long count) { List<V> polledValues = new ArrayList<>(); if (count >= values.size()) { if (first) { polledValues.addAll(values); } else { Iterator<V> ite = values.descendingIterator(); while(ite.hasNext()) { polledValues.add(ite.next()); } } return new ListBucketResult(polledValues, new ListBucket<>()); } for (int i = 0 ; i < count; i++) { if (first) { polledValues.add(values.pollFirst()); } else { polledValues.add(values.pollLast()); } } return new ListBucketResult(polledValues, new ListBucket<>(values)); } public V index(long index) { if (index == 0) { return values.element(); } if (index == values.size() - 1 || index == -1) { return values.getLast(); } V result = null; if (index > 0) { if (index >= values.size()) { return null; } Iterator<V> iterator = values.iterator(); int currentIndex = 0; while (currentIndex++ <= index) { result = iterator.next(); } } else { long currentIndex = Math.abs(index); if (currentIndex > values.size()) { return null; } Iterator<V> iterator = values.descendingIterator(); while (currentIndex-- > 0) { result = iterator.next(); } } return result; } }
11,041
25.931707
117
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/EmbeddedSetCache.java
package org.infinispan.multimap.impl; import static java.util.Objects.requireNonNull; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.functional.FunctionalMap; import org.infinispan.functional.impl.FunctionalMapImpl; import org.infinispan.functional.impl.ReadWriteMapImpl; import org.infinispan.multimap.impl.function.set.SAddFunction; import org.infinispan.multimap.impl.function.set.SGetFunction; import org.infinispan.multimap.impl.function.set.SSetFunction; /** * SetCache with Set methods implementation * * @author Vittorio Rigamonti * @since 15.0 */ public class EmbeddedSetCache<K, V> { public static final String ERR_KEY_CAN_T_BE_NULL = "key can't be null"; public static final String ERR_VALUE_CAN_T_BE_NULL = "value can't be null"; protected final FunctionalMap.ReadWriteMap<K, SetBucket<V>> readWriteMap; protected final AdvancedCache<K, SetBucket<V>> cache; protected final InternalEntryFactory entryFactory; public EmbeddedSetCache(Cache<K, SetBucket<V>> cache) { this.cache = cache.getAdvancedCache(); FunctionalMapImpl<K, SetBucket<V>> functionalMap = FunctionalMapImpl.create(this.cache); this.readWriteMap = ReadWriteMapImpl.create(functionalMap); this.entryFactory = this.cache.getComponentRegistry().getInternalEntryFactory().running(); } /** * Get the entry by key and return it as a set * * @param key, the name of the set * @return the set with values if such exist, or null if the key is not present */ public CompletionStage<Set<V>> get(K key) { return readWriteMap.eval(key, new SGetFunction<K, V>()).thenApply(v -> v.values()); } /** * Add the specified element to the set, creates the set in case * * @param key, the name of the set * @param value, the element to be inserted * @return {@link CompletionStage} containing a {@link Void} */ public CompletionStage<Boolean> add(K key, V value) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(value, ERR_VALUE_CAN_T_BE_NULL); return readWriteMap.eval(key, new SAddFunction<>(value)); } /** * Get all the entries specified in the keys collection * * @param keys, collection of keys to be get * @return {@link CompletionStage} containing a {@link } */ public CompletableFuture<Map<K, SetBucket<V>>> getAll(Set<K> keys) { requireNonNull(keys, ERR_KEY_CAN_T_BE_NULL); return cache.getAllAsync(keys); } /** * Returns the number of elements in the set. * If the entry does not exit, returns size 0. * * @param key, the name of the list * @return {@link CompletionStage} containing a {@link Long} */ public CompletionStage<Long> size(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return cache.getAsync(key).thenApply(b -> b == null ? 0 : (long) b.size()); } /** * Create the set with given values * * @param key, the name of the set * @param values, the elements to be inserted * @return {@link CompletionStage} containing the number of elements */ public CompletionStage<Long> set(K key, Collection<V> values) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(values, ERR_VALUE_CAN_T_BE_NULL); return readWriteMap.eval(key, new SSetFunction<>(values)); } }
3,610
35.11
96
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/EmbeddedMultimapSortedSetCache.java
package org.infinispan.multimap.impl; import org.infinispan.AdvancedCache; import org.infinispan.Cache; import org.infinispan.container.entries.CacheEntry; import org.infinispan.container.impl.InternalEntryFactory; import org.infinispan.functional.FunctionalMap; import org.infinispan.functional.impl.FunctionalMapImpl; import org.infinispan.functional.impl.ReadWriteMapImpl; import org.infinispan.multimap.impl.function.sortedset.AddManyFunction; import org.infinispan.multimap.impl.function.sortedset.CountFunction; import org.infinispan.multimap.impl.function.sortedset.PopFunction; import org.infinispan.multimap.impl.function.sortedset.ScoreFunction; import java.util.Collection; import java.util.Set; import java.util.SortedSet; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import static java.util.Objects.requireNonNull; /** * Multimap with Sorted Map Implementation methods * * @author Katia Aresti * @since 15.0 */ public class EmbeddedMultimapSortedSetCache<K, V> { public static final String ERR_KEY_CAN_T_BE_NULL = "key can't be null"; public static final String ERR_MEMBER_CAN_T_BE_NULL = "member can't be null"; public static final String ERR_SCORES_CAN_T_BE_NULL = "scores can't be null"; public static final String ERR_VALUES_CAN_T_BE_NULL = "values can't be null"; public static final String ERR_SCORES_VALUES_MUST_HAVE_SAME_SIZE = "scores and values must have the same size"; protected final FunctionalMap.ReadWriteMap<K, SortedSetBucket<V>> readWriteMap; protected final AdvancedCache<K, SortedSetBucket<V>> cache; protected final InternalEntryFactory entryFactory; public EmbeddedMultimapSortedSetCache(Cache<K, SortedSetBucket<V>> cache) { this.cache = cache.getAdvancedCache(); FunctionalMapImpl<K, SortedSetBucket<V>> functionalMap = FunctionalMapImpl.create(this.cache); this.readWriteMap = ReadWriteMapImpl.create(functionalMap); this.entryFactory = this.cache.getComponentRegistry().getInternalEntryFactory().running(); } /** * Adds and/or updates, depending on the provided options, the value and the associated score. * * @param key, the name of the sorted set * @param scores, the score for each of the elements in the values * @param values, the values to be added * @param args to provide different options: * addOnly -> adds new elements only, ignore existing ones. * updateOnly -> updates existing elements only, ignore new elements. * updateLessScoresOnly -> creates new elements and updates existing elements if the score is less than current score. * updateGreaterScoresOnly -> creates new elements and updates existing elements if the score is greater than current score. * returnChangedCount -> by default returns number of new added elements. If true, counts created and updated elements. * @return {@link CompletionStage} containing the number of entries added and/or updated depending on the provided arguments */ public CompletionStage<Long> addMany(K key, double[] scores, V[] values, SortedSetAddArgs args) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(scores, ERR_SCORES_CAN_T_BE_NULL); requireNonNull(values, ERR_VALUES_CAN_T_BE_NULL); requireSameLength(scores, values); if (scores.length == 0) { return CompletableFuture.completedFuture(0L); } return readWriteMap.eval(key, new AddManyFunction<>(scores, values, args.addOnly, args.updateOnly, args.updateLessScoresOnly, args.updateGreaterScoresOnly, args.returnChangedCount)); } /** * Retieves the size of the sorted set value * @param key, the name of the sorted set * @return, the size */ public CompletionStage<Long> size(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return cache.getAsync(key).thenApply(b -> b == null ? 0 : b.size()); } /** * Get the value as a collection * * @param key, the name of the list * @return the collection with values if such exist, or an empty collection if the key is not present */ public CompletionStage<Collection<SortedSetBucket.ScoredValue<V>>> get(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return getEntry(key).thenApply(entry -> { if (entry != null) { return entry.getValue(); } return Set.of(); }); } private CompletionStage<CacheEntry<K, Collection<SortedSetBucket.ScoredValue<V>>>> getEntry(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return cache.getAdvancedCache().getCacheEntryAsync(key) .thenApply(entry -> { if (entry == null) return null; return entryFactory.create(entry.getKey(),(entry.getValue().toTreeSet()) , entry.getMetadata()); }); } /** * Returns the sorted set value if such exists. * * @param key, the name of the sorted set * @return the value of the Sorted Set */ public CompletionStage<SortedSet<SortedSetBucket.ScoredValue<V>>> getValue(K key) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return cache.getAsync(key).thenApply(b -> { if (b != null) { return b.getScoredEntries(); } return null; }); } /** * Counts the number of elements between the given min and max scores. * * @param key, the name of the sorted set * @param min, the min score * @param max, the max score * @param includeMin, include elements with the min score in the count * @param includeMax, include elements with the max score in the count * @return the number of elements in between min and max scores */ public CompletionStage<Long> count(K key, double min, boolean includeMin, double max, boolean includeMax) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return readWriteMap.eval(key, new CountFunction<>(min, includeMin, max, includeMax)); } /** * Pops the number of elements provided by the count parameter. * Elements are pop from the head or the tail, depending on the min parameter. * @param key, the sorted set name * @param min, if true pops lower scores, if false pops higher scores * @param count, number of values * @return, empty if the sorted set does not exist */ public CompletionStage<Collection<SortedSetBucket.ScoredValue<V>>> pop(K key, boolean min, long count) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); return readWriteMap.eval(key, new PopFunction<>(min, count)); } /** * Returns the score of member in the sorted. * * @param key, the name of the sorted set * @param member, the score value to be retrieved * @return {@link CompletionStage} with the score, or null if the score of the key does not exist. */ public CompletionStage<Double> score(K key, V member) { requireNonNull(key, ERR_KEY_CAN_T_BE_NULL); requireNonNull(member, ERR_MEMBER_CAN_T_BE_NULL); return readWriteMap.eval(key, new ScoreFunction<>(member)); } private void requireSameLength(double[] scores, V[] values) { if (scores.length != values.length) { throw new IllegalArgumentException(ERR_SCORES_VALUES_MUST_HAVE_SAME_SIZE); } } }
7,398
41.28
133
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/EmbeddedMultimapCacheManager.java
package org.infinispan.multimap.impl; import java.util.Collection; import org.infinispan.Cache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.multimap.api.embedded.MultimapCache; import org.infinispan.multimap.api.embedded.MultimapCacheManager; /** * Embedded implementation of {@link MultimapCacheManager} * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public class EmbeddedMultimapCacheManager<K, V> implements MultimapCacheManager<K, V> { private EmbeddedCacheManager cacheManager; public EmbeddedMultimapCacheManager(EmbeddedCacheManager embeddedMultimapCacheManager) { this.cacheManager = embeddedMultimapCacheManager; } @Override public Configuration defineConfiguration(String name, Configuration configuration) { return cacheManager.defineConfiguration(name, configuration); } @Override public MultimapCache<K, V> get(String name, boolean supportsDuplicates) { Cache<K, Collection<V>> cache = cacheManager.getCache(name, true); EmbeddedMultimapCache multimapCache = new EmbeddedMultimapCache(cache, supportsDuplicates); return multimapCache; } /** * Provides an api to manipulate key/values with lists. * * @param cacheName, name of the cache * @return EmbeddedMultimapListCache */ public EmbeddedMultimapListCache<K, V> getMultimapList(String cacheName) { Cache<K, ListBucket<V>> cache = cacheManager.getCache(cacheName); if (cache == null) { throw new IllegalStateException("Cache must exist: " + cacheName); } return new EmbeddedMultimapListCache<>(cache); } /** * Provides an api to manipulate key/values with sorted sets. * * @param cacheName, name of the cache * @return EmbeddedMultimapSortedSetCache */ public EmbeddedMultimapSortedSetCache<K, V> getMultimapSortedSet(String cacheName) { Cache<K, SortedSetBucket<V>> cache = cacheManager.getCache(cacheName); if (cache == null) { throw new IllegalStateException("Cache must exist: " + cacheName); } return new EmbeddedMultimapSortedSetCache<>(cache); } public <HK, HV> EmbeddedMultimapPairCache<K, HK, HV> getMultimapPair(String cacheName) { Cache<K, HashMapBucket<HK, HV>> cache = cacheManager.getCache(cacheName); if (cache == null) { throw new IllegalStateException("Cache must exist: " + cacheName); } return new EmbeddedMultimapPairCache<>(cache); } }
2,557
34.041096
97
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/SortedSetAddArgs.java
package org.infinispan.multimap.impl; /** * Utility class to hold multiple options for sorted sets * @since 15.0 */ public class SortedSetAddArgs { public static final String ADD_AND_UPDATE_ONLY_INCOMPATIBLE_ERROR = "addOnly and updateOnly can't both be true"; public static final String ADD_AND_UPDATE_OPTIONS_INCOMPATIBLE_ERROR = "addOnly, updateGreaterScoresOnly and updateLessScoresOnly can't all be true"; public boolean addOnly; public boolean updateOnly; public boolean updateLessScoresOnly; public boolean updateGreaterScoresOnly; public boolean returnChangedCount; private SortedSetAddArgs(SortedSetAddArgs.Builder builder) { this.addOnly = builder.addOnly; this.updateOnly = builder.updateOnly; this.updateLessScoresOnly = builder.updateLessScoresOnly; this.updateGreaterScoresOnly = builder.updateGreaterScoresOnly; this.returnChangedCount = builder.returnChangedCount; } public static Builder create() { return new Builder(); } public static class Builder { private boolean addOnly; private boolean updateOnly; private boolean updateLessScoresOnly; private boolean updateGreaterScoresOnly; private boolean returnChangedCount; private Builder() { } public SortedSetAddArgs.Builder addOnly() { this.addOnly = true; return this; } public SortedSetAddArgs.Builder updateOnly() { this.updateOnly = true; return this; } public SortedSetAddArgs.Builder updateLessScoresOnly() { this.updateLessScoresOnly = true; return this; } public SortedSetAddArgs.Builder updateGreaterScoresOnly() { this.updateGreaterScoresOnly = true; return this; } public SortedSetAddArgs.Builder returnChangedCount() { this.returnChangedCount = true; return this; } public SortedSetAddArgs build(){ // validate if (updateOnly && addOnly) { throw new IllegalStateException(ADD_AND_UPDATE_ONLY_INCOMPATIBLE_ERROR); } if ((addOnly && updateGreaterScoresOnly) || (addOnly && updateLessScoresOnly) || (updateGreaterScoresOnly && updateLessScoresOnly) ) { throw new IllegalStateException(ADD_AND_UPDATE_OPTIONS_INCOMPATIBLE_ERROR); } return new SortedSetAddArgs(this); } } }
2,459
30.538462
152
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/Bucket.java
package org.infinispan.multimap.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.commons.util.Util; import org.infinispan.marshall.protostream.impl.MarshallableUserObject; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; /** * Bucket used to store Multimap values, required as HashSet cannot be directly marshalled via ProtoStream. * * @author Ryan Emerson * @since 10.0 */ @ProtoTypeId(ProtoStreamTypeIds.MULTIMAP_BUCKET) public class Bucket<V> { final Collection<V> values; public Bucket() { this.values = Collections.emptyList(); } public Bucket(V value) { this.values = Collections.singletonList(value); } private Bucket(List<V> values) { this.values = values; } @ProtoFactory Bucket(Collection<MarshallableUserObject<V>> wrappedValues) { this(wrappedValues.stream().map(MarshallableUserObject::get).collect(Collectors.toList())); } @ProtoField(number = 1, collectionImplementation = ArrayList.class) Collection<MarshallableUserObject<V>> getWrappedValues() { return this.values.stream().map(MarshallableUserObject::new).collect(Collectors.toSet()); } public boolean contains(V value) { for (V v : values) { if (Objects.deepEquals(v, value)) { return Boolean.TRUE; } } return Boolean.FALSE; } /** * @return {@code null} if the element exists and {@parameter supportsDuplicates is false} in this {@link Bucket}, otherwise, it returns a new {@link Bucket} * instance. */ public Bucket<V> add(V value, boolean supportsDuplicates) { List<V> newBucket = new ArrayList<>(values.size() + 1); for (V v : values) { if (!supportsDuplicates && Objects.deepEquals(v, value)) { return null; } newBucket.add(v); } newBucket.add(value); return new Bucket<>(newBucket); } public Bucket<V> remove(V value, boolean supportsDuplicates) { List<V> newBucket = new ArrayList<>(values.size()); boolean removed = false; Iterator<V> it = values.iterator(); if (supportsDuplicates) { while (it.hasNext()){ V v = it.next(); if (Objects.deepEquals(v, value)) { removed = true; } else { newBucket.add(v); } } }else { while (it.hasNext()) { V v = it.next(); if (Objects.deepEquals(v, value)) { removed = true; break; } newBucket.add(v); } //add remaining values while (it.hasNext()) { newBucket.add(it.next()); } } return removed ? new Bucket<>(newBucket) : null; } public Bucket<V> removeIf(Predicate<? super V> p) { List<V> newBucket = new ArrayList<>(values.size()); for (V v : values) { if (!p.test(v)) { newBucket.add(v); } } return newBucket.size() == values.size() ? null : new Bucket<>(newBucket); } public boolean isEmpty() { return values.isEmpty(); } public int size() { return values.size(); } /** * @return a defensive copy of the {@link #values} collection. */ public Set<V> toSet() { return new HashSet<>(values); } /** * @return a defensive copy of the {@link #values} collection if the cache supports duplicates. */ public List<V> toList() { return new ArrayList<>(values); } @Override public String toString() { return "Bucket{values=" + Util.toStr(values) + '}'; } }
4,070
26.883562
160
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/SortedSetBucket.java
package org.infinispan.multimap.impl; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.multimap.impl.internal.MultimapObjectWrapper; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.SortedSet; import java.util.TreeSet; /** * Bucket used to store Sorted Set data type. * * @author Katia Aresti * @since 15.0 */ @ProtoTypeId(ProtoStreamTypeIds.MULTIMAP_SORTED_SET_BUCKET) public class SortedSetBucket<V> { private final static Object NO_VALUE = new Object(); private final TreeSet<ScoredValue<V>> scoredEntries; private final Map<MultimapObjectWrapper<V>, Double> entries; private final Comparator<ScoredValue<V>> scoreComparator = Comparator.naturalOrder(); @ProtoFactory SortedSetBucket(Collection<ScoredValue<V>> wrappedValues) { scoredEntries = new TreeSet<>(scoreComparator); scoredEntries.addAll(wrappedValues); entries = new HashMap<>(); wrappedValues.forEach(e -> entries.put(e.wrappedValue(), e.score())); } @ProtoField(number = 1, collectionImplementation = ArrayList.class) Collection<ScoredValue<V>> getWrappedValues() { return new ArrayList<>(scoredEntries); } /** * Returns a copy of the entries; * @return entries copy */ public SortedSet<ScoredValue<V>> getScoredEntries() { return new TreeSet<>(scoredEntries); } public SortedSetBucket() { this.scoredEntries = new TreeSet<>(scoreComparator); this.entries = new HashMap<>(); } public Collection<ScoredValue<V>> pop(boolean min, long count) { List<ScoredValue<V>> popValuesList = new ArrayList<>(); for (long i = 0; i < count && !scoredEntries.isEmpty(); i++) { ScoredValue<V> popedScoredValue = min ? scoredEntries.pollFirst() : scoredEntries.pollLast(); entries.remove(popedScoredValue.wrappedValue()); popValuesList.add(popedScoredValue); } return popValuesList; } public Double score(V member) { return entries.get(new MultimapObjectWrapper<>(member)); } public static class AddResult { public long created = 0; public long updated = 0; } public AddResult addMany(double[] scores, V[] values, boolean addOnly, boolean updateOnly, boolean updateLessScoresOnly, boolean updateGreaterScoresOnly) { AddResult addResult = new AddResult(); int startSize = entries.size(); for (int i = 0 ; i < values.length; i++) { Double newScore = scores[i]; MultimapObjectWrapper<V> value = new MultimapObjectWrapper<>(values[i]); if (addOnly) { Double existingScore = entries.get(value); if (existingScore == null){ addScoredValue(newScore, value); } } else if (updateOnly) { Double existingScore = entries.get(value); if (existingScore != null && !existingScore.equals(newScore)) { updateScoredValue(addResult, newScore, value, existingScore); } } else if (updateGreaterScoresOnly) { // Adds or updates if the new score is greater than the current score Double existingScore = entries.get(value); if (existingScore == null) { addScoredValue(newScore, value); } else if (newScore > existingScore) { // Update updateScoredValue(addResult, newScore, value, existingScore); } } else if (updateLessScoresOnly) { // Adds or updates if the new score is less than the current score Double existingScore = entries.get(value); if (existingScore == null) { addScoredValue(newScore, value); } else if (newScore < existingScore) { updateScoredValue(addResult, newScore, value, existingScore); } } else { Double existingScore = entries.get(value); if (existingScore == null) { addScoredValue(newScore, value); } else if (!newScore.equals(existingScore)) { // entry exists, check score updateScoredValue(addResult, newScore, value, existingScore); } } } addResult.created = entries.size() - startSize; return addResult; } private void updateScoredValue(AddResult addResult, Double newScore, MultimapObjectWrapper<V> value, Double existingScore) { ScoredValue<V> oldScoredValue = new ScoredValue<>(existingScore, value); ScoredValue<V> newScoredValue = new ScoredValue<>(newScore, value); scoredEntries.remove(oldScoredValue); scoredEntries.add(newScoredValue); entries.put(value, newScore); addResult.updated++; } private void addScoredValue(Double newScore, MultimapObjectWrapper<V> value) { scoredEntries.add(new ScoredValue<>(newScore, value)); entries.put(value, newScore); } @SuppressWarnings({ "unchecked", "rawtypes" }) public SortedSet<ScoredValue<V>> subsetByScores(double min, boolean includeMin, double max, boolean includeMax) { ScoredValue<V> minSv; ScoredValue<V> maxSv; boolean unboundedMin = false; boolean unboundedMax = false; if (min == max && (!includeMin || !includeMax)) { return Collections.emptySortedSet(); } if (min == Double.MIN_VALUE) { minSv = scoredEntries.first(); unboundedMin = true; } else { if (includeMin) { minSv = scoredEntries.lower(new ScoredValue(min, NO_VALUE)); } else { minSv = scoredEntries.higher(new ScoredValue(min, NO_VALUE)); } if (minSv == null) { minSv = scoredEntries.first(); } } if (max == Double.MAX_VALUE) { maxSv = scoredEntries.last(); unboundedMax = true; } else { if (includeMax) { maxSv = scoredEntries.higher(new ScoredValue(max, NO_VALUE)); } else { maxSv = scoredEntries.lower(new ScoredValue(max, NO_VALUE)); } if (maxSv == null) { maxSv = scoredEntries.last(); } } if (minSv.score() > maxSv.score()) { return Collections.emptySortedSet(); } return scoredEntries .subSet(minSv, unboundedMin || (minSv.score() > min || (includeMin && minSv.score() == min)), maxSv, unboundedMax || (maxSv.score() < max || (includeMax && maxSv.score() == max))); } public Collection<ScoredValue<V>> toTreeSet() { return new TreeSet<>(scoredEntries); } public long size() { return scoredEntries.size(); } @ProtoTypeId(ProtoStreamTypeIds.MULTIMAP_SORTED_SET_SCORED_ENTRY) public static class ScoredValue<V> implements Comparable<ScoredValue<V>> { private final double score; private final MultimapObjectWrapper<V> value; private ScoredValue(double score, V value) { this.score = score; this.value = new MultimapObjectWrapper<>(value); } public static <V> ScoredValue<V> of(double score, V value) { return new ScoredValue<>(score, value); } @ProtoFactory ScoredValue(double score, MultimapObjectWrapper<V> wrappedValue) { this.score = score; this.value = wrappedValue; } @ProtoField(value = 1, required = true) public double score() { return score; } @ProtoField(2) public MultimapObjectWrapper<V> wrappedValue() { return value; } public V getValue() { return value.get(); } @Override public int hashCode() { return Objects.hash(value, score); } @Override public boolean equals(Object entry) { if (this == entry) return true; if (entry == null || getClass() != entry.getClass()) return false; @SuppressWarnings("unchecked") ScoredValue<V> other = (ScoredValue<V>) entry; return this.value.equals(other.value) && this.score == other.score; } @Override public String toString() { return "ScoredValue{" + "score=" + score + ", value=" + value.toString() + '}'; } @Override public int compareTo(ScoredValue<V> other) { if (this == other) return 0; int compare = Double.compare(this.score, other.score); if (compare == 0) { if (other.getValue() == NO_VALUE || this.getValue() == NO_VALUE) { return 0; } return value.compareTo(other.wrappedValue()); } return compare; } } }
9,149
32.394161
127
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/MultimapModuleLifecycle.java
package org.infinispan.multimap.impl; import java.util.Map; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.lifecycle.ModuleLifecycle; import org.infinispan.marshall.protostream.impl.SerializationContextRegistry; import org.infinispan.multimap.impl.function.hmap.HashMapKeySetFunction; import org.infinispan.multimap.impl.function.hmap.HashMapPutFunction; import org.infinispan.multimap.impl.function.hmap.HashMapRemoveFunction; import org.infinispan.multimap.impl.function.hmap.HashMapReplaceFunction; import org.infinispan.multimap.impl.function.hmap.HashMapValuesFunction; import org.infinispan.multimap.impl.function.list.IndexFunction; import org.infinispan.multimap.impl.function.list.IndexOfFunction; import org.infinispan.multimap.impl.function.list.InsertFunction; import org.infinispan.multimap.impl.function.list.OfferFunction; import org.infinispan.multimap.impl.function.list.PollFunction; import org.infinispan.multimap.impl.function.list.RemoveCountFunction; import org.infinispan.multimap.impl.function.list.RotateFunction; import org.infinispan.multimap.impl.function.list.SetFunction; import org.infinispan.multimap.impl.function.list.SubListFunction; import org.infinispan.multimap.impl.function.list.TrimFunction; import org.infinispan.multimap.impl.function.multimap.ContainsFunction; import org.infinispan.multimap.impl.function.multimap.GetFunction; import org.infinispan.multimap.impl.function.multimap.PutFunction; import org.infinispan.multimap.impl.function.multimap.RemoveFunction; import org.infinispan.multimap.impl.function.set.SAddFunction; import org.infinispan.multimap.impl.function.set.SGetFunction; import org.infinispan.multimap.impl.function.set.SSetFunction; import org.infinispan.multimap.impl.function.sortedset.AddManyFunction; import org.infinispan.multimap.impl.function.sortedset.CountFunction; import org.infinispan.multimap.impl.function.sortedset.PopFunction; import org.infinispan.multimap.impl.function.sortedset.ScoreFunction; /** * MultimapModuleLifecycle is necessary for the Multimap Cache module. * Registers advanced externalizers. * * @author Katia Aresti - karesti@redhat.com * @since 9.2 */ @InfinispanModule(name = "multimap", requiredModules = "core") public class MultimapModuleLifecycle implements ModuleLifecycle { @Override public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) { SerializationContextRegistry ctxRegistry = gcr.getComponent(SerializationContextRegistry.class); ctxRegistry.addContextInitializer(SerializationContextRegistry.MarshallerType.PERSISTENCE, new PersistenceContextInitializerImpl()); ctxRegistry.addContextInitializer(SerializationContextRegistry.MarshallerType.GLOBAL, new PersistenceContextInitializerImpl()); final Map<Integer, AdvancedExternalizer<?>> externalizerMap = globalConfiguration.serialization() .advancedExternalizers(); addMultimapExternalizers(externalizerMap); addListsExternalizers(externalizerMap); addSetExternalizers(externalizerMap); addHashMapExternalizers(externalizerMap); addSortedSetExternalizers(externalizerMap); } /** * Multimap functions * * @param externalizerMap */ private static void addMultimapExternalizers(Map<Integer, AdvancedExternalizer<?>> externalizerMap) { addAdvancedExternalizer(externalizerMap, PutFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, RemoveFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, ContainsFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, GetFunction.EXTERNALIZER); } /** * Lists functions * * @param externalizerMap */ private static void addListsExternalizers(Map<Integer, AdvancedExternalizer<?>> externalizerMap) { addAdvancedExternalizer(externalizerMap, OfferFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, IndexFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, PollFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, SubListFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, SetFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, IndexOfFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, InsertFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, RemoveCountFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, TrimFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, RotateFunction.EXTERNALIZER); } /** * HashMap functions * * @param externalizerMap */ private static void addHashMapExternalizers(Map<Integer, AdvancedExternalizer<?>> externalizerMap) { addAdvancedExternalizer(externalizerMap, HashMapPutFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, HashMapKeySetFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, HashMapValuesFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, HashMapRemoveFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, HashMapReplaceFunction.EXTERNALIZER); } /** * Set functions * * @param externalizerMap */ private static void addSetExternalizers(Map<Integer, AdvancedExternalizer<?>> externalizerMap) { addAdvancedExternalizer(externalizerMap, SAddFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, SGetFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, SSetFunction.EXTERNALIZER); } /** * Sorted Set functions * * @param externalizerMap */ private static void addSortedSetExternalizers(Map<Integer, AdvancedExternalizer<?>> externalizerMap) { addAdvancedExternalizer(externalizerMap, AddManyFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, CountFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, PopFunction.EXTERNALIZER); addAdvancedExternalizer(externalizerMap, ScoreFunction.EXTERNALIZER); } private static void addAdvancedExternalizer(Map<Integer, AdvancedExternalizer<?>> map, AdvancedExternalizer<?> ext) { map.put(ext.getId(), ext); } }
6,482
47.380597
138
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/HashMapBucket.java
package org.infinispan.multimap.impl; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.marshall.protostream.impl.MarshallableUserObject; import org.infinispan.multimap.impl.internal.MultimapObjectWrapper; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; @ProtoTypeId(ProtoStreamTypeIds.MULTIMAP_HASH_MAP_BUCKET) public class HashMapBucket<K, V> { final Map<MultimapObjectWrapper<K>, V> values; private HashMapBucket(Map<K, V> values) { this.values = toStore(values); } @ProtoFactory HashMapBucket(Collection<BucketEntry<K, V>> wrappedValues) { this.values = wrappedValues.stream() .collect(Collectors.toMap(e -> new MultimapObjectWrapper<>(e.getKey()), BucketEntry::getValue)); } public static <K, V> HashMapBucket<K, V> create(Map<K, V> values) { return new HashMapBucket<>(values); } @ProtoField(number = 1, collectionImplementation = ArrayList.class) Collection<BucketEntry<K, V>> getWrappedValues() { return values.entrySet().stream().map(BucketEntry::new).collect(Collectors.toList()); } public int putAll(Map<K, V> map) { int res = 0; for (Map.Entry<K, V> entry : map.entrySet()) { V prev = values.put(new MultimapObjectWrapper<>(entry.getKey()), entry.getValue()); if (prev == null) res++; } return res; } public Map<K, V> getAll(Set<K> keys) { // We can have null vales here, so we need HashMap. Map<K, V> response = new HashMap<>(keys.size()); for (K key : keys) { response.put(key, values.get(new MultimapObjectWrapper<>(key))); } return response; } public Map<K, V> converted() { return fromStore(); } public boolean isEmpty() { return values.isEmpty(); } public int removeAll(Collection<K> keys) { int res = 0; for (K key : keys) { Object prev = values.remove(new MultimapObjectWrapper<>(key)); if (prev != null) res++; } return res; } public V get(K k) { return values.get(new MultimapObjectWrapper<>(k)); } public int size() { return values.size(); } public Collection<V> values() { return new ArrayList<>(values.values()); } public Set<K> keySet() { Set<K> keys = new HashSet<>(values.size()); for (MultimapObjectWrapper<K> key : values.keySet()) { keys.add(key.get()); } return keys; } public boolean containsKey(K key) { return values.containsKey(new MultimapObjectWrapper<>(key)); } /** * We do not use the original replace method here. Our implementation allows to create and delete entries. */ public boolean replace(K key, V expected, V replacement) { MultimapObjectWrapper<K> storeKey = new MultimapObjectWrapper<>(key); V current = values.get(storeKey); if (current == null && expected == null && replacement != null) { values.put(storeKey, replacement); return true; } if (!Objects.equals(current, expected)) return false; if (replacement == null) { values.remove(storeKey); } else { values.put(storeKey, replacement); } return true; } private Map<MultimapObjectWrapper<K>, V> toStore(Map<K, V> raw) { Map<MultimapObjectWrapper<K>, V> converted = new HashMap<>(); for (Map.Entry<K, V> entry : raw.entrySet()) { converted.put(new MultimapObjectWrapper<>(entry.getKey()), entry.getValue()); } return converted; } private Map<K, V> fromStore() { Map<K, V> converted = new HashMap<>(); for (Map.Entry<MultimapObjectWrapper<K>, V> entry : values.entrySet()) { converted.put(entry.getKey().get(), entry.getValue()); } return converted; } @ProtoTypeId(ProtoStreamTypeIds.MULTIMAP_HASH_MAP_BUCKET_ENTRY) static class BucketEntry<K, V> { final K key; final V value; private BucketEntry(K key, V value) { this.key = key; this.value = value; } private BucketEntry(Map.Entry<MultimapObjectWrapper<K>, V> entry) { this(entry.getKey().get(), entry.getValue()); } @ProtoFactory BucketEntry(MarshallableUserObject<K> wrappedKey, MarshallableUserObject<V> wrappedValue) { this(wrappedKey.get(), wrappedValue.get()); } @ProtoField(number = 1) MarshallableUserObject<K> wrappedKey() { return new MarshallableUserObject<>(key); } public K getKey() { return key; } @ProtoField(number = 2) MarshallableUserObject<V> wrappedValue() { return new MarshallableUserObject<>(value); } public V getValue() { return value; } } }
5,130
27.988701
109
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/set/SSetFunction.java
package org.infinispan.multimap.impl.function.set; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.SetBucket; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedSetCache#set} * to operator on Sets. * * @author Vittorio Rigamonti * @see <a href="http://infinispan.org/documentation/">Marshalling of * Functions</a> * @since 15.0 */ public final class SSetFunction<K, V> implements SetBucketBaseFunction<K, V, Long> { public static final AdvancedExternalizer<SSetFunction> EXTERNALIZER = new Externalizer(); private final Collection<V> values; public SSetFunction(Collection<V> values) { this.values = values; } @Override public Long apply(EntryView.ReadWriteEntryView<K, SetBucket<V>> entryView) { var set = new SetBucket<V>(new HashSet<>(values)); entryView.set(set); return (long) set.size(); } private static class Externalizer implements AdvancedExternalizer<SSetFunction> { @Override public Set<Class<? extends SSetFunction>> getTypeClasses() { return Collections.singleton(SSetFunction.class); } @Override public Integer getId() { return ExternalizerIds.SET_SET_FUNCTION; } @Override public void writeObject(ObjectOutput output, SSetFunction object) throws IOException { output.writeInt(object.values.size()); for (var el : object.values) { output.writeObject(el); } } @Override public SSetFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { int size = input.readInt(); Set<Object> values = new HashSet<>(size); for (int i = 0; i < size; i++) { values.add(input.readObject()); } return new SSetFunction<>(values); } } }
2,187
29.388889
100
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/set/SGetFunction.java
package org.infinispan.multimap.impl.function.set; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.SetBucket; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedSetCache#get} * to get a Set value with the given key. * * @author Vittorio Rigamonti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class SGetFunction<K, V> implements SetBucketBaseFunction<K, V, SetBucket<V>> { public static final AdvancedExternalizer<SGetFunction> EXTERNALIZER = new Externalizer(); @Override public SetBucket<V> apply(EntryView.ReadWriteEntryView<K, SetBucket<V>> entryView) { Optional<SetBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { return existing.get(); } return new SetBucket<V>(); } private static class Externalizer implements AdvancedExternalizer<SGetFunction> { @Override public Set<Class<? extends SGetFunction>> getTypeClasses() { return Collections.singleton(SGetFunction.class); } @Override public Integer getId() { return ExternalizerIds.SET_GET_FUNCTION; } @Override public void writeObject(ObjectOutput output, SGetFunction object) throws IOException { } @Override public SGetFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new SGetFunction(); } } }
1,787
29.827586
100
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/set/SAddFunction.java
package org.infinispan.multimap.impl.function.set; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.SetBucket; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedSetCache#add} * to add elements to a Set. * * @author Vittorio Rigamonti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class SAddFunction<K, V> implements SetBucketBaseFunction<K, V, Boolean> { public static final AdvancedExternalizer<SAddFunction> EXTERNALIZER = new Externalizer(); private final V value; public SAddFunction(V value) { this.value = value; } @Override public Boolean apply(EntryView.ReadWriteEntryView<K, SetBucket<V>> entryView) { Optional<SetBucket<V>> existing = entryView.peek(); boolean retVal; if (existing.isPresent()) { var s = existing.get(); retVal = existing.get().add(value); //don't change the cache if the value already exists. it avoids replicating a no-op if (retVal) { entryView.set(s); } } else { entryView.set(SetBucket.create(value)); retVal = true; } return retVal; } private static class Externalizer implements AdvancedExternalizer<SAddFunction> { @Override public Set<Class<? extends SAddFunction>> getTypeClasses() { return Collections.singleton(SAddFunction.class); } @Override public Integer getId() { return ExternalizerIds.SET_ADD_FUNCTION; } @Override public void writeObject(ObjectOutput output, SAddFunction object) throws IOException { output.writeObject(object.value); } @Override public SAddFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new SAddFunction(input.readObject()); } } }
2,218
29.39726
100
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/set/SetBucketBaseFunction.java
package org.infinispan.multimap.impl.function.set; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.SetBucket; import org.infinispan.util.function.SerializableFunction; /** * A base function for the set updates * * @author Vittorio Rigamonti * @since 15.0 */ public interface SetBucketBaseFunction<K, V, R> extends SerializableFunction<EntryView.ReadWriteEntryView<K, SetBucket<V>>, R> {}
427
29.571429
129
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/hmap/HashMapKeySetFunction.java
package org.infinispan.multimap.impl.function.hmap; import static org.infinispan.multimap.impl.ExternalizerIds.HASH_MAP_KEYSET_FUNCTION; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.HashMapBucket; /** * Serializable function used by {@link org.infinispan.multimap.impl.EmbeddedMultimapPairCache#keySet(Object)}. * <p> * This functions returns the key set of the {@link HashMapBucket}, or an empty set if the entry is not found. * </p> * * @param <K>: Key type to identify the {@link HashMapBucket}. * @param <HK>: The {@link HashMapBucket} key type. * @param <HV>: The {@link HashMapBucket} value type. * @since 15.0 * @see BaseFunction */ public class HashMapKeySetFunction<K, HK, HV> extends HashMapBucketBaseFunction<K, HK, HV, Set<HK>> { public static final Externalizer EXTERNALIZER = new Externalizer(); @Override public Set<HK> apply(EntryView.ReadWriteEntryView<K, HashMapBucket<HK, HV>> view) { Optional<HashMapBucket<HK, HV>> existing = view.peek(); if (existing.isPresent()) { return existing.get().keySet(); } return Collections.emptySet(); } @SuppressWarnings({"rawtypes", "deprecation"}) private static class Externalizer implements AdvancedExternalizer<HashMapKeySetFunction> { @Override public Set<Class<? extends HashMapKeySetFunction>> getTypeClasses() { return Collections.singleton(HashMapKeySetFunction.class); } @Override public Integer getId() { return HASH_MAP_KEYSET_FUNCTION; } @Override public void writeObject(ObjectOutput output, HashMapKeySetFunction object) throws IOException { } @Override public HashMapKeySetFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new HashMapKeySetFunction(); } } }
2,099
31.307692
111
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/hmap/HashMapBucketBaseFunction.java
package org.infinispan.multimap.impl.function.hmap; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.HashMapBucket; import org.infinispan.util.function.SerializableFunction; public abstract class HashMapBucketBaseFunction<K, HK, HV, R> implements SerializableFunction<EntryView.ReadWriteEntryView<K, HashMapBucket<HK, HV>>, R> { }
370
40.222222
100
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/hmap/HashMapValuesFunction.java
package org.infinispan.multimap.impl.function.hmap; import static org.infinispan.multimap.impl.ExternalizerIds.HASH_MAP_VALUES_FUNCTION; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.HashMapBucket; /** * Serializable function used by {@link org.infinispan.multimap.impl.EmbeddedMultimapPairCache#values(Object)}. * <p> * This function returns the values of the {@link HashMapBucket}, or an empty set if the entry is not found. * </p> * * @param <K>: Key type to identify the {@link HashMapBucket}. * @param <HK>: The {@link HashMapBucket} key type. * @param <HV>: The {@link HashMapBucket} value type. * @since 15.0 * @see BaseFunction */ public class HashMapValuesFunction<K, HK, HV> extends HashMapBucketBaseFunction<K, HK, HV, Collection<HV>> { public static final Externalizer EXTERNALIZER = new Externalizer(); @Override public Collection<HV> apply(EntryView.ReadWriteEntryView<K, HashMapBucket<HK, HV>> view) { Optional<HashMapBucket<HK, HV>> existing = view.peek(); if (existing.isPresent()) { return existing.get().values(); } return Collections.emptyList(); } @SuppressWarnings({"rawtypes", "deprecation"}) private static class Externalizer implements AdvancedExternalizer<HashMapValuesFunction> { @Override public Set<Class<? extends HashMapValuesFunction>> getTypeClasses() { return Collections.singleton(HashMapValuesFunction.class); } @Override public Integer getId() { return HASH_MAP_VALUES_FUNCTION; } @Override public void writeObject(ObjectOutput output, HashMapValuesFunction object) throws IOException { } @Override public HashMapValuesFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new HashMapValuesFunction(); } } }
2,142
32.484375
111
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/hmap/HashMapRemoveFunction.java
package org.infinispan.multimap.impl.function.hmap; import static org.infinispan.multimap.impl.ExternalizerIds.HASH_MAP_REMOVE_FUNCTION; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.HashMapBucket; public class HashMapRemoveFunction<K, HK, HV> extends HashMapBucketBaseFunction<K, HK, HV, Integer> { public static final Externalizer EXTERNALIZER = new Externalizer(); private final Collection<HK> keys; public HashMapRemoveFunction(Collection<HK> keys) { this.keys = keys; } @Override public Integer apply(EntryView.ReadWriteEntryView<K, HashMapBucket<HK, HV>> view) { int res = 0; Optional<HashMapBucket<HK, HV>> existing = view.peek(); if (existing.isPresent()) { HashMapBucket<HK, HV> bucket = existing.get(); res = bucket.removeAll(keys); if (bucket.isEmpty()) { view.remove(); } else { view.set(bucket); } } return res; } @SuppressWarnings({"rawtypes", "deprecation"}) private static class Externalizer implements AdvancedExternalizer<HashMapRemoveFunction> { @Override public Set<Class<? extends HashMapRemoveFunction>> getTypeClasses() { return Collections.singleton(HashMapRemoveFunction.class); } @Override public Integer getId() { return HASH_MAP_REMOVE_FUNCTION; } @Override public void writeObject(ObjectOutput output, HashMapRemoveFunction object) throws IOException { output.writeObject(object.keys); } @Override @SuppressWarnings("unchecked") public HashMapRemoveFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { Collection keys = (Collection) input.readObject(); return new HashMapRemoveFunction(keys); } } }
2,119
29.285714
109
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/hmap/HashMapPutFunction.java
package org.infinispan.multimap.impl.function.hmap; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.HashMapBucket; /** * Serializable function use by {@link org.infinispan.multimap.impl.EmbeddedMultimapPairCache#set(Object, Map.Entry[])}. * </p> * This function inserts a collection of key-value pairs into the multimap. If it not exists, a new one is created. * * @author José Bolina * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public class HashMapPutFunction<K, HK, HV> extends HashMapBucketBaseFunction<K, HK, HV, Integer> { public static final AdvancedExternalizer<HashMapPutFunction> EXTERNALIZER = new Externalizer(); private final Collection<Map.Entry<HK, HV>> entries; public HashMapPutFunction(Collection<Map.Entry<HK, HV>> entries) { this.entries = entries; } @Override public Integer apply(EntryView.ReadWriteEntryView<K, HashMapBucket<HK, HV>> view) { Map<HK, HV> values = entries.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); Optional<HashMapBucket<HK, HV>> existing = view.peek(); int res; HashMapBucket<HK, HV> bucket; if (existing.isPresent()) { bucket = existing.get(); res = bucket.putAll(values); } else { bucket = HashMapBucket.create(values); res = values.size(); } view.set(bucket); return res; } public static class Externalizer implements AdvancedExternalizer<HashMapPutFunction> { @Override public Set<Class<? extends HashMapPutFunction>> getTypeClasses() { return Collections.singleton(HashMapPutFunction.class); } @Override public Integer getId() { return ExternalizerIds.HASH_MAP_PUT_FUNCTION; } @Override public void writeObject(ObjectOutput output, HashMapPutFunction object) throws IOException { output.writeInt(object.entries.size()); Collection<Map.Entry> e = object.entries; for (Map.Entry entry : e) { output.writeObject(entry.getKey()); output.writeObject(entry.getValue()); } } @Override public HashMapPutFunction<?, ?, ?> readObject(ObjectInput input) throws IOException, ClassNotFoundException { int size = input.readInt(); Map<Object, Object> values = new HashMap<>(size); for (int i = 0; i < size; i++) { values.put(input.readObject(), input.readObject()); } return new HashMapPutFunction<>(values.entrySet()); } } }
3,018
32.921348
120
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/hmap/HashMapReplaceFunction.java
package org.infinispan.multimap.impl.function.hmap; import static org.infinispan.multimap.impl.ExternalizerIds.HASH_MAP_REPLACE_FUNCTION; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.HashMapBucket; public class HashMapReplaceFunction<K, HK, HV> extends HashMapBucketBaseFunction<K, HK, HV, Boolean> { public static final Externalizer EXTERNALIZER = new Externalizer(); private final HK property; private final HV expected; private final HV replacement; public HashMapReplaceFunction(HK property, HV expected, HV replacement) { this.property = property; this.expected = expected; this.replacement = replacement; } @Override public Boolean apply(EntryView.ReadWriteEntryView<K, HashMapBucket<HK, HV>> view) { Optional<HashMapBucket<HK, HV>> existing = view.peek(); HashMapBucket<HK, HV> bucket = existing.orElse(HashMapBucket.create(Map.of())); boolean replaced = bucket.replace(property, expected, replacement); if (replaced) view.set(bucket); return replaced; } @SuppressWarnings({"unchecked", "rawtypes", "deprecation"}) private static class Externalizer implements AdvancedExternalizer<HashMapReplaceFunction> { @Override public Set<Class<? extends HashMapReplaceFunction>> getTypeClasses() { return Collections.singleton(HashMapReplaceFunction.class); } @Override public Integer getId() { return HASH_MAP_REPLACE_FUNCTION; } @Override public void writeObject(ObjectOutput output, HashMapReplaceFunction object) throws IOException { output.writeObject(object.property); output.writeObject(object.expected); output.writeObject(object.replacement); } @Override public HashMapReplaceFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new HashMapReplaceFunction(input.readObject(), input.readObject(), input.readObject()); } } }
2,274
32.455882
110
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/list/TrimFunction.java
package org.infinispan.multimap.impl.function.list; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.ListBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#trim(Object, long, long)} * to trim the multimap list value. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class TrimFunction<K, V> implements ListBucketBaseFunction<K, V, Boolean> { public static final AdvancedExternalizer<TrimFunction> EXTERNALIZER = new TrimFunction.Externalizer(); private final long from; private final long to; public TrimFunction(long from, long to) { this.from = from; this.to = to; } @Override public Boolean apply(EntryView.ReadWriteEntryView<K, ListBucket<V>> entryView) { Optional<ListBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { ListBucket bucket = existing.get(); bucket.trim(from, to); if (bucket.isEmpty()) { entryView.remove(); } return true; } // key does not exist return false; } private static class Externalizer implements AdvancedExternalizer<TrimFunction> { @Override public Set<Class<? extends TrimFunction>> getTypeClasses() { return Collections.singleton(TrimFunction.class); } @Override public Integer getId() { return ExternalizerIds.TRIM_FUNCTION; } @Override public void writeObject(ObjectOutput output, TrimFunction object) throws IOException { output.writeLong(object.from); output.writeLong(object.to); } @Override public TrimFunction readObject(ObjectInput input) throws IOException { return new TrimFunction(input.readLong(), input.readLong()); } } }
2,205
29.219178
105
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/list/IndexFunction.java
package org.infinispan.multimap.impl.function.list; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.ListBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#index(Object, long)} * to retrieve the index at the head or the tail of the multimap list value. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class IndexFunction<K, V> implements ListBucketBaseFunction<K, V, V> { public static final AdvancedExternalizer<IndexFunction> EXTERNALIZER = new IndexFunction.Externalizer(); private final long index; public IndexFunction(long index) { this.index = index; } @Override public V apply(EntryView.ReadWriteEntryView<K, ListBucket<V>> entryView) { Optional<ListBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { return existing.get().index(index); } // key does not exist return null; } private static class Externalizer implements AdvancedExternalizer<IndexFunction> { @Override public Set<Class<? extends IndexFunction>> getTypeClasses() { return Collections.singleton(IndexFunction.class); } @Override public Integer getId() { return ExternalizerIds.INDEX_FUNCTION; } @Override public void writeObject(ObjectOutput output, IndexFunction object) throws IOException { output.writeLong(object.index); } @Override public IndexFunction readObject(ObjectInput input) throws IOException { return new IndexFunction(input.readLong()); } } }
2,003
29.830769
107
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/list/InsertFunction.java
package org.infinispan.multimap.impl.function.list; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.ListBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#insert(Object, boolean, Object, Object)} * to insert an element before or after the provided pivot element. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class InsertFunction<K, V> implements ListBucketBaseFunction<K, V, Long> { public static final AdvancedExternalizer<InsertFunction> EXTERNALIZER = new InsertFunction.Externalizer(); private final boolean before; private final V pivot; private final V element; public InsertFunction(boolean before, V pivot, V element) { this.before = before; this.pivot = pivot; this.element = element; } @Override public Long apply(EntryView.ReadWriteEntryView<K, ListBucket<V>> entryView) { Optional<ListBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { ListBucket<V> bucket = existing.get().insert(before, pivot, element); if (bucket == null) { // pivot not found return -1L; } else { entryView.set(bucket); return (long) bucket.size(); } } // key does not exist return 0L; } private static class Externalizer implements AdvancedExternalizer<InsertFunction> { @Override public Set<Class<? extends InsertFunction>> getTypeClasses() { return Collections.singleton(InsertFunction.class); } @Override public Integer getId() { return ExternalizerIds.INSERT_FUNCTION; } @Override public void writeObject(ObjectOutput output, InsertFunction object) throws IOException { output.writeBoolean(object.before); output.writeObject(object.pivot); output.writeObject(object.element); } @Override public InsertFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException{ return new InsertFunction(input.readBoolean(), input.readObject(), input.readObject()); } } }
2,553
31.329114
109
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/list/IndexOfFunction.java
package org.infinispan.multimap.impl.function.list; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.ListBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#indexOf(Object, Object, Long, Long, Long)} * to retrieve the index at the head or the tail of the multimap list value. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class IndexOfFunction<K, V> implements ListBucketBaseFunction<K, V, Collection<Long>> { public static final AdvancedExternalizer<IndexOfFunction> EXTERNALIZER = new IndexOfFunction.Externalizer(); private final V element; private final long count; private final long rank; private final long maxLen; public IndexOfFunction(V element, long count, long rank, long maxLen) { this.element = element; this.count = count; this.rank = rank; this.maxLen = maxLen; } @Override public Collection<Long> apply(EntryView.ReadWriteEntryView<K, ListBucket<V>> entryView) { Optional<ListBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { return existing.get().indexOf(element, count, rank, maxLen); } // key does not exist return null; } private static class Externalizer implements AdvancedExternalizer<IndexOfFunction> { @Override public Set<Class<? extends IndexOfFunction>> getTypeClasses() { return Collections.singleton(IndexOfFunction.class); } @Override public Integer getId() { return ExternalizerIds.INDEXOF_FUNCTION; } @Override public void writeObject(ObjectOutput output, IndexOfFunction object) throws IOException { output.writeObject(object.element); output.writeLong(object.count); output.writeLong(object.rank); output.writeLong(object.maxLen); } @Override public IndexOfFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException{ return new IndexOfFunction(input.readObject(), input.readLong(), input.readLong(), input.readLong()); } } }
2,540
32.88
111
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/list/OfferFunction.java
package org.infinispan.multimap.impl.function.list; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.ListBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#offerFirst(Object, Object)} and * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#offerLast(Object, Object)} (Object, Object)} * to insert a key/value pair at the head or the tail of the multimap list value. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class OfferFunction<K, V> implements ListBucketBaseFunction<K, V, Void> { public static final AdvancedExternalizer<OfferFunction> EXTERNALIZER = new Externalizer(); private final V value; private final boolean first; public OfferFunction(V value, boolean first) { this.value = value; this.first = first; } @Override public Void apply(EntryView.ReadWriteEntryView<K, ListBucket<V>> entryView) { Optional<ListBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { ListBucket<V> newBucket = existing.get().offer(value, first); //don't change the cache is the value already exists. it avoids replicating a no-op if (newBucket != null) { entryView.set(newBucket); } } else { entryView.set(ListBucket.create(value)); } return null; } private static class Externalizer implements AdvancedExternalizer<OfferFunction> { @Override public Set<Class<? extends OfferFunction>> getTypeClasses() { return Collections.singleton(OfferFunction.class); } @Override public Integer getId() { return ExternalizerIds.OFFER_FUNCTION; } @Override public void writeObject(ObjectOutput output, OfferFunction object) throws IOException { output.writeObject(object.value); output.writeBoolean(object.first); } @Override public OfferFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new OfferFunction(input.readObject(), input.readBoolean()); } } }
2,521
32.626667
109
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/list/SubListFunction.java
package org.infinispan.multimap.impl.function.list; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.ListBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#subList(Object, long, long)} * to retrieve the sublist with indexes. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class SubListFunction<K, V> implements ListBucketBaseFunction<K, V, Collection<V>> { public static final AdvancedExternalizer<SubListFunction> EXTERNALIZER = new SubListFunction.Externalizer(); private final long from; private final long to; public SubListFunction(long from, long to) { this.from = from; this.to = to; } @Override public Collection<V> apply(EntryView.ReadWriteEntryView<K, ListBucket<V>> entryView) { Optional<ListBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { return existing.get().sublist(from, to); } return null; } private static class Externalizer implements AdvancedExternalizer<SubListFunction> { @Override public Set<Class<? extends SubListFunction>> getTypeClasses() { return Collections.singleton(SubListFunction.class); } @Override public Integer getId() { return ExternalizerIds.SUBLIST_FUNCTION; } @Override public void writeObject(ObjectOutput output, SubListFunction object) throws IOException { output.writeLong(object.from); output.writeLong(object.to); } @Override public SubListFunction readObject(ObjectInput input) throws IOException { return new SubListFunction(input.readLong(), input.readLong()); } } }
2,133
30.382353
111
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/list/RemoveCountFunction.java
package org.infinispan.multimap.impl.function.list; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.ListBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#remove(Object, long, Object)} * to remove an element. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class RemoveCountFunction<K, V> implements ListBucketBaseFunction<K, V, Long> { public static final AdvancedExternalizer<RemoveCountFunction> EXTERNALIZER = new RemoveCountFunction.Externalizer(); private final long count; private final V element; public RemoveCountFunction(long count, V element) { this.count = count; this.element = element; } @Override public Long apply(EntryView.ReadWriteEntryView<K, ListBucket<V>> entryView) { Optional<ListBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { ListBucket<V> prevBucket = existing.get(); long removedCount = existing.get().remove(count, element); if (prevBucket.isEmpty()) { // if the list is empty, remove entryView.remove(); } return removedCount; } // key does not exist return 0L; } private static class Externalizer implements AdvancedExternalizer<RemoveCountFunction> { @Override public Set<Class<? extends RemoveCountFunction>> getTypeClasses() { return Collections.singleton(RemoveCountFunction.class); } @Override public Integer getId() { return ExternalizerIds.REMOVE_COUNT_FUNCTION; } @Override public void writeObject(ObjectOutput output, RemoveCountFunction object) throws IOException { output.writeLong(object.count); output.writeObject(object.element); } @Override public RemoveCountFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException{ return new RemoveCountFunction(input.readLong(), input.readObject()); } } }
2,417
31.675676
119
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/list/RotateFunction.java
package org.infinispan.multimap.impl.function.list; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.ListBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#rotate(Object, boolean)} (Object, boolean)} * to remove an element. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class RotateFunction<K, V> implements ListBucketBaseFunction<K, V, V> { public static final AdvancedExternalizer<RotateFunction> EXTERNALIZER = new RotateFunction.Externalizer(); private final boolean rotateRight; public RotateFunction(boolean rotateRight) { this.rotateRight = rotateRight; } @Override public V apply(EntryView.ReadWriteEntryView<K, ListBucket<V>> entryView) { Optional<ListBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { return existing.get().rotate(rotateRight); } // key does not exist return null; } private static class Externalizer implements AdvancedExternalizer<RotateFunction> { @Override public Set<Class<? extends RotateFunction>> getTypeClasses() { return Collections.singleton(RotateFunction.class); } @Override public Integer getId() { return ExternalizerIds.ROTATE_FUNCTION; } @Override public void writeObject(ObjectOutput output, RotateFunction object) throws IOException { output.writeBoolean(object.rotateRight); } @Override public RotateFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException{ return new RotateFunction(input.readBoolean()); } } }
2,057
30.661538
109
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/list/ListBucketBaseFunction.java
package org.infinispan.multimap.impl.function.list; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ListBucket; import org.infinispan.util.function.SerializableFunction; /** * A base function for the list multimap updates * * @author Katia Aresti * @since 15.0 */ public interface ListBucketBaseFunction<K, V, R> extends SerializableFunction<EntryView.ReadWriteEntryView<K, ListBucket<V>>, R> {}
435
30.142857
131
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/list/SetFunction.java
package org.infinispan.multimap.impl.function.list; import org.infinispan.commons.CacheException; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.ListBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#set(Object, long, Object)} * to insert a key/value pair at the index of the multimap list value. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class SetFunction<K, V> implements ListBucketBaseFunction<K, V, Boolean> { public static final AdvancedExternalizer<SetFunction> EXTERNALIZER = new Externalizer(); private final long index; private final V value; public SetFunction(long index, V value) { this.index = index; this.value = value; } @Override public Boolean apply(EntryView.ReadWriteEntryView<K, ListBucket<V>> entryView) { Optional<ListBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { ListBucket<V> newBucket = existing.get().set(index, value); if (newBucket != null) { entryView.set(newBucket); return true; } throw new CacheException(new IndexOutOfBoundsException("Index is out of range")); } return false; } private static class Externalizer implements AdvancedExternalizer<SetFunction> { @Override public Set<Class<? extends SetFunction>> getTypeClasses() { return Collections.singleton(SetFunction.class); } @Override public Integer getId() { return ExternalizerIds.SET_FUNCTION; } @Override public void writeObject(ObjectOutput output, SetFunction object) throws IOException { output.writeLong(object.index); output.writeObject(object.value); } @Override public SetFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new SetFunction(input.readLong(), input.readObject()); } } }
2,372
31.067568
99
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/list/PollFunction.java
package org.infinispan.multimap.impl.function.list; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.ListBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#pollFirst(K, long)} and * {@link org.infinispan.multimap.impl.EmbeddedMultimapListCache#pollLast(K, long)} * to poll N values at the head or the tail of the multimap list value. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class PollFunction<K, V> implements ListBucketBaseFunction<K, V, Collection<V>> { public static final AdvancedExternalizer<PollFunction> EXTERNALIZER = new PollFunction.Externalizer(); private final boolean first; private final long count; public PollFunction(boolean first, long count) { this.first = first; this.count = count; } @Override public Collection<V> apply(EntryView.ReadWriteEntryView<K, ListBucket<V>> entryView) { Optional<ListBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { if (count == 0) { // Do nothing and return an empty list return List.of(); } ListBucket<V>.ListBucketResult result = existing.get().poll(first, count); if (result.bucketValue().isEmpty()) { entryView.remove(); } else { entryView.set(result.bucketValue()); } return result.opResult(); } // key does not exist return null; } private static class Externalizer implements AdvancedExternalizer<PollFunction> { @Override public Set<Class<? extends PollFunction>> getTypeClasses() { return Collections.singleton(PollFunction.class); } @Override public Integer getId() { return ExternalizerIds.POLL_FUNCTION; } @Override public void writeObject(ObjectOutput output, PollFunction object) throws IOException { output.writeBoolean(object.first); output.writeLong(object.count); } @Override public PollFunction readObject(ObjectInput input) throws IOException { return new PollFunction(input.readBoolean(), input.readLong()); } } }
2,639
31.195122
105
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/multimap/GetFunction.java
package org.infinispan.multimap.impl.function.multimap; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.Bucket; import org.infinispan.multimap.impl.ExternalizerIds; /** * Serializable function used by {@link org.infinispan.multimap.impl.EmbeddedMultimapCache#get(Object)} * to get a key's value. * * @author Katia Aresti - karesti@redhat.com * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 9.2 */ public final class GetFunction<K, V> implements BaseFunction<K, V, Collection<V>> { public static final AdvancedExternalizer<GetFunction> EXTERNALIZER = new Externalizer(); private final boolean supportsDuplicates; public GetFunction(Boolean supportsDuplicates) { this.supportsDuplicates = supportsDuplicates; } @Override public Collection<V> apply(EntryView.ReadWriteEntryView<K, Bucket<V>> entryView) { Optional<Bucket<V>> valuesOpt = entryView.find(); if (valuesOpt.isPresent()) { return supportsDuplicates ? entryView.find().get().toList() : entryView.find().get().toSet(); } else { return Collections.emptySet(); } } private static class Externalizer implements AdvancedExternalizer<GetFunction> { @Override public Set<Class<? extends GetFunction>> getTypeClasses() { return Collections.singleton(GetFunction.class); } @Override public Integer getId() { return ExternalizerIds.GET_FUNCTION; } @Override public void writeObject(ObjectOutput output, GetFunction object) throws IOException { output.writeBoolean(object.supportsDuplicates); } @Override public GetFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new GetFunction(input.readBoolean()); } } }
2,127
31.242424
103
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/multimap/ContainsFunction.java
package org.infinispan.multimap.impl.function.multimap; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.Bucket; import org.infinispan.multimap.impl.ExternalizerIds; /** * Serializable function used by {@link org.infinispan.multimap.impl.EmbeddedMultimapCache#containsKey(Object)} and * {@link org.infinispan.multimap.impl.EmbeddedMultimapCache#containsEntry(Object, Object)}. * * @author Katia Aresti - karesti@redhat.com * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 9.2 */ public final class ContainsFunction<K, V> implements BaseFunction<K, V, Boolean> { public static final AdvancedExternalizer<ContainsFunction> EXTERNALIZER = new Externalizer(); private final V value; public ContainsFunction() { this.value = null; } /** * Call this constructor to create a function that checks if a key/value pair exists * <ul> * <li>if the key is null, the value will be searched in any key * <li>if the value is null, the key will be searched * <li>key-value pair are not null, the entry will be searched * <li>key-value pair are null, a {@link NullPointerException} will be raised * </ul> * * @param value value to be checked on the key */ public ContainsFunction(V value) { this.value = value; } @Override public Boolean apply(EntryView.ReadWriteEntryView<K, Bucket<V>> entryView) { return value == null ? entryView.find().isPresent() : entryView.find().map(values -> values.contains(value)).orElse(Boolean.FALSE); } private static class Externalizer implements AdvancedExternalizer<ContainsFunction> { @Override public Set<Class<? extends ContainsFunction>> getTypeClasses() { return Collections.singleton(ContainsFunction.class); } @Override public Integer getId() { return ExternalizerIds.CONTAINS_KEY_VALUE_FUNCTION; } @Override public void writeObject(ObjectOutput output, ContainsFunction object) throws IOException { output.writeObject(object.value); } @Override public ContainsFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new ContainsFunction(input.readObject()); } } }
2,540
32.434211
115
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/multimap/PutFunction.java
package org.infinispan.multimap.impl.function.multimap; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.Bucket; import org.infinispan.multimap.impl.ExternalizerIds; /** * Serializable function used by {@link org.infinispan.multimap.impl.EmbeddedMultimapCache#put(Object, Object)} to add a * key/value pair. * * @author Katia Aresti - karesti@redhat.com * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 9.2 */ public final class PutFunction<K, V> implements BaseFunction<K, V, Void> { public static final AdvancedExternalizer<PutFunction> EXTERNALIZER = new Externalizer(); private final V value; private final boolean supportsDuplicates; public PutFunction(V value, boolean supportsDuplicates) { this.value = value; this.supportsDuplicates = supportsDuplicates; } @Override public Void apply(EntryView.ReadWriteEntryView<K, Bucket<V>> entryView) { Optional<Bucket<V>> existing = entryView.peek(); if (existing.isPresent()) { Bucket<V> newBucket = existing.get().add(value, supportsDuplicates); //don't change the cache is the value already exists. it avoids replicating a no-op if (newBucket != null) { entryView.set(newBucket); } } else { entryView.set(new Bucket<>(value)); } return null; } private static class Externalizer implements AdvancedExternalizer<PutFunction> { @Override public Set<Class<? extends PutFunction>> getTypeClasses() { return Collections.singleton(PutFunction.class); } @Override public Integer getId() { return ExternalizerIds.PUT_KEY_VALUE_FUNCTION; } @Override public void writeObject(ObjectOutput output, PutFunction object) throws IOException { output.writeObject(object.value); output.writeBoolean(object.supportsDuplicates); } @Override public PutFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new PutFunction(input.readObject(), input.readBoolean()); } } }
2,399
31.432432
120
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/multimap/RemoveFunction.java
package org.infinispan.multimap.impl.function.multimap; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Set; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.Bucket; import org.infinispan.multimap.impl.ExternalizerIds; /** * Serializable function used by {@link org.infinispan.multimap.impl.EmbeddedMultimapCache#remove(Object)} and {@link * org.infinispan.multimap.impl.EmbeddedMultimapCache#remove(Object, Object)} to remove a key or a key/value pair from * the Multimap Cache, if such exists. * <p> * {@link #apply(EntryView.ReadWriteEntryView)} will return {@link Boolean#TRUE} when the operation removed a key or a * key/value pair and will return {@link Boolean#FALSE} if the key or key/value pair does not exist * * @author Katia Aresti - karesti@redhat.com * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 9.2 */ public final class RemoveFunction<K, V> implements BaseFunction<K, V, Boolean> { public static final AdvancedExternalizer<RemoveFunction> EXTERNALIZER = new Externalizer(); private final V value; private final boolean supportsDuplicates; /** * Call this constructor to create a function that removed a key */ public RemoveFunction() { this.value = null; this.supportsDuplicates = false; } /** * Call this constructor to create a function that removed a key/value pair * * @param value value to be removed */ public RemoveFunction(V value, boolean supportsDuplicates) { this.value = value; this.supportsDuplicates = supportsDuplicates; } @Override public Boolean apply(EntryView.ReadWriteEntryView<K, Bucket<V>> entryView) { Boolean removed; if (value == null) { removed = removeKey(entryView); } else { removed = removeKeyValue(entryView); } return removed; } private Boolean removeKeyValue(EntryView.ReadWriteEntryView<K, Bucket<V>> entryView) { return entryView.find().map(bucket -> { Bucket<V> newBucket = bucket.remove(value, supportsDuplicates); if (newBucket != null) { if (newBucket.isEmpty()) { entryView.remove(); } else { entryView.set(newBucket); } return Boolean.TRUE; } return Boolean.FALSE; } ).orElse(Boolean.FALSE); } private Boolean removeKey(EntryView.ReadWriteEntryView<K, Bucket<V>> entryView) { return entryView.find().map(values -> { entryView.remove(); return Boolean.TRUE; }).orElse(Boolean.FALSE); } private static class Externalizer implements AdvancedExternalizer<RemoveFunction> { @Override public Set<Class<? extends RemoveFunction>> getTypeClasses() { return Collections.singleton(RemoveFunction.class); } @Override public Integer getId() { return ExternalizerIds.REMOVE_KEY_VALUE_FUNCTION; } @Override public void writeObject(ObjectOutput output, RemoveFunction object) throws IOException { output.writeObject(object.value); output.writeBoolean(object.supportsDuplicates); } @Override public RemoveFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new RemoveFunction(input.readObject(), input.readBoolean()); } } }
3,647
32.777778
118
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/multimap/BaseFunction.java
package org.infinispan.multimap.impl.function.multimap; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.Bucket; import org.infinispan.util.function.SerializableFunction; /** * A base function for the multimap updates * * @author Katia Aresti, karesti@redhat.com * @since 9.2 */ public interface BaseFunction<K, V, R> extends SerializableFunction<EntryView.ReadWriteEntryView<K, Bucket<V>>, R> {}
435
30.142857
117
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/sortedset/ScoreFunction.java
package org.infinispan.multimap.impl.function.sortedset; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.SortedSetBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapSortedSetCache#score(Object, Object)}. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class ScoreFunction<K, V> implements SortedSetBucketBaseFunction<K, V, Double> { public static final AdvancedExternalizer<ScoreFunction> EXTERNALIZER = new Externalizer(); private final V member; public ScoreFunction(V member) { this.member = member; } @Override public Double apply(EntryView.ReadWriteEntryView<K, SortedSetBucket<V>> entryView) { Optional<SortedSetBucket<V>> existing = entryView.peek(); if (existing.isPresent()) { return existing.get().score(member); } return null; } private static class Externalizer implements AdvancedExternalizer<ScoreFunction> { @Override public Set<Class<? extends ScoreFunction>> getTypeClasses() { return Collections.singleton(ScoreFunction.class); } @Override public Integer getId() { return ExternalizerIds.SORTED_SET_SCORE_FUNCTION; } @Override public void writeObject(ObjectOutput output, ScoreFunction object) throws IOException { output.writeObject(object.member); } @Override public ScoreFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new ScoreFunction(input.readObject()); } } }
1,966
30.222222
101
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/sortedset/AddManyFunction.java
package org.infinispan.multimap.impl.function.sortedset; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.SortedSetAddArgs; import org.infinispan.multimap.impl.SortedSetBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapSortedSetCache#addMany(Object, double[], Object[], SortedSetAddArgs)}. * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class AddManyFunction<K, V> implements SortedSetBucketBaseFunction<K, V, Long> { public static final AdvancedExternalizer<AddManyFunction> EXTERNALIZER = new Externalizer(); private final double[] scores; private final V[] values; private final boolean addOnly; private final boolean updateOnly; private final boolean updateLessScoresOnly; private final boolean updateGreaterScoresOnly; private final boolean returnChangedCount; public AddManyFunction(double[] scores, V[] values, boolean addOnly, boolean updateOnly, boolean updateLessScoresOnly, boolean updateGreaterScoresOnly, boolean returnChangedCount) { this.scores = scores; this.values = values; this.addOnly = addOnly; this.updateOnly = updateOnly; this.updateLessScoresOnly = updateLessScoresOnly; this.updateGreaterScoresOnly = updateGreaterScoresOnly; this.returnChangedCount = returnChangedCount; } @Override public Long apply(EntryView.ReadWriteEntryView<K, SortedSetBucket<V>> entryView) { Optional<SortedSetBucket<V>> existing = entryView.peek(); SortedSetBucket bucket = null; if (existing.isPresent()) { bucket = existing.get(); } else if (!updateOnly){ bucket = new SortedSetBucket(); } if (bucket != null) { SortedSetBucket.AddResult addResult = bucket.addMany(scores, values, addOnly, updateOnly, updateLessScoresOnly, updateGreaterScoresOnly); //don't change if nothing was added or updated. it avoids replicating a no-op if (addResult.updated > 0 || addResult.created > 0) { entryView.set(bucket); } // Return created only or created and updated count return returnChangedCount? addResult.created + addResult.updated : addResult.created; } // nothing has been done return 0L; } private static class Externalizer implements AdvancedExternalizer<AddManyFunction> { @Override public Set<Class<? extends AddManyFunction>> getTypeClasses() { return Collections.singleton(AddManyFunction.class); } @Override public Integer getId() { return ExternalizerIds.SORTED_SET_ADD_MANY_FUNCTION; } @Override public void writeObject(ObjectOutput output, AddManyFunction object) throws IOException { output.writeObject(object.scores); output.writeObject(object.values); output.writeBoolean(object.addOnly); output.writeBoolean(object.updateOnly); output.writeBoolean(object.updateLessScoresOnly); output.writeBoolean(object.updateGreaterScoresOnly); output.writeBoolean(object.returnChangedCount); } @Override public AddManyFunction readObject(ObjectInput input) throws IOException, ClassNotFoundException { return new AddManyFunction((double[]) input.readObject(), (Object[])input.readObject(), input.readBoolean(), input.readBoolean(), input.readBoolean(), input.readBoolean(), input.readBoolean()); } } }
4,011
37.576923
202
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/sortedset/CountFunction.java
package org.infinispan.multimap.impl.function.sortedset; import org.infinispan.commons.marshall.AdvancedExternalizer; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.ExternalizerIds; import org.infinispan.multimap.impl.SortedSetBucket; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Collections; import java.util.Optional; import java.util.Set; import java.util.SortedSet; /** * Serializable function used by * {@link org.infinispan.multimap.impl.EmbeddedMultimapSortedSetCache#count(K, double, boolean, double, boolean)} . * * @author Katia Aresti * @see <a href="http://infinispan.org/documentation/">Marshalling of Functions</a> * @since 15.0 */ public final class CountFunction<K, V> implements SortedSetBucketBaseFunction<K, V, Long> { public static final AdvancedExternalizer<CountFunction> EXTERNALIZER = new Externalizer(); private final double min; private final double max; private final boolean includeMin; private final boolean includeMax; public CountFunction(double min, boolean includeMin, double max, boolean includeMax) { this.min = min; this.includeMin = includeMin; this.max = max; this.includeMax = includeMax; } @Override public Long apply(EntryView.ReadWriteEntryView<K, SortedSetBucket<V>> entryView) { Optional<SortedSetBucket<V>> existing = entryView.peek(); long count = 0; if (existing.isPresent()) { SortedSet<SortedSetBucket.ScoredValue<V>> scoredValues = existing.get() .subsetByScores(min, includeMin, max, includeMax); count = scoredValues.size(); } return count; } private static class Externalizer implements AdvancedExternalizer<CountFunction> { @Override public Set<Class<? extends CountFunction>> getTypeClasses() { return Collections.singleton(CountFunction.class); } @Override public Integer getId() { return ExternalizerIds.SORTED_SET_COUNT_FUNCTION; } @Override public void writeObject(ObjectOutput output, CountFunction object) throws IOException { output.writeDouble(object.min); output.writeBoolean(object.includeMin); output.writeDouble(object.max); output.writeBoolean(object.includeMax); } @Override public CountFunction readObject(ObjectInput input) throws IOException { return new CountFunction(input.readDouble(), input.readBoolean(), input.readDouble(), input.readBoolean()); } } }
2,667
32.772152
116
java
null
infinispan-main/multimap/src/main/java/org/infinispan/multimap/impl/function/sortedset/SortedSetBucketBaseFunction.java
package org.infinispan.multimap.impl.function.sortedset; import org.infinispan.functional.EntryView; import org.infinispan.multimap.impl.SortedSetBucket; import org.infinispan.util.function.SerializableFunction; /** * A base function for the sorted set multimap updates * * @author Katia Aresti * @since 15.0 */ public interface SortedSetBucketBaseFunction<K, V, R> extends SerializableFunction<EntryView.ReadWriteEntryView<K, SortedSetBucket<V>>, R> {}
461
32
141
java