repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/eventbus/TestSubscriber.java
utils/src/test/java/org/killbill/commons/eventbus/TestSubscriber.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Tests for {@link Subscriber}. * * @author Cliff Biffle * @author Colin Decker */ public class TestSubscriber { private static final Object FIXTURE_ARGUMENT = new Object(); private EventBus bus; private boolean methodCalled; private Object methodArgument; @BeforeMethod(groups = "fast", alwaysRun = true) protected void setUp() { bus = new EventBus(); methodCalled = false; methodArgument = null; } @Test(groups = "fast") public void testCreate() { final Subscriber s1 = Subscriber.create(bus, this, getTestSubscriberMethod("recordingMethod")); Assert.assertTrue(s1 instanceof Subscriber.SynchronizedSubscriber); // a thread-safe method should not create a synchronized subscriber final Subscriber s2 = Subscriber.create(bus, this, getTestSubscriberMethod("threadSafeMethod")); Assert.assertFalse(s2 instanceof Subscriber.SynchronizedSubscriber); // assertThat(s2).isNotInstanceOf(Subscriber.SynchronizedSubscriber.class); } @Test(groups = "fast") public void testInvokeSubscriberMethod_basicMethodCall() throws Throwable { final Method method = getTestSubscriberMethod("recordingMethod"); final Subscriber subscriber = Subscriber.create(bus, this, method); subscriber.invokeSubscriberMethod(FIXTURE_ARGUMENT); Assert.assertTrue(methodCalled, "Subscriber must call provided method"); Assert.assertSame(methodArgument, FIXTURE_ARGUMENT, "Subscriber argument must be exactly the provided object."); } @Test(groups = "fast") public void testInvokeSubscriberMethod_exceptionWrapping() { final Method method = getTestSubscriberMethod("exceptionThrowingMethod"); final Subscriber subscriber = Subscriber.create(bus, this, method); try { subscriber.invokeSubscriberMethod(FIXTURE_ARGUMENT); Assert.fail("Subscribers whose methods throw must throw InvocationTargetException"); } catch (final InvocationTargetException ignored) { } } @Test(groups = "fast") public void testInvokeSubscriberMethod_errorPassthrough() throws Throwable { final Method method = getTestSubscriberMethod("errorThrowingMethod"); final Subscriber subscriber = Subscriber.create(bus, this, method); try { subscriber.invokeSubscriberMethod(FIXTURE_ARGUMENT); Assert.fail("Subscribers whose methods throw Errors must rethrow them"); } catch (final JudgmentError ignored) { } } private Method getTestSubscriberMethod(final String name) { try { return getClass().getDeclaredMethod(name, Object.class); } catch (final NoSuchMethodException e) { throw new AssertionError(); } } /** * Records the provided object in {@link #methodArgument} and sets {@link #methodCalled}. This * method is called reflectively by Subscriber during tests, and must remain public. * * @param arg argument to record. */ @Subscribe public void recordingMethod(final Object arg) { Assert.assertFalse(methodCalled); methodCalled = true; methodArgument = arg; } @Subscribe public void exceptionThrowingMethod(final Object ignored) throws Exception { throw new IntentionalException(); } /** Local exception subclass to check variety of exception thrown. */ static class IntentionalException extends Exception { private static final long serialVersionUID = -2500191180248181379L; } @Subscribe public void errorThrowingMethod(final Object ignored) { throw new JudgmentError(); } @Subscribe @AllowConcurrentEvents public void threadSafeMethod(final Object ignored) {} /** Local Error subclass to check variety of error thrown. */ static class JudgmentError extends Error { private static final long serialVersionUID = 634248373797713373L; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/eventbus/TestReentrantEvents.java
utils/src/test/java/org/killbill/commons/eventbus/TestReentrantEvents.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.util.ArrayList; import java.util.List; import org.killbill.commons.utils.concurrent.DirectExecutor; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Validate that {@link EventBus} behaves carefully when listeners publish their own events. * * @author Jesse Wilson */ public class TestReentrantEvents { static final String FIRST = "one"; static final Double SECOND = 2.0d; private EventBus bus; @BeforeMethod(groups = "fast", alwaysRun = true) public void beforeMethod() { // to post reentrant-ly, we should use Dispatcher.perThreadDispatchQueue() bus = new EventBus("", DirectExecutor.INSTANCE, Dispatcher.perThreadDispatchQueue(), new DefaultCatchableSubscriberExceptionsHandler()); } @Test(groups = "fast") public void testNoReentrantEvents() { final ReentrantEventsHater hater = new ReentrantEventsHater(); bus.register(hater); bus.post(FIRST); Assert.assertEquals(hater.eventsReceived, List.of(FIRST, SECOND), "ReentrantEventHater expected 2 events"); } public class ReentrantEventsHater { boolean ready = true; List<Object> eventsReceived = new ArrayList<>(); @Subscribe public void listenForStrings(final String event) { eventsReceived.add(event); ready = false; try { bus.post(SECOND); } finally { ready = true; } } @Subscribe public void listenForDoubles(final Double event) { Assert.assertTrue(ready, "I received an event when I wasn't ready!"); eventsReceived.add(event); } } @Test(groups = "fast") public void testEventOrderingIsPredictable() { final EventProcessor processor = new EventProcessor(); bus.register(processor); final EventRecorder recorder = new EventRecorder(); bus.register(recorder); bus.post(FIRST); Assert.assertEquals(recorder.eventsReceived, List.of(FIRST, SECOND), "EventRecorder expected events in order"); } public class EventProcessor { @Subscribe public void listenForStrings(final String ignored) { bus.post(SECOND); } } public static class EventRecorder { List<Object> eventsReceived = new ArrayList<>(); @Subscribe public void listenForEverything(final Object event) { eventsReceived.add(event); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/eventbus/TestDispatcher.java
utils/src/test/java/org/killbill/commons/eventbus/TestDispatcher.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import org.testng.Assert; import org.testng.annotations.Test; /** * Tests for {@link Dispatcher} implementations. * * @author Colin Decker */ public class TestDispatcher { private final EventBus bus = new EventBus(); private final IntegerSubscriber i1 = new IntegerSubscriber("i1"); private final IntegerSubscriber i2 = new IntegerSubscriber("i2"); private final IntegerSubscriber i3 = new IntegerSubscriber("i3"); private final List<Subscriber> integerSubscribers = List.of(subscriber(bus, i1, "handleInteger", Integer.class), subscriber(bus, i2, "handleInteger", Integer.class), subscriber(bus, i3, "handleInteger", Integer.class)); private final StringSubscriber s1 = new StringSubscriber("s1"); private final StringSubscriber s2 = new StringSubscriber("s2"); private final List<Subscriber> stringSubscribers = List.of(subscriber(bus, s1, "handleString", String.class), subscriber(bus, s2, "handleString", String.class)); private final ConcurrentLinkedQueue<Object> dispatchedSubscribers = new ConcurrentLinkedQueue<>(); private Dispatcher dispatcher; @Test(groups = "fast") public void testPerThreadQueuedDispatcher() { dispatcher = Dispatcher.perThreadDispatchQueue(); dispatcher.dispatch(1, integerSubscribers.iterator()); Assert.assertTrue(dispatchedSubscribers.containsAll(List.of(i1, i2, i3, // Integer subscribers are dispatched to first. s1, s2, // Though each integer subscriber dispatches to all string subscribers, s1, s2, // those string subscribers aren't actually dispatched to until all integer s1, s2))); // subscribers have finished. } @Test(groups = "fast") public void testImmediateDispatcher() { dispatcher = Dispatcher.immediate(); dispatcher.dispatch(1, integerSubscribers.iterator()); Assert.assertTrue(dispatchedSubscribers.containsAll(List.of(i1, s1, s2, // Each integer subscriber immediately dispatches to 2 string subscribers. i2, s1, s2, i3, s1, s2))); } private static Subscriber subscriber(final EventBus bus, final Object target, final String methodName, final Class<?> eventType) { try { return Subscriber.create(bus, target, target.getClass().getMethod(methodName, eventType)); } catch (final NoSuchMethodException e) { throw new AssertionError(e); } } public final class IntegerSubscriber { private final String name; public IntegerSubscriber(final String name) { this.name = name; } @Subscribe public void handleInteger(final Integer ignored) { dispatchedSubscribers.add(this); dispatcher.dispatch("hello", stringSubscribers.iterator()); } @Override public String toString() { return name; } } public final class StringSubscriber { private final String name; public StringSubscriber(final String name) { this.name = name; } @Subscribe public void handleString(final String ignored) { dispatchedSubscribers.add(this); } @Override public String toString() { return name; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/eventbus/StringCatcher.java
utils/src/test/java/org/killbill/commons/eventbus/StringCatcher.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import org.testng.Assert; /** * A simple EventSubscriber mock that records Strings. * * <p>For testing fun, also includes a landmine method that EventBus tests are required <em>not</em> * to call ({@link #methodWithoutAnnotation(String)}). * * @author Cliff Biffle */ class StringCatcher { private final List<String> events = new ArrayList<>(); @Subscribe public void hereHaveAString(@Nullable final String string) { events.add(string); } public void methodWithoutAnnotation(@Nullable final String string) { Assert.fail("Event bus must not call methods without @Subscribe: " + string); } public List<String> getEvents() { return events; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/eventbus/TestSubscriberRegistry.java
utils/src/test/java/org/killbill/commons/eventbus/TestSubscriberRegistry.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.util.Iterator; import java.util.Set; import org.killbill.commons.utils.collect.Iterators; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; /** * Tests for {@link SubscriberRegistry}. Taken from Guava's test. * * @author Colin Decker */ public class TestSubscriberRegistry { private SubscriberRegistry registry; @BeforeMethod(groups = "fast", alwaysRun = true) public void beforeMethod() { registry = new SubscriberRegistry(new EventBus()); } @Test(groups = "fast") public void testRegister() { assertEquals(registry.getSubscribersForTesting(String.class).size(), 0); registry.register(new StringSubscriber()); assertEquals(registry.getSubscribersForTesting(String.class).size(), 1); registry.register(new StringSubscriber()); assertEquals(registry.getSubscribersForTesting(String.class).size(), 2); registry.register(new ObjectSubscriber()); assertEquals(registry.getSubscribersForTesting(String.class).size(), 2); assertEquals(registry.getSubscribersForTesting(Object.class).size(), 1); } @Test(groups = "fast") public void testUnregister() { final StringSubscriber s1 = new StringSubscriber(); final StringSubscriber s2 = new StringSubscriber(); registry.register(s1); registry.register(s2); registry.unregister(s1); assertEquals(registry.getSubscribersForTesting(String.class).size(), 1); registry.unregister(s2); assertTrue(registry.getSubscribersForTesting(String.class).isEmpty()); } @Test(groups = "fast") public void testUnregisterNotRegistered() { try { registry.unregister(new StringSubscriber()); fail(); } catch (final IllegalArgumentException expected) { } final StringSubscriber s1 = new StringSubscriber(); registry.register(s1); try { registry.unregister(new StringSubscriber()); fail(); } catch (final IllegalArgumentException expected) { // a StringSubscriber was registered, but not the same one we tried to unregister } registry.unregister(s1); try { registry.unregister(s1); fail(); } catch (final IllegalArgumentException expected) { } } @Test(groups = "fast") public void testGetSubscribers() { assertEquals(Iterators.size(registry.getSubscribers(new Object())), 0); assertEquals(Iterators.size(registry.getSubscribers("")), 0); assertEquals(Iterators.size(registry.getSubscribers(1)), 0); registry.register(new StringSubscriber()); assertEquals(Iterators.size(registry.getSubscribers("")), 1); assertEquals(Iterators.size(registry.getSubscribers(new Object())), 0); assertEquals(Iterators.size(registry.getSubscribers(1)), 0); registry.register(new StringSubscriber()); assertEquals(Iterators.size(registry.getSubscribers("")), 2); assertEquals(Iterators.size(registry.getSubscribers(new Object())), 0); assertEquals(Iterators.size(registry.getSubscribers(1)), 0); // Object registered. All subclasses will be increased. final ObjectSubscriber objSub = new ObjectSubscriber(); registry.register(objSub); assertEquals(Iterators.size(registry.getSubscribers(new Object())), 1); assertEquals(Iterators.size(registry.getSubscribers("")), 3); assertEquals(Iterators.size(registry.getSubscribers(1)), 1); registry.register(new IntegerSubscriber()); assertEquals(Iterators.size(registry.getSubscribers(new Object())), 1); assertEquals(Iterators.size(registry.getSubscribers("")), 3); assertEquals(Iterators.size(registry.getSubscribers(1)), 2); // Unregister Object registry.unregister(objSub); assertEquals(Iterators.size(registry.getSubscribers(new Object())), 0); assertEquals(Iterators.size(registry.getSubscribers("")), 2); assertEquals(Iterators.size(registry.getSubscribers(1)), 1); } @Test(groups = "fast") public void testGetSubscribersReturnsImmutableSnapshot() { final StringSubscriber str1 = new StringSubscriber(); final StringSubscriber str2 = new StringSubscriber(); final ObjectSubscriber obj1 = new ObjectSubscriber(); Iterator<Subscriber> empty = registry.getSubscribers(""); assertFalse(empty.hasNext()); empty = registry.getSubscribers(""); registry.register(str1); assertFalse(empty.hasNext()); Iterator<Subscriber> one = registry.getSubscribers(""); assertEquals(str1, one.next().target); assertFalse(one.hasNext()); one = registry.getSubscribers(""); registry.register(str2); registry.register(obj1); Iterator<Subscriber> three = registry.getSubscribers(""); assertEquals(str1, one.next().target); assertFalse(one.hasNext()); assertEquals(str1, three.next().target); assertEquals(str2, three.next().target); assertEquals(obj1, three.next().target); assertFalse(three.hasNext()); three = registry.getSubscribers(""); registry.unregister(str2); assertEquals(str1, three.next().target); assertEquals(str2, three.next().target); assertEquals(obj1, three.next().target); assertFalse(three.hasNext()); final Iterator<Subscriber> two = registry.getSubscribers(""); assertEquals(str1, two.next().target); assertEquals(obj1, two.next().target); assertFalse(two.hasNext()); } public static class StringSubscriber { @Subscribe public void handle(final String s) {} } public static class IntegerSubscriber { @Subscribe public void handle(final Integer i) {} } public static class ObjectSubscriber { @Subscribe public void handle(final Object o) {} } @Test(groups = "fast") public void testFlattenHierarchy() { assertEquals( Set.of(Object.class, HierarchyFixtureInterface.class, HierarchyFixtureSubinterface.class, HierarchyFixtureParent.class, HierarchyFixture.class), SubscriberRegistry.flattenHierarchy(HierarchyFixture.class)); } private interface HierarchyFixtureInterface { // Exists only for hierarchy mapping; no members. } private interface HierarchyFixtureSubinterface extends HierarchyFixtureInterface { // Exists only for hierarchy mapping; no members. } private static class HierarchyFixtureParent implements HierarchyFixtureSubinterface { // Exists only for hierarchy mapping; no members. } private static class HierarchyFixture extends HierarchyFixtureParent { // Exists only for hierarchy mapping; no members. } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/eventbus/TestEventBusPostWithException.java
utils/src/test/java/org/killbill/commons/eventbus/TestEventBusPostWithException.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.lang.reflect.InvocationTargetException; import java.util.UUID; import org.testng.Assert; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; /** * Move all test from {@code TestEventBusThatThrowsException} and {@code TestMultiThreadedEventBusThatThrowsException} */ public class TestEventBusPostWithException extends SetupTestEventBusPostWithException { @BeforeSuite(groups = "fast") public void beforeSuite() { busSetup(); } @Test(groups = "fast") public void testThrowFirstExceptionFromSubscribersV1() { final MyEvent event = new MyEvent(UUID.randomUUID(), "A"); try { eventBus.postWithException(event); Assert.fail(); } catch (final EventBusException e) { Assert.assertTrue(e.getCause() instanceof InvocationTargetException); Assert.assertTrue(e.getCause().getCause() instanceof RuntimeException); Assert.assertEquals(e.getCause().getCause().getMessage(), Subscriber.exceptionMarker("A")); } checkEventsSeen(subscriberA); checkEventsSeen(subscriberB, event); } @Test(groups = "fast") public void testThrowFirstExceptionFromSubscribersV2() { final MyEvent event = new MyEvent(UUID.randomUUID(), "B"); try { eventBus.postWithException(event); Assert.fail(); } catch (final EventBusException e) { Assert.assertTrue(e.getCause() instanceof InvocationTargetException); Assert.assertTrue(e.getCause().getCause() instanceof RuntimeException); Assert.assertEquals(e.getCause().getCause().getMessage(), Subscriber.exceptionMarker("B")); } checkEventsSeen(subscriberA, event); checkEventsSeen(subscriberB); } @Test(groups = "fast") public void testThrowFirstExceptionFromSubscribersV3() { final MyEvent event = new MyEvent(UUID.randomUUID(), "A", "B"); try { eventBus.postWithException(event); Assert.fail(); } catch (final EventBusException e) { Assert.assertTrue(e.getCause() instanceof InvocationTargetException); Assert.assertTrue(e.getCause().getCause() instanceof RuntimeException); // The second exception won't be seen Assert.assertEquals(e.getCause().getCause().getMessage(), Subscriber.exceptionMarker("A")); } checkEventsSeen(subscriberA); checkEventsSeen(subscriberB); } // Make sure to use a large enough invocationCount so that threads are re-used @Test(groups = "fast", threadPoolSize = 25, invocationCount = 100, description = "Check that postWithException is thread safe") public void testThrowFirstExceptionMultithreaded() { final int n = rand.nextInt(10000) + 1; final String subscriberMarker = n % 2 == 0 ? "A" : "B"; final MyEvent event = new MyEvent(UUID.randomUUID(), subscriberMarker); try { eventBus.postWithException(event); Assert.fail(); } catch (final EventBusException e) { Assert.assertTrue(e.getCause() instanceof InvocationTargetException); Assert.assertTrue(e.getCause().getCause() instanceof RuntimeException); Assert.assertEquals(e.getCause().getCause().getMessage(), Subscriber.exceptionMarker(subscriberMarker)); } if ("A".equals(subscriberMarker)) { checkEventsSeen(subscriberA); checkEventsSeen(subscriberB, event); } else { checkEventsSeen(subscriberA, event); checkEventsSeen(subscriberB); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/eventbus/TestEventBus.java
utils/src/test/java/org/killbill/commons/eventbus/TestEventBus.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * Test case for {@link EventBus}. * * @author Cliff Biffle */ public class TestEventBus { private static final String EVENT = "Hello"; private static final String BUS_IDENTIFIER = "test-bus"; private EventBus bus; @BeforeMethod(groups = "fast", alwaysRun = true) protected void setUp() { bus = new EventBus(BUS_IDENTIFIER); } @Test(groups = "fast") public void testBasicCatcherDistribution() { final StringCatcher catcher = new StringCatcher(); bus.register(catcher); bus.post(EVENT); final List<String> events = catcher.getEvents(); Assert.assertEquals(events.size(), 1, "Only one event should be delivered."); Assert.assertEquals(events.get(0), EVENT, "Correct string should be delivered."); } /** * Tests that events are distributed to any subscribers to their type or any supertype, including * interfaces and superclasses. * * <p>Also checks delivery ordering in such cases. */ @Test(groups = "fast") public void testPolymorphicDistribution() { // Three catchers for related types String, Object, and Comparable<?>. // String isa Object // String isa Comparable<?> // Comparable<?> isa Object final StringCatcher stringCatcher = new StringCatcher(); final List<Object> objectEvents = new ArrayList<>(); final Object objCatcher = new Object() { @SuppressWarnings("unused") @Subscribe public void eat(final Object food) { objectEvents.add(food); } }; final List<Comparable<?>> compEvents = new ArrayList<>(); final Object compCatcher = new Object() { @SuppressWarnings("unused") @Subscribe public void eat(final Comparable<?> food) { compEvents.add(food); } }; bus.register(stringCatcher); bus.register(objCatcher); bus.register(compCatcher); // Two additional event types: Object and Comparable<?> (played by Integer) final Object objEvent = new Object(); final Object compEvent = 6; bus.post(EVENT); bus.post(objEvent); bus.post(compEvent); // Check the StringCatcher... final List<String> stringEvents = stringCatcher.getEvents(); Assert.assertEquals(stringEvents.size(), 1, "Only one String should be delivered."); Assert.assertEquals(stringEvents.get(0), EVENT, "Correct string should be delivered."); // Check the Catcher<Object>... Assert.assertEquals(objectEvents.size(), 3, "Three Objects should be delivered."); Assert.assertEquals(objectEvents.get(0), EVENT, "String fixture must be first object delivered."); Assert.assertEquals(objectEvents.get(1), objEvent, "Object fixture must be second object delivered."); Assert.assertEquals(objectEvents.get(2), compEvent, "Comparable fixture must be third object delivered."); // Check the Catcher<Comparable<?>>... Assert.assertEquals(compEvents.size(), 2, "Two Comparable<?>s should be delivered."); Assert.assertEquals(compEvents.get(0), EVENT, "String fixture must be first comparable delivered."); Assert.assertEquals(compEvents.get(1), compEvent, "Comparable fixture must be second comparable delivered."); } @Test(groups = "fast") public void testSubscriberThrowsException() throws Exception { final RecordingSubscriberExceptionHandler handler = new RecordingSubscriberExceptionHandler(); final EventBus eventBus = new EventBus(handler); final RuntimeException exception = new RuntimeException("but culottes have a tendency to ride up!"); final Object subscriber = new Object() { @Subscribe public void throwExceptionOn(final String ignored) { throw exception; } }; eventBus.register(subscriber); eventBus.post(EVENT); Assert.assertEquals(handler.exception, exception, "Cause should be available."); Assert.assertEquals(handler.context.getEventBus(), eventBus, "EventBus should be available."); Assert.assertEquals(handler.context.getEvent(), EVENT, "Event should be available."); Assert.assertEquals(handler.context.getSubscriber(), subscriber, "Subscriber should be available."); Assert.assertEquals(handler.context.getSubscriberMethod(), subscriber.getClass().getMethod("throwExceptionOn", String.class), "Method should be available."); } @Test(groups = "fast") public void testSubscriberThrowsExceptionHandlerThrowsException() { final EventBus eventBus = new EventBus( new SubscriberExceptionHandler() { @Override public void handleException(final Throwable exception, final SubscriberExceptionContext context) { throw new RuntimeException(); } }); final Object subscriber = new Object() { @Subscribe public void throwExceptionOn(final String ignored) { throw new RuntimeException(); } }; eventBus.register(subscriber); try { eventBus.post(EVENT); } catch (final RuntimeException e) { Assert.fail("Exception should not be thrown: " + e); } } @Test(groups = "fast") public void testDeadEventForwarding() { final GhostCatcher catcher = new GhostCatcher(); bus.register(catcher); // A String -- an event for which noone has registered. bus.post(EVENT); final List<DeadEvent> events = catcher.getEvents(); Assert.assertEquals(events.size(), 1, "One dead event should be delivered."); Assert.assertEquals(events.get(0).getEvent(), EVENT, "The dead event should wrap the original event."); } @Test(groups = "fast") public void testDeadEventPosting() { final GhostCatcher catcher = new GhostCatcher(); bus.register(catcher); bus.post(new DeadEvent(this, EVENT)); final List<DeadEvent> events = catcher.getEvents(); Assert.assertEquals(events.size(), 1, "The explicit DeadEvent should be delivered."); Assert.assertEquals(events.get(0).getEvent(), EVENT, "The dead event must not be re-wrapped."); } @Test(groups = "fast") public void testMissingSubscribe() { bus.register(new Object()); } @Test(groups = "fast") public void testUnregister() { final StringCatcher catcher1 = new StringCatcher(); final StringCatcher catcher2 = new StringCatcher(); try { bus.unregister(catcher1); Assert.fail("Attempting to unregister an unregistered object succeeded"); } catch (final IllegalArgumentException expected) { // OK. } bus.register(catcher1); bus.post(EVENT); bus.register(catcher2); bus.post(EVENT); final Collection<String> expectedEvents = new ArrayList<>(); expectedEvents.add(EVENT); expectedEvents.add(EVENT); Assert.assertEquals(catcher1.getEvents(), expectedEvents, "Two correct events should be delivered."); Assert.assertEquals(catcher2.getEvents(), List.of(EVENT), "One correct event should be delivered."); bus.unregister(catcher1); bus.post(EVENT); Assert.assertEquals(catcher1.getEvents(), expectedEvents, "Shouldn't catch any more events when unregistered."); Assert.assertEquals(catcher2.getEvents(), expectedEvents, "Two correct events should be delivered."); try { bus.unregister(catcher1); Assert.fail("Attempting to unregister an unregistered object succeeded"); } catch (final IllegalArgumentException expected) { // OK. } bus.unregister(catcher2); bus.post(EVENT); Assert.assertEquals(catcher1.getEvents(), expectedEvents, "Shouldn't catch any more events when unregistered."); Assert.assertEquals(catcher2.getEvents(), expectedEvents, "Shouldn't catch any more events when unregistered."); } // NOTE: This test will always pass if register() is thread-safe but may also // pass if it isn't, though this is unlikely. @Test(groups = "fast") public void testRegisterThreadSafety() throws Exception { final List<StringCatcher> catchers = new CopyOnWriteArrayList<>(); final List<Future<?>> futures = new ArrayList<>(); final ExecutorService executor = Executors.newFixedThreadPool(10); final int numberOfCatchers = 10000; for (int i = 0; i < numberOfCatchers; i++) { futures.add(executor.submit(new Registrator(bus, catchers))); } for (int i = 0; i < numberOfCatchers; i++) { futures.get(i).get(); } Assert.assertEquals(catchers.size(), numberOfCatchers, "Unexpected number of catchers in the list"); bus.post(EVENT); final List<String> expectedEvents = List.of(EVENT); for (final StringCatcher catcher : catchers) { Assert.assertEquals(catcher.getEvents(), expectedEvents, "One of the registered catchers did not receive an event."); } } @Test(groups = "fast") public void testToString() { final EventBus eventBus = new EventBus("a b ; - \" < > / \\ €"); Assert.assertEquals(eventBus.toString(), "EventBus {identifier='a b ; - \" < > / \\ €'}"); } /** * Tests that bridge methods are not subscribed to events. In Java 8, annotations are included on * the bridge method in addition to the original method, which causes both the original and bridge * methods to be subscribed (since both are annotated @Subscribe) without specifically checking * for bridge methods. */ @Test(groups = "fast") public void testRegistrationWithBridgeMethod() { final AtomicInteger calls = new AtomicInteger(); bus.register( new Callback<String>() { @Subscribe @Override public void call(final String s) { calls.incrementAndGet(); } }); bus.post("hello"); Assert.assertEquals(1, calls.get()); } @Test(groups = "fast") public void testPrimitiveSubscribeFails() { class SubscribesToPrimitive { @Subscribe public void toInt(final int ignored) {} } try { bus.register(new SubscribesToPrimitive()); Assert.fail("should have thrown"); } catch (final IllegalArgumentException expected) { } } /** Records thrown exception information. */ private static final class RecordingSubscriberExceptionHandler implements SubscriberExceptionHandler { public SubscriberExceptionContext context; public Throwable exception; @Override public void handleException(final Throwable exception, final SubscriberExceptionContext context) { this.exception = exception; this.context = context; } } /** Runnable which registers a StringCatcher on an event bus and adds it to a list. */ private static class Registrator implements Runnable { private final EventBus bus; private final List<StringCatcher> catchers; Registrator(final EventBus bus, final List<StringCatcher> catchers) { this.bus = bus; this.catchers = catchers; } @Override public void run() { final StringCatcher catcher = new StringCatcher(); bus.register(catcher); catchers.add(catcher); } } /** * A collector for DeadEvents. * * @author cbiffle */ public static class GhostCatcher { private final List<DeadEvent> events = new ArrayList<>(); @Subscribe public void ohNoesIHaveDied(final DeadEvent event) { events.add(event); } public List<DeadEvent> getEvents() { return events; } } private interface Callback<T> { void call(T t); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/test/java/org/killbill/commons/eventbus/SetupTestEventBusPostWithException.java
utils/src/test/java/org/killbill/commons/eventbus/SetupTestEventBusPostWithException.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.UUID; import org.testng.Assert; class SetupTestEventBusPostWithException { static final Random rand = new Random(); EventBus eventBus; Subscriber subscriberA; Subscriber subscriberB; void busSetup() { eventBus = new EventBus("testing"); subscriberA = new SubscriberA(); eventBus.register(subscriberA); subscriberB = new SubscriberB(); eventBus.register(subscriberB); } void checkEventsSeen(final Subscriber subscriber, final MyEvent... events) { final long threadId = Thread.currentThread().getId(); Collection<MyEvent> myEvents = subscriber.events.get(threadId); if (myEvents != null && !myEvents.isEmpty()) { subscriber.events.put(threadId, Collections.emptySet()); } else { myEvents = Collections.emptyList(); } Assert.assertEquals(myEvents.size(), events.length); int i = 0; for (final MyEvent myEvent : myEvents) { Assert.assertSame(myEvent, events[i]); i++; } } abstract static class Subscriber { /** * Originally, {@code events} instantiation is as follows: * final Multimap<Long, MyEvent> events = Multimaps.synchronizedMultimap(HashMultimap.<Long, MyEvent>create()); * * We can change this using {@link org.killbill.commons.utils.collect.MultiValueMap}, and add new method * {@code #removeAll()} that needed in {@code #checkEventsSeen()} above. * * The problem is, guava's HashMultimap doesn't allow duplicate values, so the behaviour quite different from * our {@link org.killbill.commons.utils.collect.MultiValueHashMap} and causing test fails. Thus, we just use * simple map here. */ final Map<Long, Set<MyEvent>> events = Collections.synchronizedMap(new HashMap<>()); static String exceptionMarker(final String id) { return String.format("%s-%s", Thread.currentThread().getId(), id); } void maybeThrow(final MyEvent event, final String id) { if (event.exceptionThrowerIds.contains(id)) { throw new RuntimeException(exceptionMarker(id)); } } } protected static final class SubscriberA extends Subscriber { @Subscribe public void onEvent(final MyEvent event) { maybeThrow(event, "A"); events.put(Thread.currentThread().getId(), Set.of(event)); } } protected static final class SubscriberB extends Subscriber { @Subscribe public void onEvent(final MyEvent event) { maybeThrow(event, "B"); events.put(Thread.currentThread().getId(), Set.of(event)); } } protected static final class MyEvent { private final UUID id; private final Set<String> exceptionThrowerIds; MyEvent(final UUID id, final String... exceptionThrowerIds) { this.id = id; this.exceptionThrowerIds = Set.of(exceptionThrowerIds); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final MyEvent myEvent = (MyEvent) o; return Objects.equals(id, myEvent.id); } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/Primitives.java
utils/src/main/java/org/killbill/commons/utils/Primitives.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * Verbatim copy to guava's Primitives (v.31.0.1). <a href="https://github.com/killbill/killbill/issues/1615">See more</a> * about this. */ public final class Primitives { /** A map from primitive types to their corresponding wrapper types. */ private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER_TYPE; static { final Map<Class<?>, Class<?>> primToWrap = new LinkedHashMap<>(16); final Map<Class<?>, Class<?>> wrapToPrim = new LinkedHashMap<>(16); add(primToWrap, wrapToPrim, boolean.class, Boolean.class); add(primToWrap, wrapToPrim, byte.class, Byte.class); add(primToWrap, wrapToPrim, char.class, Character.class); add(primToWrap, wrapToPrim, double.class, Double.class); add(primToWrap, wrapToPrim, float.class, Float.class); add(primToWrap, wrapToPrim, int.class, Integer.class); add(primToWrap, wrapToPrim, long.class, Long.class); add(primToWrap, wrapToPrim, short.class, Short.class); add(primToWrap, wrapToPrim, void.class, Void.class); PRIMITIVE_TO_WRAPPER_TYPE = Collections.unmodifiableMap(primToWrap); } private static void add(final Map<Class<?>, Class<?>> forward, final Map<Class<?>, Class<?>> backward, final Class<?> key, final Class<?> value) { forward.put(key, value); backward.put(value, key); } /** * Returns the corresponding wrapper type of {@code type} if it is a primitive type; otherwise * returns {@code type} itself. Idempotent. * * <pre> * wrap(int.class) == Integer.class * wrap(Integer.class) == Integer.class * wrap(String.class) == String.class * </pre> */ public static <T> Class<T> wrap(final Class<T> type) { Preconditions.checkNotNull(type); // cast is safe: long.class and Long.class are both of type Class<Long> @SuppressWarnings("unchecked") final Class<T> wrapped = (Class<T>) PRIMITIVE_TO_WRAPPER_TYPE.get(type); return (wrapped == null) ? type : wrapped; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/TypeToken.java
utils/src/main/java/org/killbill/commons/utils/TypeToken.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils; import java.util.LinkedHashSet; import java.util.Set; /** * (At the time of writing), "TypeToken" name chosen because this class try to mimic Guava's TypeToken behavior. */ public final class TypeToken { /** * Mimic the same behavior of Guava's {@code TypeToken.of(clazz).getTypes().rawTypes()}. */ public static Set<Class<?>> getRawTypes(final Class<?> clazz) { final Set<Class<?>> result = new LinkedHashSet<>(); result.add(clazz); result.addAll(getInterfaces(clazz)); Class<?> superClass = clazz.getSuperclass(); while (superClass != null) { result.addAll(getRawTypes(superClass)); superClass = superClass.getSuperclass(); } return result; } static Set<Class<?>> getInterfaces(final Class<?> clazz) { final Set<Class<?>> result = new LinkedHashSet<>(); Set<Class<?>> interfaces = Set.of(clazz.getInterfaces()); while (!interfaces.isEmpty()) { result.addAll(interfaces); for (final Class<?> anInterface : interfaces) { interfaces = Set.of(anInterface.getInterfaces()); result.addAll(interfaces); } } return result; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/StandardSystemProperty.java
utils/src/main/java/org/killbill/commons/utils/StandardSystemProperty.java
/* * Copyright (C) 2012 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils; import javax.annotation.CheckForNull; public enum StandardSystemProperty { /** Java Runtime Environment version. */ JAVA_VERSION("java.version"), /** Java Runtime Environment vendor. */ JAVA_VENDOR("java.vendor"), /** Java vendor URL. */ JAVA_VENDOR_URL("java.vendor.url"), /** Java installation directory. */ JAVA_HOME("java.home"), /** Java Virtual Machine specification version. */ JAVA_VM_SPECIFICATION_VERSION("java.vm.specification.version"), /** Java Virtual Machine specification vendor. */ JAVA_VM_SPECIFICATION_VENDOR("java.vm.specification.vendor"), /** Java Virtual Machine specification name. */ JAVA_VM_SPECIFICATION_NAME("java.vm.specification.name"), /** Java Virtual Machine implementation version. */ JAVA_VM_VERSION("java.vm.version"), /** Java Virtual Machine implementation vendor. */ JAVA_VM_VENDOR("java.vm.vendor"), /** Java Virtual Machine implementation name. */ JAVA_VM_NAME("java.vm.name"), /** Java Runtime Environment specification version. */ JAVA_SPECIFICATION_VERSION("java.specification.version"), /** Java Runtime Environment specification vendor. */ JAVA_SPECIFICATION_VENDOR("java.specification.vendor"), /** Java Runtime Environment specification name. */ JAVA_SPECIFICATION_NAME("java.specification.name"), /** Java class format version number. */ JAVA_CLASS_VERSION("java.class.version"), /** Java class path. */ JAVA_CLASS_PATH("java.class.path"), /** List of paths to search when loading libraries. */ JAVA_LIBRARY_PATH("java.library.path"), /** Default temp file path. */ JAVA_IO_TMPDIR("java.io.tmpdir"), /** Name of JIT compiler to use. */ JAVA_COMPILER("java.compiler"), /** * Path of extension directory or directories. * * @deprecated This property was <a * href="https://openjdk.java.net/jeps/220#Removed:-The-extension-mechanism">deprecated</a> in * Java 8 and removed in Java 9. We do not plan to remove this API from Guava, but if you are * using it, it is probably not doing what you want. */ @Deprecated JAVA_EXT_DIRS("java.ext.dirs"), /** Operating system name. */ OS_NAME("os.name"), /** Operating system architecture. */ OS_ARCH("os.arch"), /** Operating system version. */ OS_VERSION("os.version"), /** File separator ("/" on UNIX). */ FILE_SEPARATOR("file.separator"), /** Path separator (":" on UNIX). */ PATH_SEPARATOR("path.separator"), /** Line separator ("\n" on UNIX). */ LINE_SEPARATOR("line.separator"), /** User's account name. */ USER_NAME("user.name"), /** User's home directory. */ USER_HOME("user.home"), /** User's current working directory. */ USER_DIR("user.dir"); private final String key; StandardSystemProperty(String key) { this.key = key; } /** Returns the key used to lookup this system property. */ public String key() { return key; } /** * Returns the current value for this system property by delegating to {@link * System#getProperty(String)}. * * <p>The value returned by this method is non-null except in rare circumstances: * * <ul> * <li>{@link #JAVA_EXT_DIRS} was deprecated in Java 8 and removed in Java 9. We have not * confirmed whether it is available under older versions. * <li>{@link #JAVA_COMPILER}, while still listed as required as of Java 15, is typically not * available even under older version. * <li>Any property may be cleared through APIs like {@link System#clearProperty}. * <li>Unusual environments like GWT may have their own special handling of system properties. * </ul> * * <p>Note that {@code StandardSystemProperty} does not provide constants for more recently added * properties, including: * * <ul> * <li>{@code java.vendor.version} (added in Java 11, listed as optional as of Java 13) * <li>{@code jdk.module.*} (added in Java 9, optional) * </ul> */ @CheckForNull public String value() { return System.getProperty(key); } /** Returns a string representation of this system property. */ @Override public String toString() { return key() + "=" + value(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/Preconditions.java
utils/src/main/java/org/killbill/commons/utils/Preconditions.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Verbatim copy to guava's Joiner (v.31.0.1). See https://github.com/killbill/killbill/issues/1615 */ public final class Preconditions { private static final Logger logger = LoggerFactory.getLogger(Preconditions.class); /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @throws IllegalStateException if {@code expression} is false */ public static void checkState(final boolean expression, @CheckForNull final Object errorMessage) { if (!expression) { throw new IllegalStateException(String.valueOf(errorMessage)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in * square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @throws IllegalStateException if {@code expression} is false */ public static void checkState(final boolean expression, final String errorMessageTemplate, final Object... errorMessageArgs) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in * square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(@CheckForNull final T reference, final String errorMessageTemplate, @CheckForNull @Nullable final Object... errorMessageArgs) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, errorMessageArgs)); } return reference; } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. */ public static void checkState(final boolean b, final String errorMessageTemplate, @CheckForNull final Object p1) { if (!b) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(final T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(@CheckForNull final T reference, @CheckForNull final Object errorMessage) { if (reference == null) { throw new NullPointerException(String.valueOf(errorMessage)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. */ public static <T> T checkNotNull(@CheckForNull final T obj, final String errorMessageTemplate, @CheckForNull final Object p1) { if (obj == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1)); } return obj; } private static String lenientFormat(@CheckForNull String template, @CheckForNull Object... args) { template = String.valueOf(template); // null -> "null" if (args == null) { args = new Object[] {"(Object[])null"}; } else { for (int i = 0; i < args.length; i++) { args[i] = lenientToString(args[i]); } } // start substituting the arguments into the '%s' placeholders final StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { final int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template, templateStart, placeholderStart); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template, templateStart, template.length()); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append(']'); } return builder.toString(); } private static String lenientToString(@CheckForNull final Object o) { if (o == null) { return "null"; } try { return o.toString(); } catch (final Exception e) { final String objectToString = o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o)); logger.warn("Exception during lenientFormat for {}, {}", objectToString, e); return "<" + objectToString + " threw " + e.getClass().getName() + ">"; } } /** * <p>This method is DEPRECATED, to encourage user put message in precondition. See * <a href="https://github.com/killbill/killbill/pull/1687#discussion_r869565378">this discussion</a>.</p> * * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @throws IllegalStateException if {@code expression} is false */ @Deprecated public static void checkState(final boolean expression) { if (!expression) { throw new IllegalStateException(); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument(final boolean b, final String errorMessageTemplate, final Object p1, final int p2) { if (!b) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument(final boolean b, final String errorMessageTemplate, final Object p1, final Object p2, final Object p3) { if (!b) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2, p3)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in * square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(final boolean expression, final String errorMessageTemplate, final Object... errorMessageArgs) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, errorMessageArgs)); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/Strings.java
utils/src/main/java/org/killbill/commons/utils/Strings.java
/* * Copyright (C) 2021 Apache Software Foundation * Copyright (C) 2010 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.CheckForNull; /** * Verbatim copy to guava's Strings (v.31.0.1). <a href="https://github.com/killbill/killbill/issues/1615">See more</a> * about this. */ public final class Strings { public static boolean isNullOrEmpty(final String string) { return string == null || string.isEmpty(); } /** * Returns the given string if it is nonempty; {@code null} otherwise. * * @param string the string to test and possibly return * @return {@code string} itself if it is nonempty; {@code null} if it is empty or null */ public static String emptyToNull(final String string) { return isNullOrEmpty(string) ? null : string; } /** * Do what {@link String#split(String)} do, additionally filter empty/blank string and trim it. * A replacement for Guava's <pre>Splitter.on(',').omitEmptyStrings().trimResults();</pre> */ public static List<String> split(final String string, final String separator) { if (isNullOrEmpty(string)) { return Collections.emptyList(); } return Stream.of(string.split(separator)) .filter(s -> !s.isBlank()) .map(String::trim) .collect(Collectors.toUnmodifiableList()); } /** * Returns the given string if it is non-null; the empty string otherwise. * * @param string the string to test and possibly return * @return {@code string} itself if it is non-null; {@code ""} if it is null */ public static String nullToEmpty(@CheckForNull final String string) { return (string == null) ? "" : string; } /** * Return true if {@code str} contains upper-case. */ public static boolean containsUpperCase(final String str) { if (isNullOrEmpty(str)) { return false; } return !str.equals(str.toLowerCase()); } /** * Convert string to camel case, based on {@code delimiter}. Taken from apache common-text * <a href="https://raw.githubusercontent.com/apache/commons-text/master/src/main/java/org/apache/commons/text/CaseUtils.java">CaseUtils</a> */ public static String toCamelCase(String str, final boolean capitalizeFirstLetter, final char... delimiters) { if (str == null || str.isBlank()) { return str; } str = str.toLowerCase(); final int strLen = str.length(); final int[] newCodePoints = new int[strLen]; int outOffset = 0; final Set<Integer> delimiterSet = toDelimiterSet(delimiters); boolean capitalizeNext = capitalizeFirstLetter; for (int index = 0; index < strLen; ) { final int codePoint = str.codePointAt(index); if (delimiterSet.contains(codePoint)) { capitalizeNext = outOffset != 0; index += Character.charCount(codePoint); } else if (capitalizeNext || outOffset == 0 && capitalizeFirstLetter) { final int titleCaseCodePoint = Character.toTitleCase(codePoint); newCodePoints[outOffset++] = titleCaseCodePoint; index += Character.charCount(titleCaseCodePoint); capitalizeNext = false; } else { newCodePoints[outOffset++] = codePoint; index += Character.charCount(codePoint); } } return new String(newCodePoints, 0, outOffset); } private static Set<Integer> toDelimiterSet(final char[] delimiters) { final Set<Integer> delimiterHashSet = new HashSet<>(); delimiterHashSet.add(Character.codePointAt(new char[]{' '}, 0)); if (delimiters == null || delimiters.length == 0) { return delimiterHashSet; } for (int index = 0; index < delimiters.length; index++) { delimiterHashSet.add(Character.codePointAt(delimiters, index)); } return delimiterHashSet; } /** * Replace string from camel case to snake case, eg: "thisIsASentence" to "this_is_a_sentence". */ // https://stackoverflow.com/a/57632022 public static String toSnakeCase(final String str) { final StringBuilder result = new StringBuilder(); boolean lastUppercase = false; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); final char lastEntry = i == 0 ? 'X' : result.charAt(result.length() - 1); // ch == ' ' || ch == '_' || ch == '-' || ch == '.' if (ch == '_') { lastUppercase = false; if (lastEntry == '_') { continue; } else { ch = '_'; } } else if (Character.isUpperCase(ch)) { ch = Character.toLowerCase(ch); // is start? if (i > 0) { if (lastUppercase) { // test if end of acronym if (i + 1 < str.length()) { char next = str.charAt(i + 1); if (!Character.isUpperCase(next) && Character.isAlphabetic(next)) { // end of acronym if (lastEntry != '_') { result.append('_'); } } else { result.append('_'); } } } else { // last was lowercase, insert _ if (lastEntry != '_') { result.append('_'); } } } lastUppercase = true; } else { lastUppercase = false; } result.append(ch); } return result.toString(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/Joiner.java
utils/src/main/java/org/killbill/commons/utils/Joiner.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils; import java.io.IOException; import java.util.AbstractList; import java.util.Iterator; import javax.annotation.CheckForNull; import static java.util.Objects.requireNonNull; /** * Verbatim copy to guava's Joiner (v.31.0.1). See https://github.com/killbill/killbill/issues/1615 */ public final class Joiner { /** Returns a joiner which automatically places {@code separator} between consecutive elements. */ public static Joiner on(final String separator) { return new Joiner(separator); } /** Returns a joiner which automatically places {@code separator} between consecutive elements. */ public static Joiner on(final char separator) { return new Joiner(String.valueOf(separator)); } private final String separator; private Joiner(final String separator) { this.separator = Preconditions.checkNotNull(separator); } /** * Returns a string containing the string representation of each of {@code parts}, using the * previously configured separator between each. */ public String join(final Iterable<?> parts) { return join(parts.iterator()); } /** * Returns a string containing the string representation of each of {@code parts}, using the * previously configured separator between each. * * @since 11.0 */ public String join(final Iterator<?> parts) { return appendTo(new StringBuilder(), parts).toString(); } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code builder}. * * @since 11.0 */ public StringBuilder appendTo(final StringBuilder builder, final Iterator<?> parts) { try { appendTo((Appendable) builder, parts); } catch (final IOException impossible) { throw new AssertionError(impossible); } return builder; } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code appendable}. * * @since 11.0 */ public <A extends Appendable> A appendTo(final A appendable, final Iterator<?> parts) throws IOException { Preconditions.checkNotNull(appendable); if (parts.hasNext()) { appendable.append(toString(parts.next())); while (parts.hasNext()) { appendable.append(separator); appendable.append(toString(parts.next())); } } return appendable; } CharSequence toString(final Object part) { requireNonNull(part); return (part instanceof CharSequence) ? (CharSequence) part : part.toString(); } /** * Returns a string containing the string representation of each argument, using the previously * configured separator between each. */ public String join(@CheckForNull final Object first, @CheckForNull final Object second, final Object... rest) { return join(iterable(first, second, rest)); } /** * See Guava's {@code Joiner#iterable(first, second, rest)} */ private static Iterable<Object> iterable(final Object first, final Object second, final Object[] rest) { Preconditions.checkNotNull(rest); return new AbstractList<Object>() { @Override public int size() { return rest.length + 2; } @Override @CheckForNull public Object get(final int index) { switch (index) { case 0: return first; case 1: return second; default: return rest[index - 2]; } } }; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/MapJoiner.java
utils/src/main/java/org/killbill/commons/utils/MapJoiner.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * Replacement of Guava's {@code Joiner.MapJoiner}. */ public final class MapJoiner { private final String separator; private final String keyValueSeparator; public MapJoiner(final String separator, final String keyValueSeparator) { this.separator = separator; this.keyValueSeparator = keyValueSeparator; } public String join(final Map<?, ?> map) { final StringBuilder sb = new StringBuilder(); final Iterator<? extends Entry<?, ?>> iterator = map.entrySet().iterator(); if (iterator.hasNext()) { final Map.Entry<?, ?> entry = iterator.next(); if (isEntryKeyExist(entry)) { sb.append(entry.getKey()); sb.append(separator); sb.append(entry.getValue()); } while (iterator.hasNext()) { final Map.Entry<?, ?> e = iterator.next(); if (sb.length() != 0) { sb.append(keyValueSeparator); } if (isEntryKeyExist(e)) { sb.append(e.getKey()); sb.append(separator); sb.append(e.getValue()); } } } return sb.toString(); } private boolean isEntryKeyExist(final Entry<?, ?> entry) { final Object o = entry.getKey(); if (o == null) { return false; } final String s = o.toString(); return !(s.isEmpty() && s.isBlank()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/cache/DefaultSynchronizedCache.java
utils/src/main/java/org/killbill/commons/utils/cache/DefaultSynchronizedCache.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.cache; import java.util.function.Function; /** * {@link DefaultCache} that synchronize {@link Cache} methods call. */ public class DefaultSynchronizedCache<K, V> extends DefaultCache<K, V> implements Cache<K, V> { public DefaultSynchronizedCache(final int maxSize) { super(maxSize); } public DefaultSynchronizedCache(final Function<K, V> cacheLoader) { super(cacheLoader); } public DefaultSynchronizedCache(final int maxSize, final long timeoutInSecond, final Function<K, V> cacheLoader) { super(maxSize, timeoutInSecond, cacheLoader); } @Override public V get(final K key) { synchronized (this) { return super.get(key); } } @Override public V getOrLoad(final K key, final Function<K, V> loader) { synchronized (this) { return super.getOrLoad(key, loader); } } @Override public void put(final K key, final V value) { synchronized (this) { super.put(key, value); } } @Override public void invalidate(final K key) { synchronized (this) { super.invalidate(key); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/cache/Cache.java
utils/src/main/java/org/killbill/commons/utils/cache/Cache.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.cache; import java.util.function.Function; public interface Cache <K, V> { /** * Get the cache value, or null if no value associated with key. Value returned by this method depends on * implementation logic. * * @param key to load the value * @return cache value, or null * @throws NullPointerException is key is null */ V get(K key); /** * Get or load the cache. Note that value returned from loader parameter will not update cache. * * Implementation may decide to load it first from any other source/loader before loader parameter called. * * @param key to load the value * @param loader algorithm to load a value if, not exist in cache * @return cache value, or depends on {@code loader} algorithm * @throws NullPointerException if key or loader is null */ V getOrLoad(K key, Function<K, V> loader); /** * Add value to cache. * @param key key * @param value value * @throws NullPointerException if key or value is null */ void put(K key, V value); /** * Remove the cache based on its key. * @param key to remove. * @throws NullPointerException if key is null */ void invalidate(K key); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/cache/TimedValue.java
utils/src/main/java/org/killbill/commons/utils/cache/TimedValue.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.cache; import java.util.Objects; import org.killbill.commons.utils.Preconditions; class TimedValue<V> { private final long expireTime; private final V value; /** * @param timeoutMillis timeout in millisecond */ TimedValue(final long timeoutMillis, final V value) { this.expireTime = System.currentTimeMillis() + timeoutMillis; this.value = Preconditions.checkNotNull(value, "TimedValue.value cannot be null"); } boolean isTimeout() { return System.currentTimeMillis() >= expireTime; } V getValue() { return value; } @Override public String toString() { return "TimedValue {" + "expireTime=" + expireTime + ", value=" + value + '}'; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final TimedValue<?> that = (TimedValue<?>) o; return expireTime == that.expireTime && value.equals(that.value); } @Override public int hashCode() { return Objects.hash(expireTime, value); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/cache/DefaultCache.java
utils/src/main/java/org/killbill/commons/utils/cache/DefaultCache.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.cache; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.function.Function; import org.killbill.commons.utils.Preconditions; import org.killbill.commons.utils.annotation.VisibleForTesting; /** * <p> * Default {@link Cache} implementation, that provide ability to: * <ol> * <li>Add maxSize to the cache. If more entry added, the oldest entry get removed automatically</li> * <li> * Add lazy-loading capability with {@code cacheLoader} parameter in constructor. This {@code cacheLoader} * will be called if {@link #get(Object)} return {@code null}. {@code cacheLoader} also will take precedence * over loader defined in {@link #getOrLoad(Object, Function)}. * </li> * <li>Add timout (similar to expire-after-write in Guava and Caffeine) capability</li> * </ol> * </p> * @param <K> cache key * @param <V> cache value */ public class DefaultCache<K, V> implements Cache<K, V> { public static final long NO_TIMEOUT = 0; @VisibleForTesting final Map<K, TimedValue<V>> map; private final long timeoutMillis; private final Function<K, V> cacheLoader; /** * Create cache with maximum entry size, without any timout (live forever) and no cache loader. * * @param maxSize max entry that should be existed in cache. */ public DefaultCache(final int maxSize) { this(maxSize, NO_TIMEOUT, noCacheLoader()); } /** * Create cache with {@code maxSize = Integer.MAX_VALUE}, {@code timeoutInSecond = NO_TIMEOUT}, and with supplied * {@code cacheLoader}. * * @param cacheLoader cache loader. Use {@link #noCacheLoader()} to make this cache should not attempt to load * anything if value is null. */ public DefaultCache(final Function<K, V> cacheLoader) { this(Integer.MAX_VALUE, NO_TIMEOUT, cacheLoader); } /** * Create cache with maximum entry size, timeout (in second), and cacheLoader capability. * * @param maxSize cache maximum size. If more entry added, the oldest entry get removed automatically. * @param timeoutInSecond cache entry expire time. Entry will eventually be removed after specifics time defined * here. Use {@link DefaultCache#NO_TIMEOUT} to make entry live forever. * @param cacheLoader cache loader. Use {@link #noCacheLoader()} to make this cache should not attempt to load * anything if value is null. */ public DefaultCache(final int maxSize, final long timeoutInSecond, final Function<K, V> cacheLoader) { Preconditions.checkArgument(maxSize > 0, "cache maxSize should > 0"); Preconditions.checkArgument(timeoutInSecond >= 0, "cache timeoutInSecond should >= 0"); this.timeoutMillis = timeoutInSecond * 1_000; this.cacheLoader = Preconditions.checkNotNull(cacheLoader, "cacheLoader is null. Use DefaultCache#noCacheLoader() to create a cache without loader"); map = new LinkedHashMap<>(16, 0.75f, true) { @Override protected boolean removeEldestEntry(final Entry<K, TimedValue<V>> eldest) { return size() > maxSize; } }; } /** * Create {@link DefaultCache} without any loader. */ public static <K1, V1> Function<K1, V1> noCacheLoader() { return k1 -> null; } protected boolean isTimeoutEnabled() { return timeoutMillis > 0L; } protected boolean isCacheLoaderExist() { return !noCacheLoader().equals(cacheLoader); } protected void evictExpireEntry(final K key) { if (isTimeoutEnabled()) { final TimedValue<V> value = map.get(key); if (value != null && value.isTimeout()) { invalidate(key); } } } @Override public V get(final K key) { Preconditions.checkNotNull(key, "Cannot #get() cache with key = null"); evictExpireEntry(key); final TimedValue<V> timedValue = map.get(key); if (timedValue != null) { return timedValue.getValue(); } else if (isCacheLoaderExist()) { final V value = cacheLoader.apply(key); if (value != null) { put(key, value); } return value; } else { return null; } } @Override public V getOrLoad(final K key, final Function<K, V> loader) { Preconditions.checkNotNull(loader, "loader parameter in #getOrLoad() is null"); final V value = get(key); return value == null ? loader.apply(key) : value; } @Override public void put(final K key, final V value) { Preconditions.checkNotNull(key, "key in #put() is null"); Preconditions.checkNotNull(value, "value in #put() is null"); map.put(key, new TimedValue<>(timeoutMillis, value)); } @Override public void invalidate(final K key) { Preconditions.checkNotNull(key, "Cannot invalidate. Cache with null key is not allowed"); map.remove(key); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/math/Ints.java
utils/src/main/java/org/killbill/commons/utils/math/Ints.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.math; public final class Ints { /** * Returns the {@code int} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code int} if it is in the range of the {@code int} type, * {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too * small */ public static int saturatedCast(final long value) { if (value > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (value < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } return (int) value; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/math/IntMath.java
utils/src/main/java/org/killbill/commons/utils/math/IntMath.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.math; public final class IntMath { /** * Returns the product of {@code a} and {@code b} unless it would overflow or underflow in which * case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively. */ public static int saturatedMultiply(final int a, final int b) { return Ints.saturatedCast((long) a * b); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/net/HttpHeaders.java
utils/src/main/java/org/killbill/commons/utils/net/HttpHeaders.java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.killbill.commons.utils.net; /** * Verbatim-copy of Guava's {@code HttpHeaders}. */ public final class HttpHeaders { private HttpHeaders() {} // HTTP Request and Response header fields /** The HTTP {@code Cache-Control} header field name. */ public static final String CACHE_CONTROL = "Cache-Control"; /** The HTTP {@code Content-Length} header field name. */ public static final String CONTENT_LENGTH = "Content-Length"; /** The HTTP {@code Content-Type} header field name. */ public static final String CONTENT_TYPE = "Content-Type"; /** The HTTP {@code Date} header field name. */ public static final String DATE = "Date"; /** The HTTP {@code Pragma} header field name. */ public static final String PRAGMA = "Pragma"; /** The HTTP {@code Via} header field name. */ public static final String VIA = "Via"; /** The HTTP {@code Warning} header field name. */ public static final String WARNING = "Warning"; // HTTP Request header fields /** The HTTP {@code Accept} header field name. */ public static final String ACCEPT = "Accept"; /** The HTTP {@code Accept-Charset} header field name. */ public static final String ACCEPT_CHARSET = "Accept-Charset"; /** The HTTP {@code Accept-Encoding} header field name. */ public static final String ACCEPT_ENCODING = "Accept-Encoding"; /** The HTTP {@code Accept-Language} header field name. */ public static final String ACCEPT_LANGUAGE = "Accept-Language"; /** The HTTP {@code Access-Control-Request-Headers} header field name. */ public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers"; /** The HTTP {@code Access-Control-Request-Method} header field name. */ public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method"; /** The HTTP {@code Authorization} header field name. */ public static final String AUTHORIZATION = "Authorization"; /** The HTTP {@code Connection} header field name. */ public static final String CONNECTION = "Connection"; /** The HTTP {@code Cookie} header field name. */ public static final String COOKIE = "Cookie"; /** * The HTTP <a href="https://fetch.spec.whatwg.org/#cross-origin-resource-policy-header">{@code * Cross-Origin-Resource-Policy}</a> header field name. * * @since 28.0 */ public static final String CROSS_ORIGIN_RESOURCE_POLICY = "Cross-Origin-Resource-Policy"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc8470">{@code Early-Data}</a> header field * name. * * @since 27.0 */ public static final String EARLY_DATA = "Early-Data"; /** The HTTP {@code Expect} header field name. */ public static final String EXPECT = "Expect"; /** The HTTP {@code From} header field name. */ public static final String FROM = "From"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc7239">{@code Forwarded}</a> header field name. * * @since 20.0 */ public static final String FORWARDED = "Forwarded"; /** * The HTTP {@code Follow-Only-When-Prerender-Shown} header field name. * * @since 17.0 */ public static final String FOLLOW_ONLY_WHEN_PRERENDER_SHOWN = "Follow-Only-When-Prerender-Shown"; /** The HTTP {@code Host} header field name. */ public static final String HOST = "Host"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc7540#section-3.2.1">{@code HTTP2-Settings} * </a> header field name. * * @since 24.0 */ public static final String HTTP2_SETTINGS = "HTTP2-Settings"; /** The HTTP {@code If-Match} header field name. */ public static final String IF_MATCH = "If-Match"; /** The HTTP {@code If-Modified-Since} header field name. */ public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; /** The HTTP {@code If-None-Match} header field name. */ public static final String IF_NONE_MATCH = "If-None-Match"; /** The HTTP {@code If-Range} header field name. */ public static final String IF_RANGE = "If-Range"; /** The HTTP {@code If-Unmodified-Since} header field name. */ public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; /** The HTTP {@code Last-Event-ID} header field name. */ public static final String LAST_EVENT_ID = "Last-Event-ID"; /** The HTTP {@code Max-Forwards} header field name. */ public static final String MAX_FORWARDS = "Max-Forwards"; /** The HTTP {@code Origin} header field name. */ public static final String ORIGIN = "Origin"; /** * The HTTP <a href="https://github.com/WICG/origin-isolation">{@code Origin-Isolation}</a> header * field name. * * @since 30.1 */ public static final String ORIGIN_ISOLATION = "Origin-Isolation"; /** The HTTP {@code Proxy-Authorization} header field name. */ public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; /** The HTTP {@code Range} header field name. */ public static final String RANGE = "Range"; /** The HTTP {@code Referer} header field name. */ public static final String REFERER = "Referer"; /** * The HTTP <a href="https://www.w3.org/TR/referrer-policy/">{@code Referrer-Policy}</a> header * field name. * * @since 23.4 */ public static final String REFERRER_POLICY = "Referrer-Policy"; /** * Values for the <a href="https://www.w3.org/TR/referrer-policy/">{@code Referrer-Policy}</a> * header. * * @since 23.4 */ public static final class ReferrerPolicyValues { private ReferrerPolicyValues() {} public static final String NO_REFERRER = "no-referrer"; public static final String NO_REFFERER_WHEN_DOWNGRADE = "no-referrer-when-downgrade"; public static final String SAME_ORIGIN = "same-origin"; public static final String ORIGIN = "origin"; public static final String STRICT_ORIGIN = "strict-origin"; public static final String ORIGIN_WHEN_CROSS_ORIGIN = "origin-when-cross-origin"; public static final String STRICT_ORIGIN_WHEN_CROSS_ORIGIN = "strict-origin-when-cross-origin"; public static final String UNSAFE_URL = "unsafe-url"; } /** * The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code * Service-Worker}</a> header field name. * * @since 20.0 */ public static final String SERVICE_WORKER = "Service-Worker"; /** The HTTP {@code TE} header field name. */ public static final String TE = "TE"; /** The HTTP {@code Upgrade} header field name. */ public static final String UPGRADE = "Upgrade"; /** * The HTTP <a href="https://w3c.github.io/webappsec-upgrade-insecure-requests/#preference">{@code * Upgrade-Insecure-Requests}</a> header field name. * * @since 28.1 */ public static final String UPGRADE_INSECURE_REQUESTS = "Upgrade-Insecure-Requests"; /** The HTTP {@code User-Agent} header field name. */ public static final String USER_AGENT = "User-Agent"; // HTTP Response header fields /** The HTTP {@code Accept-Ranges} header field name. */ public static final String ACCEPT_RANGES = "Accept-Ranges"; /** The HTTP {@code Access-Control-Allow-Headers} header field name. */ public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"; /** The HTTP {@code Access-Control-Allow-Methods} header field name. */ public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"; /** The HTTP {@code Access-Control-Allow-Origin} header field name. */ public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; /** * The HTTP <a href="https://wicg.github.io/private-network-access/#headers">{@code * Access-Control-Allow-Private-Network}</a> header field name. * * @since 31.1 */ public static final String ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK = "Access-Control-Allow-Private-Network"; /** The HTTP {@code Access-Control-Allow-Credentials} header field name. */ public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"; /** The HTTP {@code Access-Control-Expose-Headers} header field name. */ public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers"; /** The HTTP {@code Access-Control-Max-Age} header field name. */ public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age"; /** The HTTP {@code Age} header field name. */ public static final String AGE = "Age"; /** The HTTP {@code Allow} header field name. */ public static final String ALLOW = "Allow"; /** The HTTP {@code Content-Disposition} header field name. */ public static final String CONTENT_DISPOSITION = "Content-Disposition"; /** The HTTP {@code Content-Encoding} header field name. */ public static final String CONTENT_ENCODING = "Content-Encoding"; /** The HTTP {@code Content-Language} header field name. */ public static final String CONTENT_LANGUAGE = "Content-Language"; /** The HTTP {@code Content-Location} header field name. */ public static final String CONTENT_LOCATION = "Content-Location"; /** The HTTP {@code Content-MD5} header field name. */ public static final String CONTENT_MD5 = "Content-MD5"; /** The HTTP {@code Content-Range} header field name. */ public static final String CONTENT_RANGE = "Content-Range"; /** * The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-header-field">{@code * Content-Security-Policy}</a> header field name. * * @since 15.0 */ public static final String CONTENT_SECURITY_POLICY = "Content-Security-Policy"; /** * The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-report-only-header-field"> * {@code Content-Security-Policy-Report-Only}</a> header field name. * * @since 15.0 */ public static final String CONTENT_SECURITY_POLICY_REPORT_ONLY = "Content-Security-Policy-Report-Only"; /** * The HTTP nonstandard {@code X-Content-Security-Policy} header field name. It was introduced in * <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Firefox until * version 23 and the Internet Explorer version 10. Please, use {@link #CONTENT_SECURITY_POLICY} * to pass the CSP. * * @since 20.0 */ public static final String X_CONTENT_SECURITY_POLICY = "X-Content-Security-Policy"; /** * The HTTP nonstandard {@code X-Content-Security-Policy-Report-Only} header field name. It was * introduced in <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the * Firefox until version 23 and the Internet Explorer version 10. Please, use {@link * #CONTENT_SECURITY_POLICY_REPORT_ONLY} to pass the CSP. * * @since 20.0 */ public static final String X_CONTENT_SECURITY_POLICY_REPORT_ONLY = "X-Content-Security-Policy-Report-Only"; /** * The HTTP nonstandard {@code X-WebKit-CSP} header field name. It was introduced in <a * href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Chrome until * version 25. Please, use {@link #CONTENT_SECURITY_POLICY} to pass the CSP. * * @since 20.0 */ public static final String X_WEBKIT_CSP = "X-WebKit-CSP"; /** * The HTTP nonstandard {@code X-WebKit-CSP-Report-Only} header field name. It was introduced in * <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Chrome until * version 25. Please, use {@link #CONTENT_SECURITY_POLICY_REPORT_ONLY} to pass the CSP. * * @since 20.0 */ public static final String X_WEBKIT_CSP_REPORT_ONLY = "X-WebKit-CSP-Report-Only"; /** * The HTTP <a href="https://wicg.github.io/cross-origin-embedder-policy/#COEP">{@code * Cross-Origin-Embedder-Policy}</a> header field name. * * @since 30.0 */ public static final String CROSS_ORIGIN_EMBEDDER_POLICY = "Cross-Origin-Embedder-Policy"; /** * The HTTP <a href="https://wicg.github.io/cross-origin-embedder-policy/#COEP-RO">{@code * Cross-Origin-Embedder-Policy-Report-Only}</a> header field name. * * @since 30.0 */ public static final String CROSS_ORIGIN_EMBEDDER_POLICY_REPORT_ONLY = "Cross-Origin-Embedder-Policy-Report-Only"; /** * The HTTP Cross-Origin-Opener-Policy header field name. * * @since 28.2 */ public static final String CROSS_ORIGIN_OPENER_POLICY = "Cross-Origin-Opener-Policy"; /** The HTTP {@code ETag} header field name. */ public static final String ETAG = "ETag"; /** The HTTP {@code Expires} header field name. */ public static final String EXPIRES = "Expires"; /** The HTTP {@code Last-Modified} header field name. */ public static final String LAST_MODIFIED = "Last-Modified"; /** The HTTP {@code Link} header field name. */ public static final String LINK = "Link"; /** The HTTP {@code Location} header field name. */ public static final String LOCATION = "Location"; /** * The HTTP {@code Keep-Alive} header field name. * * @since 31.0 */ public static final String KEEP_ALIVE = "Keep-Alive"; /** * The HTTP <a href="https://googlechrome.github.io/OriginTrials/#header">{@code Origin-Trial}</a> * header field name. * * @since 27.1 */ public static final String ORIGIN_TRIAL = "Origin-Trial"; /** The HTTP {@code P3P} header field name. Limited browser support. */ public static final String P3P = "P3P"; /** The HTTP {@code Proxy-Authenticate} header field name. */ public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; /** The HTTP {@code Refresh} header field name. Non-standard header supported by most browsers. */ public static final String REFRESH = "Refresh"; /** * The HTTP <a href="https://www.w3.org/TR/reporting/">{@code Report-To}</a> header field name. * * @since 27.1 */ public static final String REPORT_TO = "Report-To"; /** The HTTP {@code Retry-After} header field name. */ public static final String RETRY_AFTER = "Retry-After"; /** The HTTP {@code Server} header field name. */ public static final String SERVER = "Server"; /** * The HTTP <a href="https://www.w3.org/TR/server-timing/">{@code Server-Timing}</a> header field * name. * * @since 23.6 */ public static final String SERVER_TIMING = "Server-Timing"; /** * The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code * Service-Worker-Allowed}</a> header field name. * * @since 20.0 */ public static final String SERVICE_WORKER_ALLOWED = "Service-Worker-Allowed"; /** The HTTP {@code Set-Cookie} header field name. */ public static final String SET_COOKIE = "Set-Cookie"; /** The HTTP {@code Set-Cookie2} header field name. */ public static final String SET_COOKIE2 = "Set-Cookie2"; /** * The HTTP <a href="http://goo.gl/Dxx19N">{@code SourceMap}</a> header field name. * * @since 27.1 */ public static final String SOURCE_MAP = "SourceMap"; /** * The HTTP <a href="http://tools.ietf.org/html/rfc6797#section-6.1">{@code * Strict-Transport-Security}</a> header field name. * * @since 15.0 */ public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; /** * The HTTP <a href="http://www.w3.org/TR/resource-timing/#cross-origin-resources">{@code * Timing-Allow-Origin}</a> header field name. * * @since 15.0 */ public static final String TIMING_ALLOW_ORIGIN = "Timing-Allow-Origin"; /** The HTTP {@code Trailer} header field name. */ public static final String TRAILER = "Trailer"; /** The HTTP {@code Transfer-Encoding} header field name. */ public static final String TRANSFER_ENCODING = "Transfer-Encoding"; /** The HTTP {@code Vary} header field name. */ public static final String VARY = "Vary"; /** The HTTP {@code WWW-Authenticate} header field name. */ public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; // Common, non-standard HTTP header fields /** The HTTP {@code DNT} header field name. */ public static final String DNT = "DNT"; /** The HTTP {@code X-Content-Type-Options} header field name. */ public static final String X_CONTENT_TYPE_OPTIONS = "X-Content-Type-Options"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-IP}</a> header field name. Header used for VAST requests to provide the IP address of * the device on whose behalf the request is being made. * * @since 31.0 */ public static final String X_DEVICE_IP = "X-Device-IP"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Referer}</a> header field name. Header used for VAST requests to provide the {@link * #REFERER} header value that the on-behalf-of client would have used when making a request * itself. * * @since 31.0 */ public static final String X_DEVICE_REFERER = "X-Device-Referer"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Accept-Language}</a> header field name. Header used for VAST requests to provide the * {@link #ACCEPT_LANGUAGE} header value that the on-behalf-of client would have used when making * a request itself. * * @since 31.0 */ public static final String X_DEVICE_ACCEPT_LANGUAGE = "X-Device-Accept-Language"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Requested-With}</a> header field name. Header used for VAST requests to provide the * {@link #X_REQUESTED_WITH} header value that the on-behalf-of client would have used when making * a request itself. * * @since 31.0 */ public static final String X_DEVICE_REQUESTED_WITH = "X-Device-Requested-With"; /** The HTTP {@code X-Do-Not-Track} header field name. */ public static final String X_DO_NOT_TRACK = "X-Do-Not-Track"; /** The HTTP {@code X-Forwarded-For} header field name (superseded by {@code Forwarded}). */ public static final String X_FORWARDED_FOR = "X-Forwarded-For"; /** The HTTP {@code X-Forwarded-Proto} header field name. */ public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto"; /** * The HTTP <a href="http://goo.gl/lQirAH">{@code X-Forwarded-Host}</a> header field name. * * @since 20.0 */ public static final String X_FORWARDED_HOST = "X-Forwarded-Host"; /** * The HTTP <a href="http://goo.gl/YtV2at">{@code X-Forwarded-Port}</a> header field name. * * @since 20.0 */ public static final String X_FORWARDED_PORT = "X-Forwarded-Port"; /** The HTTP {@code X-Frame-Options} header field name. */ public static final String X_FRAME_OPTIONS = "X-Frame-Options"; /** The HTTP {@code X-Powered-By} header field name. */ public static final String X_POWERED_BY = "X-Powered-By"; /** * The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning">{@code * Public-Key-Pins}</a> header field name. * * @since 15.0 */ public static final String PUBLIC_KEY_PINS = "Public-Key-Pins"; /** * The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning">{@code * Public-Key-Pins-Report-Only}</a> header field name. * * @since 15.0 */ public static final String PUBLIC_KEY_PINS_REPORT_ONLY = "Public-Key-Pins-Report-Only"; /** * The HTTP {@code X-Request-ID} header field name. * * @since 30.1 */ public static final String X_REQUEST_ID = "X-Request-ID"; /** The HTTP {@code X-Requested-With} header field name. */ public static final String X_REQUESTED_WITH = "X-Requested-With"; /** The HTTP {@code X-User-IP} header field name. */ public static final String X_USER_IP = "X-User-IP"; /** * The HTTP <a href="https://goo.gl/VKpXxa">{@code X-Download-Options}</a> header field name. * * <p>When the new X-Download-Options header is present with the value {@code noopen}, the user is * prevented from opening a file download directly; instead, they must first save the file * locally. * * @since 24.1 */ public static final String X_DOWNLOAD_OPTIONS = "X-Download-Options"; /** The HTTP {@code X-XSS-Protection} header field name. */ public static final String X_XSS_PROTECTION = "X-XSS-Protection"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control">{@code * X-DNS-Prefetch-Control}</a> header controls DNS prefetch behavior. Value can be "on" or "off". * By default, DNS prefetching is "on" for HTTP pages and "off" for HTTPS pages. */ public static final String X_DNS_PREFETCH_CONTROL = "X-DNS-Prefetch-Control"; /** * The HTTP <a href="http://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing"> * {@code Ping-From}</a> header field name. * * @since 19.0 */ public static final String PING_FROM = "Ping-From"; /** * The HTTP <a href="http://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing"> * {@code Ping-To}</a> header field name. * * @since 19.0 */ public static final String PING_TO = "Ping-To"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * Purpose}</a> header field name. * * @since 28.0 */ public static final String PURPOSE = "Purpose"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * X-Purpose}</a> header field name. * * @since 28.0 */ public static final String X_PURPOSE = "X-Purpose"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * X-Moz}</a> header field name. * * @since 28.0 */ public static final String X_MOZ = "X-Moz"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Device-Memory">{@code * Device-Memory}</a> header field name. * * @since 31.0 */ public static final String DEVICE_MEMORY = "Device-Memory"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Downlink">{@code * Downlink}</a> header field name. * * @since 31.0 */ public static final String DOWNLINK = "Downlink"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ECT">{@code * ECT}</a> header field name. * * @since 31.0 */ public static final String ECT = "ECT"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/RTT">{@code * RTT}</a> header field name. * * @since 31.0 */ public static final String RTT = "RTT"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Save-Data">{@code * Save-Data}</a> header field name. * * @since 31.0 */ public static final String SAVE_DATA = "Save-Data"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Viewport-Width">{@code * Viewport-Width}</a> header field name. * * @since 31.0 */ public static final String VIEWPORT_WIDTH = "Viewport-Width"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Width">{@code * Width}</a> header field name. * * @since 31.0 */ public static final String WIDTH = "Width"; /** * The HTTP <a href="https://www.w3.org/TR/permissions-policy-1/">{@code Permissions-Policy}</a> * header field name. * * @since 31.0 */ public static final String PERMISSIONS_POLICY = "Permissions-Policy"; /** * The HTTP <a * href="https://wicg.github.io/user-preference-media-features-headers/#sec-ch-prefers-color-scheme">{@code * Sec-CH-Prefers-Color-Scheme}</a> header field name. * * <p>This header is experimental. * * @since 31.0 */ public static final String SEC_CH_PREFERS_COLOR_SCHEME = "Sec-CH-Prefers-Color-Scheme"; /** * The HTTP <a * href="https://www.rfc-editor.org/rfc/rfc8942#name-the-accept-ch-response-head">{@code * Accept-CH}</a> header field name. * * @since 31.0 */ public static final String ACCEPT_CH = "Accept-CH"; /** * The HTTP <a * href="https://datatracker.ietf.org/doc/html/draft-davidben-http-client-hint-reliability-03.txt#section-3">{@code * Critical-CH}</a> header field name. * * @since 31.0 */ public static final String CRITICAL_CH = "Critical-CH"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua">{@code Sec-CH-UA}</a> * header field name. * * @since 30.0 */ public static final String SEC_CH_UA = "Sec-CH-UA"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-arch">{@code * Sec-CH-UA-Arch}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_ARCH = "Sec-CH-UA-Arch"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-model">{@code * Sec-CH-UA-Model}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_MODEL = "Sec-CH-UA-Model"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform">{@code * Sec-CH-UA-Platform}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_PLATFORM = "Sec-CH-UA-Platform"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform-version">{@code * Sec-CH-UA-Platform-Version}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_PLATFORM_VERSION = "Sec-CH-UA-Platform-Version"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-full-version">{@code * Sec-CH-UA-Full-Version}</a> header field name. * * @deprecated Prefer {@link #SEC_CH_UA_FULL_VERSION_LIST}. * @since 30.0 */ @Deprecated public static final String SEC_CH_UA_FULL_VERSION = "Sec-CH-UA-Full-Version"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-full-version-list">{@code * Sec-CH-UA-Full-Version}</a> header field name. * * @since 31.1 */ public static final String SEC_CH_UA_FULL_VERSION_LIST = "Sec-CH-UA-Full-Version-List"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-mobile">{@code * Sec-CH-UA-Mobile}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_MOBILE = "Sec-CH-UA-Mobile"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-bitness">{@code * Sec-CH-UA-Bitness}</a> header field name. * * @since 31.0 */ public static final String SEC_CH_UA_BITNESS = "Sec-CH-UA-Bitness"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Dest}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_DEST = "Sec-Fetch-Dest"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Mode}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_MODE = "Sec-Fetch-Mode"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Site}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_SITE = "Sec-Fetch-Site"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-User}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_USER = "Sec-Fetch-User"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Metadata}</a> * header field name. * * @since 26.0 */ public static final String SEC_METADATA = "Sec-Metadata"; /** * The HTTP <a href="https://tools.ietf.org/html/draft-ietf-tokbind-https">{@code * Sec-Token-Binding}</a> header field name. * * @since 25.1 */ public static final String SEC_TOKEN_BINDING = "Sec-Token-Binding"; /** * The HTTP <a href="https://tools.ietf.org/html/draft-ietf-tokbind-ttrp">{@code * Sec-Provided-Token-Binding-ID}</a> header field name. * * @since 25.1 */ public static final String SEC_PROVIDED_TOKEN_BINDING_ID = "Sec-Provided-Token-Binding-ID"; /** * The HTTP <a href="https://tools.ietf.org/html/draft-ietf-tokbind-ttrp">{@code * Sec-Referred-Token-Binding-ID}</a> header field name. * * @since 25.1 */ public static final String SEC_REFERRED_TOKEN_BINDING_ID = "Sec-Referred-Token-Binding-ID"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc6455">{@code Sec-WebSocket-Accept}</a> header * field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_ACCEPT = "Sec-WebSocket-Accept"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc6455">{@code Sec-WebSocket-Extensions}</a> * header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_EXTENSIONS = "Sec-WebSocket-Extensions"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc6455">{@code Sec-WebSocket-Key}</a> header * field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_KEY = "Sec-WebSocket-Key"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc6455">{@code Sec-WebSocket-Protocol}</a> * header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_PROTOCOL = "Sec-WebSocket-Protocol"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc6455">{@code Sec-WebSocket-Version}</a> header * field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_VERSION = "Sec-WebSocket-Version"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc8586">{@code CDN-Loop}</a> header field name. * * @since 28.0 */ public static final String CDN_LOOP = "CDN-Loop"; }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/concurrent/DirectExecutor.java
utils/src/main/java/org/killbill/commons/utils/concurrent/DirectExecutor.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.concurrent; import java.util.concurrent.Executor; /** * Direct replacement of Guava {@code DirectExecutor}. Placed in {@code utils} instead of {@code concurrent} module * to avoid circular dependency. * * An {@link Executor} that runs each task in the thread that invokes {@link Executor#execute}. */ public enum DirectExecutor implements Executor { INSTANCE; @Override public void execute(final Runnable command) { command.run(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/concurrent/ThreadFactoryBuilder.java
utils/src/main/java/org/killbill/commons/utils/concurrent/ThreadFactoryBuilder.java
/* * Copyright (C) 2010 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.concurrent; import java.lang.Thread.UncaughtExceptionHandler; import java.util.Locale; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; import javax.annotation.CheckForNull; import org.killbill.commons.utils.Preconditions; import static java.util.Objects.requireNonNull; /** * Verbatim copy of Guava's {@code ThreadFactoryBuilder}. Placed here instead of in {@code concurrent} module to avoid * circular dependency. * * A ThreadFactory builder, providing any combination of these features: * * <ul> * <li>whether threads should be marked as {@linkplain Thread#setDaemon daemon} threads * <li>a {@linkplain ThreadFactoryBuilder#setNameFormat naming format} * <li>a {@linkplain Thread#setPriority thread priority} * <li>an {@linkplain Thread#setUncaughtExceptionHandler uncaught exception handler} * <li>a {@linkplain ThreadFactory#newThread backing thread factory} * </ul> * * <p>If no backing thread factory is provided, a default backing thread factory is used as if by * calling {@code setThreadFactory(}{@link Executors#defaultThreadFactory()}{@code )}. * * @author Kurt Alfred Kluever * @since 4.0 */ public final class ThreadFactoryBuilder { @CheckForNull private String nameFormat = null; @CheckForNull private Boolean daemon = null; @CheckForNull private Integer priority = null; @CheckForNull private UncaughtExceptionHandler uncaughtExceptionHandler = null; @CheckForNull private ThreadFactory backingThreadFactory = null; /** Creates a new {@link ThreadFactory} builder. */ public ThreadFactoryBuilder() {} /** * Sets the naming format to use when naming threads ({@link Thread#setName}) which are created * with this ThreadFactory. * * @param nameFormat a {@link String#format(String, Object...)}-compatible format String, to which * a unique integer (0, 1, etc.) will be supplied as the single parameter. This integer will * be unique to the built instance of the ThreadFactory and will be assigned sequentially. For * example, {@code "rpc-pool-%d"} will generate thread names like {@code "rpc-pool-0"}, {@code * "rpc-pool-1"}, {@code "rpc-pool-2"}, etc. * @return this for the builder pattern */ public ThreadFactoryBuilder setNameFormat(final String nameFormat) { this.nameFormat = nameFormat; return this; } /** * Sets daemon or not for new threads created with this ThreadFactory. * * @param daemon whether or not new Threads created with this ThreadFactory will be daemon threads * @return this for the builder pattern */ public ThreadFactoryBuilder setDaemon(final boolean daemon) { this.daemon = daemon; return this; } /** * Sets the priority for new threads created with this ThreadFactory. * * @param priority the priority for new Threads created with this ThreadFactory * @return this for the builder pattern */ public ThreadFactoryBuilder setPriority(final int priority) { // Thread#setPriority() already checks for validity. These error messages // are nicer though and will fail-fast. Preconditions.checkArgument(priority >= Thread.MIN_PRIORITY, "Thread priority (%s) must be >= %s", priority, Thread.MIN_PRIORITY); Preconditions.checkArgument(priority <= Thread.MAX_PRIORITY, "Thread priority (%s) must be <= %s", priority, Thread.MAX_PRIORITY); this.priority = priority; return this; } /** * Sets the {@link UncaughtExceptionHandler} for new threads created with this ThreadFactory. * * @param uncaughtExceptionHandler the uncaught exception handler for new Threads created with * this ThreadFactory * @return this for the builder pattern */ public ThreadFactoryBuilder setUncaughtExceptionHandler(final UncaughtExceptionHandler uncaughtExceptionHandler) { this.uncaughtExceptionHandler = Preconditions.checkNotNull(uncaughtExceptionHandler); return this; } /** * Sets the backing {@link ThreadFactory} for new threads created with this ThreadFactory. Threads * will be created by invoking #newThread(Runnable) on this backing {@link ThreadFactory}. * * @param backingThreadFactory the backing {@link ThreadFactory} which will be delegated to during * thread creation. * @return this for the builder pattern */ public ThreadFactoryBuilder setThreadFactory(final ThreadFactory backingThreadFactory) { this.backingThreadFactory = Preconditions.checkNotNull(backingThreadFactory); return this; } /** * Returns a new thread factory using the options supplied during the building process. After * building, it is still possible to change the options used to build the ThreadFactory and/or * build again. State is not shared amongst built instances. * * @return the fully constructed {@link ThreadFactory} */ public ThreadFactory build() { return doBuild(this); } // Split out so that the anonymous ThreadFactory can't contain a reference back to the builder. // At least, I assume that's why. TODO(cpovirk): Check, and maybe add a test for this. private static ThreadFactory doBuild(final ThreadFactoryBuilder builder) { final String nameFormat = builder.nameFormat; final Boolean daemon = builder.daemon; final Integer priority = builder.priority; final UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler; final ThreadFactory backingThreadFactory = builder.backingThreadFactory != null ? builder.backingThreadFactory : Executors.defaultThreadFactory(); final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null; return new ThreadFactory() { @Override public Thread newThread(final Runnable runnable) { final Thread thread = backingThreadFactory.newThread(runnable); if (nameFormat != null) { // requireNonNull is safe because we create `count` if (and only if) we have a nameFormat. thread.setName(format(nameFormat, requireNonNull(count).getAndIncrement())); } if (daemon != null) { thread.setDaemon(daemon); } if (priority != null) { thread.setPriority(priority); } if (uncaughtExceptionHandler != null) { thread.setUncaughtExceptionHandler(uncaughtExceptionHandler); } return thread; } }; } private static String format(final String format, final Object... args) { return String.format(Locale.ROOT, format, args); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/reflect/AbstractInvocationHandler.java
utils/src/main/java/org/killbill/commons/utils/reflect/AbstractInvocationHandler.java
/* * Copyright (C) 2012 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.reflect; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import javax.annotation.CheckForNull; /** * Verbatim copy of Guava's {@code com.google.common.reflect.AbstractInvocationHandler}. * * Abstract implementation of {@link InvocationHandler} that handles {@link Object#equals}, {@link * Object#hashCode} and {@link Object#toString}. For example: * * <pre> * class Unsupported extends AbstractInvocationHandler { * protected Object handleInvocation(Object proxy, Method method, Object[] args) { * throw new UnsupportedOperationException(); * } * } * * CharSequence unsupported = Reflection.newProxy(CharSequence.class, new Unsupported()); * </pre> * * @author Ben Yu * @since 12.0 */ public abstract class AbstractInvocationHandler implements InvocationHandler { private static final Object[] NO_ARGS = {}; /** * {@inheritDoc} * * <ul> * <li>{@code proxy.hashCode()} delegates to {@code com.google.common.reflect.AbstractInvocationHandler#hashCode} * <li>{@code proxy.toString()} delegates to {@code com.google.common.reflect.AbstractInvocationHandler#toString} * <li>{@code proxy.equals(argument)} returns true if: * <ul> * <li>{@code proxy} and {@code argument} are of the same type * <li>and {@code com.google.common.reflect.AbstractInvocationHandler#equals} returns true for the {@link * InvocationHandler} of {@code argument} * </ul> * <li>other method calls are dispatched to {@link #handleInvocation}. * </ul> */ @Override @CheckForNull public final Object invoke(final Object proxy, final Method method, @CheckForNull Object[] args) throws Throwable { if (args == null) { args = NO_ARGS; } if (args.length == 0 && "hashCode".equals(method.getName())) { return hashCode(); } if (args.length == 1 && "equals".equals(method.getName()) && method.getParameterTypes()[0] == Object.class) { final Object arg = args[0]; if (arg == null) { return false; } if (proxy == arg) { return true; } return isProxyOfSameInterfaces(arg, proxy.getClass()) && equals(Proxy.getInvocationHandler(arg)); } if (args.length == 0 && "toString".equals(method.getName())) { return toString(); } return handleInvocation(proxy, method, args); } /** * {@link #invoke} delegates to this method upon any method invocation on the proxy instance, * except {@link Object#equals}, {@link Object#hashCode} and {@link Object#toString}. The result * will be returned as the proxied method's return value. * * <p>Unlike {@link #invoke}, {@code args} will never be null. When the method has no parameter, * an empty array is passed in. */ @CheckForNull protected abstract Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable; /** * By default delegates to {@link Object#equals} so instances are only equal if they are * identical. {@code proxy.equals(argument)} returns true if: * * <ul> * <li>{@code proxy} and {@code argument} are of the same type * <li>and this method returns true for the {@link InvocationHandler} of {@code argument} * </ul> * * <p>Subclasses can override this method to provide custom equality. */ @Override public boolean equals(@CheckForNull final Object obj) { return super.equals(obj); } /** * By default delegates to {@link Object#hashCode}. The dynamic proxies' {@code hashCode()} will * delegate to this method. Subclasses can override this method to provide custom equality. */ @Override public int hashCode() { return super.hashCode(); } /** * By default delegates to {@link Object#toString}. The dynamic proxies' {@code toString()} will * delegate to this method. Subclasses can override this method to provide custom string * representation for the proxies. */ @Override public String toString() { return super.toString(); } private static boolean isProxyOfSameInterfaces(final Object arg, final Class<?> proxyClass) { return proxyClass.isInstance(arg) // Equal proxy instances should mostly be instance of proxyClass // Under some edge cases (such as the proxy of JDK types serialized and then deserialized) // the proxy type may not be the same. // We first check isProxyClass() so that the common case of comparing with non-proxy objects // is efficient. || (Proxy.isProxyClass(arg.getClass()) && Arrays.equals(arg.getClass().getInterfaces(), proxyClass.getInterfaces())); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/annotation/VisibleForTesting.java
utils/src/main/java/org/killbill/commons/utils/annotation/VisibleForTesting.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.annotation; public @interface VisibleForTesting { }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/io/CharStreams.java
utils/src/main/java/org/killbill/commons/utils/io/CharStreams.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.io; import java.io.IOException; import java.io.Reader; import org.killbill.commons.utils.Preconditions; /** * Contains verbatim copy to guava's Joiner (v.31.0.1). See <a href="https://github.com/killbill/killbill/issues/1615">More</a>. */ public final class CharStreams { private static final int DEFAULT_BUF_SIZE = 0x800; /** * Reads all characters from a {@link Readable} object into a {@link String}. Does not close the {@code Readable}. * * @param r the object to read from * @return a string containing all the characters * @throws IOException if an I/O error occurs */ public static String toString(final Readable r) throws IOException { return toStringBuilder(r).toString(); } /** * Warning: Not like Guava's {@code com.google.common.io.CharStreams#toStringBuilder(Readable)}, parameter of this * method only accept instance of {@link Reader}, otherwise it will throw an Exception. Method parameter type * preserved here to make sure easier to track it back to Guava, if needed. * * Reads all characters from a {@link Readable} object into a new {@link StringBuilder} instance. Does not close * the {@code Readable}. * * @param r the object to read from * @return a {@link StringBuilder} containing all the characters * @throws IOException if an I/O error occurs */ private static StringBuilder toStringBuilder(final Readable r) throws IOException { final StringBuilder sb = new StringBuilder(); if (r instanceof Reader) { copyReaderToBuilder((Reader) r, sb); } else { throw new RuntimeException("IOUtils#toStringBuilder() parameter should be instance of java.io.Reader"); } return sb; } static long copyReaderToBuilder(final Reader from, final StringBuilder to) throws IOException { Preconditions.checkNotNull(from); Preconditions.checkNotNull(to); char[] buf = new char[DEFAULT_BUF_SIZE]; int nRead; long total = 0; while ((nRead = from.read(buf)) != -1) { to.append(buf, 0, nRead); total += nRead; } return total; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/io/Files.java
utils/src/main/java/org/killbill/commons/utils/io/Files.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.io; import java.io.File; import java.io.IOException; import java.nio.file.attribute.FileAttribute; public final class Files { /** * Do samething as {@link java.nio.file.Files#createTempDirectory(String, FileAttribute[])} with * {@link System#currentTimeMillis()} as its name. */ public static File createTempDirectory() { try { return java.nio.file.Files.createTempDirectory(String.valueOf(System.currentTimeMillis())).toFile(); } catch (final IOException e) { throw new RuntimeException("Cannot create temp directory: " + e.getMessage()); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/io/ByteStreams.java
utils/src/main/java/org/killbill/commons/utils/io/ByteStreams.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.io; import java.io.IOException; import java.io.InputStream; import java.util.ArrayDeque; import java.util.Queue; import org.killbill.commons.utils.Preconditions; import org.killbill.commons.utils.math.IntMath; /** * Contains verbatim copy to guava's Joiner (v.31.0.1). See <a href="https://github.com/killbill/killbill/issues/1615">More</a>. */ public final class ByteStreams { private static final int BUFFER_SIZE = 8192; /** Max array length on JVM. */ private static final int MAX_ARRAY_LEN = Integer.MAX_VALUE - 8; /** Large enough to never need to expand, given the geometric progression of buffer sizes. */ private static final int TO_BYTE_ARRAY_DEQUE_SIZE = 20; /** * Reads all bytes from an input stream into a byte array. Does not close the stream. * * @param in the input stream to read from * @return a byte array containing all the bytes from the stream * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(final InputStream in) throws IOException { Preconditions.checkNotNull(in); return toByteArrayInternal(in, new ArrayDeque<>(TO_BYTE_ARRAY_DEQUE_SIZE), 0); } /** * Returns a byte array containing the bytes from the buffers already in {@code bufs} (which have * a total combined length of {@code totalLen} bytes) followed by all bytes remaining in the given * input stream. */ private static byte[] toByteArrayInternal(final InputStream in, final Queue<byte[]> bufs, int totalLen) throws IOException { // Starting with an 8k buffer, double the size of each successive buffer. Buffers are retained // in a deque so that there's no copying between buffers while reading and so all of the bytes // in each new allocated buffer are available for reading from the stream. for (int bufSize = BUFFER_SIZE; totalLen < MAX_ARRAY_LEN; bufSize = IntMath.saturatedMultiply(bufSize, 2)) { final byte[] buf = new byte[Math.min(bufSize, MAX_ARRAY_LEN - totalLen)]; bufs.add(buf); int off = 0; while (off < buf.length) { // always OK to fill buf; its size plus the rest of bufs is never more than MAX_ARRAY_LEN final int r = in.read(buf, off, buf.length - off); if (r == -1) { return combineBuffers(bufs, totalLen); } off += r; totalLen += r; } } // read MAX_ARRAY_LEN bytes without seeing end of stream if (in.read() == -1) { // oh, there's the end of the stream return combineBuffers(bufs, MAX_ARRAY_LEN); } else { throw new OutOfMemoryError("input is too large to fit in a byte array"); } } private static byte[] combineBuffers(final Queue<byte[]> bufs, final int totalLen) { final byte[] result = new byte[totalLen]; int remaining = totalLen; while (remaining > 0) { final byte[] buf = bufs.remove(); final int bytesToCopy = Math.min(remaining, buf.length); final int resultOffset = totalLen - remaining; System.arraycopy(buf, 0, result, resultOffset, bytesToCopy); remaining -= bytesToCopy; } return result; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/io/IOUtils.java
utils/src/main/java/org/killbill/commons/utils/io/IOUtils.java
/* * Copyright 2010-2012 Ning, Inc. * * Ning licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.io; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.net.URL; import java.nio.charset.StandardCharsets; import org.killbill.commons.utils.Preconditions; /** * FIXME-1615: revert IOUtils to previous state. * * This class originally only contains {@link #toString(InputStream)} method. When working on 1615, this class host * several static methods from Guava's common.io package. Revert this class to */ public final class IOUtils { public static String toString(final InputStream inputStream) throws IOException { final String result; try (inputStream) { result = new String(ByteStreams.toByteArray(inputStream), StandardCharsets.UTF_8); } return result; } /** * DEPRECATED. Favor {@link ByteStreams} instead of this class. * * Reads all bytes from an input stream into a byte array. Does not close the stream. * * @param in the input stream to read from * @return a byte array containing all the bytes from the stream * @throws IOException if an I/O error occurs */ @Deprecated public static byte[] toByteArray(final InputStream in) throws IOException { Preconditions.checkNotNull(in); return ByteStreams.toByteArray(in); } // -- Verbatim copy of Guava 31.0.1 (com.google.common.io.Resources#getResource(String)) /** * DEPRECATED. Favor {@link Resources} instead of this class for easy and "backward searchability" with Guava. * * Returns a {@code URL} pointing to {@code resourceName} if the resource is found using the * {@linkplain Thread#getContextClassLoader() context class loader}. In simple environments, the * context class loader will find resources from the class path. In environments where different * threads can have different class loaders, for example app servers, the context class loader * will typically have been set to an appropriate loader for the current thread. * * <p>In the unusual case where the context class loader is null, the class loader that loaded * this class ({@code Resources}) will be used instead. * * @throws IllegalArgumentException if the resource is not found */ @Deprecated public static URL getResourceAsURL(final String resourceName) { return Resources.getResource(resourceName); } // -- Verbatim Copy of CharStreams // 2K chars (4K bytes) private static final int DEFAULT_BUF_SIZE = 0x800; /** * DEPRECATED. Favor {@link CharStreams} instead of this class for easy and "backward searchability" with Guava. * * Reads all characters from a {@link Readable} object into a {@link String}. Does not close the * {@code Readable}. * * @param r the object to read from * @return a string containing all the characters * @throws IOException if an I/O error occurs */ @Deprecated public static String toString(final Readable r) throws IOException { return toStringBuilder(r).toString(); } /** * Warning: Not like Guava's {@code com.google.common.io.CharStreams#toStringBuilder(Readable)}, * parameter of this method only accept instance of {@link Reader}, otherwise it will throw an Exception. Method * parameter type preserved here to make sure easier to track it back to Guava, if needed. * * Reads all characters from a {@link Readable} object into a new {@link StringBuilder} instance. * Does not close the {@code Readable}. * * @param r the object to read from * @return a {@link StringBuilder} containing all the characters * @throws IOException if an I/O error occurs */ private static StringBuilder toStringBuilder(final Readable r) throws IOException { final StringBuilder sb = new StringBuilder(); if (r instanceof Reader) { copyReaderToBuilder((Reader) r, sb); } else { throw new RuntimeException("IOUtils#toStringBuilder() parameter should be instance of java.io.Reader"); } return sb; } static long copyReaderToBuilder(final Reader from, final StringBuilder to) throws IOException { Preconditions.checkNotNull(from); Preconditions.checkNotNull(to); char[] buf = new char[DEFAULT_BUF_SIZE]; int nRead; long total = 0; while ((nRead = from.read(buf)) != -1) { to.append(buf, 0, nRead); total += nRead; } return total; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/io/Resources.java
utils/src/main/java/org/killbill/commons/utils/io/Resources.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.io; import java.net.URL; import java.util.Objects; import org.killbill.commons.utils.Preconditions; public final class Resources { /** * Returns a {@code URL} pointing to {@code resourceName} if the resource is found using the * {@linkplain Thread#getContextClassLoader() context class loader}. In simple environments, the * context class loader will find resources from the class path. In environments where different * threads can have different class loaders, for example app servers, the context class loader * will typically have been set to an appropriate loader for the current thread. * * <p>In the unusual case where the context class loader is null, the class loader that loaded * this class ({@code Resources}) will be used instead. * * @throws IllegalArgumentException if the resource is not found */ public static URL getResource(final String resourceName) { final ClassLoader loader = Objects.requireNonNullElse(Thread.currentThread().getContextClassLoader(), Resources.class.getClassLoader()); final URL url = loader.getResource(resourceName); Preconditions.checkArgument(url != null, "resource %s not found.", resourceName); return url; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/collect/TransformedIterator.java
utils/src/main/java/org/killbill/commons/utils/collect/TransformedIterator.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.collect; import java.util.Iterator; import org.killbill.commons.utils.Preconditions; abstract class TransformedIterator<F, T> implements Iterator<T> { final Iterator<? extends F> backingIterator; TransformedIterator(final Iterator<? extends F> backingIterator) { this.backingIterator = Preconditions.checkNotNull(backingIterator); } abstract T transform(F from); @Override public final boolean hasNext() { return backingIterator.hasNext(); } @Override public final T next() { return transform(backingIterator.next()); } @Override public final void remove() { backingIterator.remove(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/collect/ConcatenatedIterator.java
utils/src/main/java/org/killbill/commons/utils/collect/ConcatenatedIterator.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.collect; import java.util.ArrayDeque; import java.util.Collections; import java.util.Deque; import java.util.Iterator; import java.util.NoSuchElementException; import javax.annotation.CheckForNull; import org.killbill.commons.utils.Preconditions; /** * Verbatim copy of Guava ConcatenatedIterator (v.31.0.1) */ class ConcatenatedIterator<T> implements Iterator<T> { /* The last iterator to return an element. Calls to remove() go to this iterator. */ @CheckForNull private Iterator<? extends T> toRemove; /* The iterator currently returning elements. */ private Iterator<? extends T> iterator; /* * We track the "meta iterators," the iterators-of-iterators, below. Usually, topMetaIterator * is the only one in use, but if we encounter nested concatenations, we start a deque of * meta-iterators rather than letting the nesting get arbitrarily deep. This keeps each * operation O(1). */ @CheckForNull private Iterator<? extends Iterator<? extends T>> topMetaIterator; // Only becomes nonnull if we encounter nested concatenations. @CheckForNull private Deque<Iterator<? extends Iterator<? extends T>>> metaIterators; ConcatenatedIterator(final Iterator<? extends Iterator<? extends T>> metaIterator) { iterator = Collections.emptyIterator(); topMetaIterator = Preconditions.checkNotNull(metaIterator); } // Returns a nonempty meta-iterator or, if all meta-iterators are empty, null. @CheckForNull private Iterator<? extends Iterator<? extends T>> getTopMetaIterator() { while (topMetaIterator == null || !topMetaIterator.hasNext()) { if (metaIterators != null && !metaIterators.isEmpty()) { topMetaIterator = metaIterators.removeFirst(); } else { return null; } } return topMetaIterator; } @Override public boolean hasNext() { while (!Preconditions.checkNotNull(iterator).hasNext()) { // this weird checkNotNull positioning appears required by our tests, which expect // both hasNext and next to throw NPE if an input iterator is null. topMetaIterator = getTopMetaIterator(); if (topMetaIterator == null) { return false; } iterator = topMetaIterator.next(); if (iterator instanceof ConcatenatedIterator) { // Instead of taking linear time in the number of nested concatenations, unpack // them into the queue @SuppressWarnings("unchecked") final ConcatenatedIterator<T> topConcat = (ConcatenatedIterator<T>) iterator; iterator = topConcat.iterator; // topConcat.topMetaIterator, then topConcat.metaIterators, then this.topMetaIterator, // then this.metaIterators if (this.metaIterators == null) { this.metaIterators = new ArrayDeque<>(); } this.metaIterators.addFirst(this.topMetaIterator); if (topConcat.metaIterators != null) { while (!topConcat.metaIterators.isEmpty()) { Preconditions .checkNotNull(this.metaIterators) .addFirst(Preconditions.checkNotNull(topConcat.metaIterators.removeLast())); } } this.topMetaIterator = topConcat.topMetaIterator; } } return true; } @Override public T next() { if (hasNext()) { toRemove = iterator; return iterator.next(); } else { throw new NoSuchElementException(); } } @Override public void remove() { if (toRemove == null) { throw new IllegalStateException("no calls to next() since the last call to remove()"); } toRemove.remove(); toRemove = null; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/collect/Sets.java
utils/src/main/java/org/killbill/commons/utils/collect/Sets.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.collect; import java.util.Set; import java.util.stream.Collectors; import org.killbill.commons.utils.Preconditions; public final class Sets { /** * Will return a set of elements that exists in {@code set1} but not exist in {@code set2}. Both parameters cannot * be null. */ public static <E> Set<E> difference(final Set<E> set1, final Set<E> set2) { Preconditions.checkNotNull(set1, "set1 in Sets#difference() is null"); Preconditions.checkNotNull(set2, "set2 in Sets#difference() is null"); return set1.stream() .filter(element -> !set2.contains(element)) .collect(Collectors.toUnmodifiableSet()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/collect/MultiValueHashMap.java
utils/src/main/java/org/killbill/commons/utils/collect/MultiValueHashMap.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.collect; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MultiValueHashMap<K, E> extends HashMap<K, List<E>> implements MultiValueMap<K, E> { @Override public void putElement(final K key, final E... elements) { if (elements == null || elements.length == 0) { throw new IllegalArgumentException("MultiValueHashMap#putElement() contains null or empty element"); } if (super.containsKey(key)) { super.get(key).addAll(List.of(elements)); } else { super.put(key, new ArrayList<>(List.of(elements))); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/collect/Iterables.java
utils/src/main/java/org/killbill/commons/utils/collect/Iterables.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.collect; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.RandomAccess; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.killbill.commons.utils.Preconditions; /** * Contains subset of Guava's {@code com.google.common.collect.Iterables} functionality. */ public final class Iterables { /** * <p>Verbatim copy of {@code com.google.common.collect.Iterables#getLast(Iterable)}. Guava's suggestion on javadoc * to use stream's {@code <any_collection>.stream().findFirst()} sometimes not working if {@code findFirst()} * return null.</p> * * <p>Returns the first element in {@code iterable} or {@code defaultValue} if the iterable is empty. * The {@link Iterators} analog to this method is {@link Iterators#getNext}.</p> */ public static <T> T getFirst(final Iterable<? extends T> iterable, final T defaultValue) { return Iterators.getNext(iterable.iterator(), defaultValue); } /** * Verbatim copy of {@code com.google.common.collect.Iterables#getLast(Iterable)}. * * Returns the last element of {@code iterable}. If {@code iterable} is a {@link List} with {@link RandomAccess} * support, then this operation is guaranteed to be {@code O(1)}. * * @return the last element of {@code iterable} * @throws NoSuchElementException if the iterable is empty */ public static <T> T getLast(final Iterable<T> iterable) { if (iterable instanceof List) { final List<T> list = (List<T>) iterable; if (list.isEmpty()) { throw new NoSuchElementException("Cannot Iterables#getLast(iterable) on empty list"); } return list.get(list.size() - 1); } return Iterators.getLast(iterable.iterator()); } /** * Verbatim copy of {@code com.google.common.collect.Iterables#getLast(Iterable, Object)}. * * Returns the last element of {@code iterable} or {@code defaultValue} if the iterable is empty. * If {@code iterable} is a {@link List} with {@link RandomAccess} support, then this operation is * guaranteed to be {@code O(1)}. * * @param defaultValue the value to return if {@code iterable} is empty * @return the last element of {@code iterable} or the default value */ public static <T> T getLast(final Iterable<? extends T> iterable, final T defaultValue) { if (iterable instanceof Collection) { final Collection<? extends T> c = (Collection<? extends T>) iterable; if (c.isEmpty()) { return defaultValue; } else if (iterable instanceof List) { final List<? extends T> list = (List<? extends T>) iterable; return list.get(list.size() - 1); } } return Iterators.getLast(iterable.iterator(), defaultValue); } /** * Concat two or more iterable into single {@link Iterable}. * * @param iterables two or more iterable to concat * @param <T> the iterable element * @return combined iterable */ public static <T> Iterable<T> concat(final Iterable<T>... iterables) { Preconditions.checkNotNull(iterables); final List<T> result = new ArrayList<>(); for (final Iterable<T> iterable : iterables) { Preconditions.checkNotNull(iterable, "One of iterable in Iterables#concat() is null"); iterable.forEach(result::add); } return result; } /** * Convert {@link Iterable} to immutable {@link Set}. If any stream operation need to applied to iterable, use * {@link #toStream(Iterable)} instead. * * @param iterable to convert * @param <T> iterable element * @return immutable {@link Set} */ public static <T> Set<T> toUnmodifiableSet(final Iterable<? extends T> iterable) { return toStream(iterable).collect(Collectors.toUnmodifiableSet()); } /** * Convert {@link Iterable} to immutable {@link List}. If any stream operation needed, use {@link #toStream(Iterable)} * instead of this method. * * @param iterable to convert * @param <T> iterable element * @return converted iterable as immutable {@link List} */ public static <T> List<T> toUnmodifiableList(final Iterable<? extends T> iterable) { return toStream(iterable).collect(Collectors.toUnmodifiableList()); } /** * Convert {@link Iterable} to {@link List}. If any stream operation needed, use {@link #toStream(Iterable)} instead. * * @param iterable to convert * @param <T> iterable element * @return converted iterable as {@link List} */ public static <T> List<T> toList(final Iterable<? extends T> iterable) { return toStream(iterable).collect(Collectors.toList()); } /** * Convert {@link Iterable} to non-parallel {@link Stream} for further processing. * @param iterable iterable to convert * @param <E> iterable element * @return java {@link Stream} , for further processing */ public static <E> Stream<E> toStream(final Iterable<E> iterable) { Preconditions.checkNotNull(iterable); return StreamSupport.stream(iterable.spliterator(), false); } /** * Verbatim copy of {@code com.google.common.collect.Iterables#isEmpty(Iterable)}. * * Determines if the given iterable contains no elements. * * <p>There is no precise {@link Iterator} equivalent to this method, since one can only ask an iterator whether it * has any elements <i>remaining</i> (which one does using {@link Iterator#hasNext}). * * @return {@code true} if the iterable contains no elements */ public static boolean isEmpty(final Iterable<?> iterable) { if (iterable instanceof Collection) { return ((Collection<?>) iterable).isEmpty(); } return !iterable.iterator().hasNext(); } /** Returns the number of elements in {@code iterable}. */ public static int size(final Iterable<?> iterable) { return (iterable instanceof Collection) ? ((Collection<?>) iterable).size() : Iterators.size(iterable.iterator()); } /** * Returns {@code true} if {@code iterable} contains any element {@code o} for which {@code * Objects.equals(o, element)} would return {@code true}. Otherwise returns {@code false}, even in * cases where {@link Collection#contains} might throw {@link NullPointerException} or {@link * ClassCastException}. */ public static boolean contains(final Iterable<?> iterable, final Object element) { if (iterable instanceof Collection) { final Collection<?> collection = (Collection<?>) iterable; return safeContains(collection, element); } return Iterators.contains(iterable.iterator(), element); } /** * Delegates to {@link Collection#contains}. Returns {@code false} if the {@code contains} method * throws a {@code ClassCastException} or {@code NullPointerException}. */ private static boolean safeContains(final Collection<?> collection, final Object object) { Preconditions.checkNotNull(collection); Preconditions.checkNotNull(object); try { return collection.contains(object); } catch (final ClassCastException e) { return false; } } /** * Returns the single element contained in {@code iterable}. * * <p><b>Java 8 users:</b> the {@code Stream} equivalent to this method is {@code * stream.collect(MoreCollectors.onlyElement())}. * * @throws NoSuchElementException if the iterable is empty * @throws IllegalArgumentException if the iterable contains multiple elements */ public static <T extends Object> T getOnlyElement(final Iterable<T> iterable) { return Iterators.getOnlyElement(iterable.iterator()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/collect/EvictingQueue.java
utils/src/main/java/org/killbill/commons/utils/collect/EvictingQueue.java
/* * Copyright (C) 2012 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.collect; import java.util.ArrayDeque; import java.util.Collection; import java.util.Iterator; import java.util.Queue; import java.util.stream.Collectors; import org.killbill.commons.utils.Preconditions; /** * Replacement of Guava {@code EvictingQueue}, some behavior may different from original one. */ public class EvictingQueue<E> implements Queue<E> { private final int maxSize; private final Queue<E> delegate; public EvictingQueue(final int maxSize) { this.maxSize = maxSize; this.delegate = new ArrayDeque<>(); } /** * Returns the number of additional elements that this queue can accept without evicting; zero if * the queue is currently full. */ public int remainingCapacity() { return maxSize - size(); } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean contains(final Object o) { return delegate.contains(o); } @Override public Iterator<E> iterator() { return delegate.iterator(); } @Override public Object[] toArray() { return delegate.toArray(); } @Override public <T> T[] toArray(final T[] array) { return delegate.toArray(array); } @Override public boolean add(final E element) { Preconditions.checkNotNull(element); if (maxSize == 0) { return true; } if (size() == maxSize) { delegate.remove(); } delegate.add(element); return true; } @Override public boolean remove(final Object o) { return delegate.remove(o); } @Override public boolean containsAll(final Collection<?> collection) { return delegate.containsAll(collection); } // Different implementation from original EvictingQueue. @Override public boolean addAll(final Collection<? extends E> collection) { if (collection.isEmpty()) { return false; } final int size = collection.size(); if (size >= maxSize) { clear(); collection.stream() .skip(size - maxSize) .collect(Collectors.toUnmodifiableList()) .forEach(this::add); } else { collection.forEach(this::add); } return true; } @Override public boolean removeAll(final Collection<?> c) { return delegate.removeAll(c); } @Override public boolean retainAll(final Collection<?> c) { return delegate.retainAll(c); } @Override public void clear() { delegate.clear(); } @Override public boolean offer(final E e) { return add(e); } @Override public E remove() { return delegate.remove(); } @Override public E poll() { return delegate.poll(); } @Override public E element() { return delegate.element(); } @Override public E peek() { return delegate.peek(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/collect/AbstractIterator.java
utils/src/main/java/org/killbill/commons/utils/collect/AbstractIterator.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.collect; import java.util.Iterator; import java.util.NoSuchElementException; import javax.annotation.CheckForNull; import org.killbill.commons.utils.Preconditions; /** * Verbatim copy of Guava AbstractIterator (v.31.0.1). See https://github.com/killbill/killbill/issues/1615 */ public abstract class AbstractIterator<T> implements Iterator<T> { private State state = State.NOT_READY; /** Constructor for use by subclasses. */ protected AbstractIterator() {} private enum State { /** We have computed the next element and haven't returned it yet. */ READY, /** We haven't yet computed or have already returned the element. */ NOT_READY, /** We have reached the end of the data and are finished. */ DONE, /** We've suffered an exception and are kaput. */ FAILED, } @CheckForNull private T next; /** * Returns the next element. <b>Note:</b> the implementation must call {@link #endOfData()} when * there are no elements left in the iteration. Failure to do so could result in an infinite loop. * * <p>The initial invocation of {@link #hasNext()} or {@link #next()} calls this method, as does * the first invocation of {@code hasNext} or {@code next} following each successful call to * {@code next}. Once the implementation either invokes {@code endOfData} or throws an exception, * {@code computeNext} is guaranteed to never be called again. * * <p>If this method throws an exception, it will propagate outward to the {@code hasNext} or * {@code next} invocation that invoked this method. Any further attempts to use the iterator will * result in an {@link IllegalStateException}. * * <p>The implementation of this method may not invoke the {@code hasNext}, {@code next}, or * {@link #peek()} methods on this instance; if it does, an {@code IllegalStateException} will * result. * * @return the next element if there was one. If {@code endOfData} was called during execution, * the return value will be ignored. * @throws RuntimeException if any unrecoverable error happens. This exception will propagate * outward to the {@code hasNext()}, {@code next()}, or {@code peek()} invocation that invoked * this method. Any further attempts to use the iterator will result in an {@link * IllegalStateException}. */ @CheckForNull protected abstract T computeNext(); /** * Implementations of {@link #computeNext} <b>must</b> invoke this method when there are no * elements left in the iteration. * * @return {@code null}; a convenience so your {@code computeNext} implementation can use the * simple statement {@code return endOfData();} */ @CheckForNull protected final T endOfData() { state = State.DONE; return null; } @Override public final boolean hasNext() { Preconditions.checkState(state != State.FAILED, "AbstractIterator state==FAILED"); switch (state) { case DONE: return false; case READY: return true; default: } return tryToComputeNext(); } private boolean tryToComputeNext() { state = State.FAILED; // temporary pessimism next = computeNext(); if (state != State.DONE) { state = State.READY; return true; } return false; } @Override public final T next() { if (!hasNext()) { throw new NoSuchElementException(); } state = State.NOT_READY; // Safe because hasNext() ensures that tryToComputeNext() has put a T into `next`. final T result = uncheckedCastNullableTToT(next); next = null; return result; } /** * Returns the next element in the iteration without advancing the iteration, according to the * contract of {@code com.google.common.collect.PeekingIterator#peek()}. * * <p>Implementations of {@code AbstractIterator} that wish to expose this functionality should * implement {@code PeekingIterator}. */ public final T peek() { if (!hasNext()) { throw new NoSuchElementException(); } // Safe because hasNext() ensures that tryToComputeNext() has put a T into `next`. return uncheckedCastNullableTToT(next); } /** * See Guava's <code>NullnessCasts</code> javadoc. */ static <T> T uncheckedCastNullableTToT(@CheckForNull final T t) { return t; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/collect/Iterators.java
utils/src/main/java/org/killbill/commons/utils/collect/Iterators.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.collect; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Function; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.annotation.CheckForNull; import org.killbill.commons.utils.Preconditions; /** * Contains subset of Guava's {@code com.google.common.collect.Iterators} functionality. */ public final class Iterators { /** * Verbatim copy of Guava's {@code com.google.common.collect.Iterators#getNext(Iterator, Object)}. * * Returns the next element in {@code iterator} or {@code defaultValue} if the iterator is empty. */ public static <T> T getNext(final Iterator<? extends T> iterator, final T defaultValue) { return iterator.hasNext() ? iterator.next() : defaultValue; } /** * Verbatim copy of Guava's {@code com.google.common.collect.Iterators#getLast(Iterator)} * * Advances {@code iterator} to the end, returning the last element. * * @return the last element of {@code iterator} * @throws NoSuchElementException if the iterator is empty */ public static <T> T getLast(final Iterator<T> iterator) { while (true) { final T current = iterator.next(); if (!iterator.hasNext()) { return current; } } } /** * Returns a view containing the result of applying {@code function} to each element of {@code fromIterator}. * * <p>The returned iterator supports {@code remove()} if {@code fromIterator} does. After a * successful {@code remove()} call, {@code fromIterator} no longer contains the corresponding * element. */ public static <F, T> Iterator<T> transform(final Iterator<F> fromIterator, final Function<? super F, ? extends T> function) { Preconditions.checkNotNull(function); return new TransformedIterator<F, T>(fromIterator) { @Override T transform(final F from) { return function.apply(from); } }; } /** * Verbatim copy of what guava's did in {@code com.google.common.collect.ImmutableList#copyOf(Iterator)} . * * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if {@code elements} contains a null element */ public static <E> List<E> toUnmodifiableList(final Iterator<? extends E> elements) { // We special-case for 0 or 1 elements, but going further is madness. if (!elements.hasNext()) { return Collections.emptyList(); } final E first = elements.next(); if (!elements.hasNext()) { return List.of(first); } else { final List<E> result = new ArrayList<>(); result.add(first); elements.forEachRemaining(result::add); return List.copyOf(result); } } /** * Get size of {@link Iterator}. See also Guava's {@code com.google.common.collect.Iterators#size(Iterator)}. * * @param iterator to compute its size. * @return the size of this iterator. */ public static int size(final Iterator<?> iterator) { int count = 0; while (iterator.hasNext()) { iterator.next(); count++; } return count; } /** * Create a {@link Stream} from {@link Iterator}. Iterator first converted to {@link Spliterators} using: * <code>Spliterators.spliteratorUnknownSize(attributesIterator, Spliterator.ORDERED)</code> * * @param iterator to transform to {@link Stream} * @param <E> iterator element * @return new {@link Stream} */ public static <E> Stream<E> toStream(final Iterator<E> iterator) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false); } /** Returns {@code true} if {@code iterator} contains {@code element}. */ public static boolean contains(final Iterator<?> iterator, @CheckForNull final Object element) { if (element == null) { while (iterator.hasNext()) { if (iterator.next() == null) { return true; } } } else { while (iterator.hasNext()) { if (element.equals(iterator.next())) { return true; } } } return false; } /** * Verbatim copy of {@code com.google.common.collect.Iterators#getLast(Iterator, Object)}. * * Advances {@code iterator} to the end, returning the last element or {@code defaultValue} if the iterator is empty. * * @param defaultValue the default value to return if the iterator is empty * @return the last element of {@code iterator} */ public static <T> T getLast(final Iterator<? extends T> iterator, final T defaultValue) { return iterator.hasNext() ? getLast(iterator) : defaultValue; } public static <T> Iterator<T> concat(final Iterator<? extends Iterator<? extends T>> inputs) { return new ConcatenatedIterator<>(inputs); } /** * Returns the single element contained in {@code iterator}. * * @throws NoSuchElementException if the iterator is empty * @throws IllegalArgumentException if the iterator contains multiple elements. The state of the * iterator is unspecified. */ public static <T extends Object> T getOnlyElement(final Iterator<T> iterator) { final T first = iterator.next(); if (!iterator.hasNext()) { return first; } final StringBuilder sb = new StringBuilder().append("expected one element but was: <").append(first); for (int i = 0; i < 4 && iterator.hasNext(); i++) { sb.append(", ").append(iterator.next()); } if (iterator.hasNext()) { sb.append(", ..."); } sb.append('>'); throw new IllegalArgumentException(sb.toString()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/utils/collect/MultiValueMap.java
utils/src/main/java/org/killbill/commons/utils/collect/MultiValueMap.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.utils.collect; import java.util.List; import java.util.Map; /** * Simple {@link Map} extension where the value is a {@link List}. The value will contain duplicate value. */ public interface MultiValueMap<K, E> extends Map<K, List<E>> { /** * Add value to {@link List} associated with the key. * @param key map key * @param elements value to add to the {@link List} */ void putElement(K key, E... elements); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/Dispatcher.java
utils/src/main/java/org/killbill/commons/eventbus/Dispatcher.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.util.ArrayDeque; import java.util.Iterator; import java.util.Queue; import org.killbill.commons.utils.Preconditions; /** * <strong><p>Note: Not like Guava, {@code LegacyAsyncDispatcher} get removed as it considered as legacy code.</p></strong> * * Handler for dispatching events to subscribers, providing different event ordering guarantees that * make sense for different situations. * * <p><b>Note:</b> The dispatcher is orthogonal to the subscriber's {@code Executor}. The dispatcher * controls the order in which events are dispatched, while the executor controls how (i.e. on which * thread) the subscriber is actually called when an event is dispatched to it. * * @author Colin Decker */ abstract class Dispatcher { /** * Returns a dispatcher that queues events that are posted reentrantly on a thread that is already * dispatching an event, guaranteeing that all events posted on a single thread are dispatched to * all subscribers in the order they are posted. * * <p>When all subscribers are dispatched to using a <i>direct</i> executor (which dispatches on * the same thread that posts the event), this yields a breadth-first dispatch order on each * thread. That is, all subscribers to a single event A will be called before any subscribers to * any events B and C that are posted to the event bus by the subscribers to A. */ static Dispatcher perThreadDispatchQueue() { return new PerThreadQueuedDispatcher(); } /** * Returns a dispatcher that dispatches events to subscribers immediately as they're posted * without using an intermediate queue to change the dispatch order. This is effectively a * depth-first dispatch order, vs. breadth-first when using a queue. */ static Dispatcher immediate() { return ImmediateDispatcher.INSTANCE; } /** * Dispatches the given {@code event} to the given {@code subscribers}. */ abstract void dispatch(Object event, Iterator<Subscriber> subscribers); /** * Implementation of a {@link #perThreadDispatchQueue()} dispatcher. */ static final class PerThreadQueuedDispatcher extends Dispatcher { // This dispatcher matches the original dispatch behavior of EventBus. /** * Per-thread queue of events to dispatch. */ private final ThreadLocal<Queue<Event>> queue = ThreadLocal.withInitial(ArrayDeque::new); /** * Per-thread dispatch state, used to avoid reentrant event dispatching. */ private final ThreadLocal<Boolean> dispatching = ThreadLocal.withInitial(() -> false); @Override void dispatch(final Object event, final Iterator<Subscriber> subscribers) { Preconditions.checkNotNull(event); Preconditions.checkNotNull(subscribers); final Queue<Event> queueForThread = queue.get(); queueForThread.offer(new Event(event, subscribers)); if (!dispatching.get()) { dispatching.set(true); try { Event nextEvent; while ((nextEvent = queueForThread.poll()) != null) { while (nextEvent.subscribers.hasNext()) { nextEvent.subscribers.next().dispatchEvent(nextEvent.event); } } } finally { dispatching.remove(); queue.remove(); } } } private static final class Event { private final Object event; private final Iterator<Subscriber> subscribers; private Event(final Object event, final Iterator<Subscriber> subscribers) { this.event = event; this.subscribers = subscribers; } } } /** * Implementation of {@link #immediate()}. */ static final class ImmediateDispatcher extends Dispatcher { private static final ImmediateDispatcher INSTANCE = new ImmediateDispatcher(); @Override void dispatch(final Object event, final Iterator<Subscriber> subscribers) { Preconditions.checkNotNull(event); while (subscribers.hasNext()) { subscribers.next().dispatchEvent(event); } } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/EventBusException.java
utils/src/main/java/org/killbill/commons/eventbus/EventBusException.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; public class EventBusException extends Exception { public EventBusException() { } public EventBusException(final String message) { super(message); } public EventBusException(final String message, final Throwable cause) { super(message, cause); } public EventBusException(final Throwable cause) { super(cause); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/AllowConcurrentEvents.java
utils/src/main/java/org/killbill/commons/eventbus/AllowConcurrentEvents.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks an event subscriber method as being thread-safe. This annotation indicates that EventBus * may invoke the event subscriber simultaneously from multiple threads. * * <p>This does not mark the method, and so should be used in combination with {@link Subscribe}. * * @author Cliff Biffle * @since 10.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface AllowConcurrentEvents {}
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/EventBus.java
utils/src/main/java/org/killbill/commons/eventbus/EventBus.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.util.Iterator; import java.util.Locale; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; import org.killbill.commons.eventbus.Dispatcher.ImmediateDispatcher; import org.killbill.commons.utils.Preconditions; import org.killbill.commons.utils.concurrent.DirectExecutor; /** * Dispatches events to listeners, and provides ways for listeners to register themselves. * * <h2>Avoid EventBus</h2> * * <p><b>We recommend against using EventBus.</b> It was designed many years ago, and newer * libraries offer better ways to decouple components and react to events. * * <p>To decouple components, we recommend a dependency-injection framework. For Android code, most * apps use <a href="https://dagger.dev">Dagger</a>. For server code, common options include <a * href="https://github.com/google/guice/wiki/Motivation">Guice</a> and <a * href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-introduction">Spring</a>. * Frameworks typically offer a way to register multiple listeners independently and then request * them together as a set (<a href="https://dagger.dev/dev-guide/multibindings">Dagger</a>, <a * href="https://github.com/google/guice/wiki/Multibindings">Guice</a>, <a * href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-autowired-annotation">Spring</a>). * * <p>To react to events, we recommend a reactive-streams framework like <a * href="https://github.com/ReactiveX/RxJava/wiki">RxJava</a> (supplemented with its <a * href="https://github.com/ReactiveX/RxAndroid">RxAndroid</a> extension if you are building for * Android) or <a href="https://projectreactor.io/">Project Reactor</a>. (For the basics of * translating code from using an event bus to using a reactive-streams framework, see these two * guides: <a href="https://blog.jkl.gg/implementing-an-event-bus-with-rxjava-rxbus/">1</a>, <a * href="https://lorentzos.com/rxjava-as-event-bus-the-right-way-10a36bdd49ba">2</a>.) Some usages * of EventBus may be better written using <a * href="https://kotlinlang.org/docs/coroutines-guide.html">Kotlin coroutines</a>, including <a * href="https://kotlinlang.org/docs/flow.html">Flow</a> and <a * href="https://kotlinlang.org/docs/channels.html">Channels</a>. Yet other usages are better served * by individual libraries that provide specialized support for particular use cases. * * <p>Disadvantages of EventBus include: * * <ul> * <li>It makes the cross-references between producer and subscriber harder to find. This can * complicate debugging, lead to unintentional reentrant calls, and force apps to eagerly * initialize all possible subscribers at startup time. * <li>It uses reflection in ways that break when code is processed by optimizers/minimizers like * <a href="https://developer.android.com/studio/build/shrink-code">R8 and Proguard</a>. * <li>It doesn't offer a way to wait for multiple events before taking action. For example, it * doesn't offer a way to wait for multiple producers to all report that they're "ready," nor * does it offer a way to batch multiple events from a single producer together. * <li>It doesn't support backpressure and other features needed for resilience. * <li>It doesn't provide much control of threading. * <li>It doesn't offer much monitoring. * <li>It doesn't propagate exceptions, so apps don't have a way to react to them. * <li>It doesn't interoperate well with RxJava, coroutines, and other more commonly used * alternatives. * <li>It imposes requirements on the lifecycle of its subscribers. For example, if an event * occurs between when one subscriber is removed and the next subscriber is added, the event * is dropped. * <li>Its performance is suboptimal, especially under Android. * <li>It <a href="https://github.com/google/guava/issues/1431">doesn't support parameterized * types</a>. * <li>With the introduction of lambdas in Java 8, EventBus went from less verbose than listeners * to <a href="https://github.com/google/guava/issues/3311">more verbose</a>. * </ul> * * <h2>EventBus Summary</h2> * * <p>The EventBus allows publish-subscribe-style communication between components without requiring * the components to explicitly register with one another (and thus be aware of each other). It is * designed exclusively to replace traditional Java in-process event distribution using explicit * registration. It is <em>not</em> a general-purpose publish-subscribe system, nor is it intended * for interprocess communication. * * <h2>Receiving Events</h2> * * <p>To receive events, an object should: * * <ol> * <li>Expose a public method, known as the <i>event subscriber</i>, which accepts a single * argument of the type of event desired; * <li>Mark it with a {@link Subscribe} annotation; * <li>Pass itself to an EventBus instance's {@link #register(Object)} method. * </ol> * * <h2>Posting Events</h2> * * <p>To post an event, simply provide the event object to the {@link #post(Object)} method. The * EventBus instance will determine the type of event and route it to all registered listeners. * * <p>Events are routed based on their type &mdash; an event will be delivered to any subscriber for * any type to which the event is <em>assignable.</em> This includes implemented interfaces, all * superclasses, and all interfaces implemented by superclasses. * * <h2>Subscriber Methods</h2> * * <p>Event subscriber methods must accept only one argument: the event. * * <p>Subscribers should not, in general, throw. If they do, the EventBus will catch and log the * exception. This is rarely the right solution for error handling and should not be relied upon; it * is intended solely to help find problems during development. * * <p>The EventBus guarantees that it will not call a subscriber method from multiple threads * simultaneously, unless the method explicitly allows it by bearing the {@link * AllowConcurrentEvents} annotation. If this annotation is not present, subscriber methods need not * worry about being reentrant, unless also called from outside the EventBus. * * <h2>Dead Events</h2> * * <p>If an event is posted, but no registered subscribers can accept it, it is considered "dead." * To give the system a second chance to handle dead events, they are wrapped in an instance of * {@link DeadEvent} and reposted. * * <p>If a subscriber for a supertype of all events (such as Object) is registered, no event will * ever be considered dead, and no DeadEvents will be generated. Accordingly, while DeadEvent * extends {@link Object}, a subscriber registered to receive any Object will never receive a * DeadEvent. * * <p>This class is safe for concurrent use. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/EventBusExplained">{@code EventBus}</a>. * * @author Cliff Biffle * @since 10.0 */ public class EventBus { private static final Logger logger = Logger.getLogger(EventBus.class.getName()); private final String identifier; private final Executor executor; private final SubscriberExceptionHandler exceptionHandler; private final SubscriberRegistry subscribers = new SubscriberRegistry(this); private final Dispatcher dispatcher; /** * Creates a new EventBus named "default". */ public EventBus() { this("default"); } /** * Creates a new EventBus with the given {@code identifier}. Different with original Guava's implementation, * this constructor will use {@link ImmediateDispatcher} and {@link DefaultCatchableSubscriberExceptionsHandler}. * * @param identifier a brief name for this bus. */ public EventBus(final String identifier) { this(identifier, DirectExecutor.INSTANCE, Dispatcher.immediate(), new DefaultCatchableSubscriberExceptionsHandler()); } /** * Creates a new EventBus with the given {@link SubscriberExceptionHandler}. Different with original Guava's * implementation, this constructor will use {@link ImmediateDispatcher} as default dispatcher. * * @param exceptionHandler Handler for subscriber exceptions. * @since 16.0 */ public EventBus(final SubscriberExceptionHandler exceptionHandler) { this("default", DirectExecutor.INSTANCE, Dispatcher.immediate(), exceptionHandler); } public EventBus(final String identifier, final Executor executor, final Dispatcher dispatcher, final SubscriberExceptionHandler exceptionHandler) { this.identifier = Preconditions.checkNotNull(identifier); this.executor = Preconditions.checkNotNull(executor); this.dispatcher = Preconditions.checkNotNull(dispatcher); this.exceptionHandler = Preconditions.checkNotNull(exceptionHandler); } /** * Returns the identifier for this event bus. * * @since 19.0 */ public final String identifier() { return identifier; } /** * Returns the default executor this event bus uses for dispatching events to subscribers. */ final Executor executor() { return executor; } /** * Handles the given exception thrown by a subscriber with the given context. */ void handleSubscriberException(final Throwable e, final SubscriberExceptionContext context) { Preconditions.checkNotNull(e); Preconditions.checkNotNull(context); try { exceptionHandler.handleException(e, context); } catch (final Throwable e2) { // if the handler threw an exception... well, just log it logger.log( Level.SEVERE, String.format(Locale.ROOT, "Exception %s thrown while handling exception: %s", e2, e), e2); } } /** * Registers all subscriber methods on {@code object} to receive events. * * @param object object whose subscriber methods should be registered. */ public void register(final Object object) { subscribers.register(object); } /** * Unregisters all subscriber methods on a registered {@code object}. * * @param object object whose subscriber methods should be unregistered. * @throws IllegalArgumentException if the object was not previously registered. */ public void unregister(final Object object) { subscribers.unregister(object); } /** * Posts an event to all registered subscribers. This method will return successfully after the * event has been posted to all subscribers, and regardless of any exceptions thrown by * subscribers. * * <p>If no subscribers have been subscribed for {@code event}'s class, and {@code event} is not * already a {@link DeadEvent}, it will be wrapped in a DeadEvent and reposted. * * @param event event to post. */ public void post(final Object event) { final Iterator<Subscriber> eventSubscribers = subscribers.getSubscribers(event); if (eventSubscribers.hasNext()) { dispatcher.dispatch(event, eventSubscribers); } else if (!(event instanceof DeadEvent)) { // the event had no subscribers and was not itself a DeadEvent post(new DeadEvent(this, event)); } } /** * <p>Post an event with ability to handle exception, if any.</p> * * <p>Using this method require that when creating {@code EventBus} instance: * <ul> * <li>exceptionHandler should be instance of CatchableSubscriberExceptionHandler</li> * <li>executor should be instance of DirectExecutor</li> * <li>dispatcher should be instance of ImmediateDispatcher</li> * </ul> * </p> * @param event event to post. * @throws EventBusException */ public void postWithException(final Object event) throws EventBusException { Preconditions.checkState(exceptionHandler instanceof CatchableSubscriberExceptionHandler, "exceptionHandler should be instance of CatchableSubscriberExceptionHandler"); Preconditions.checkState(executor instanceof DirectExecutor, "executor should be instance of DirectExecutor"); Preconditions.checkState(dispatcher instanceof ImmediateDispatcher, "dispatcher should be instance of ImmediateDispatcher"); final CatchableSubscriberExceptionHandler catchableExceptionHandler = (CatchableSubscriberExceptionHandler) exceptionHandler; final Iterator<Subscriber> eventSubscribers = subscribers.getSubscribers(event); if (eventSubscribers.hasNext()) { // Just in case... catchableExceptionHandler.reset(); RuntimeException guavaException = null; final Exception subscriberException; try { dispatcher.dispatch(event, eventSubscribers); } catch (final RuntimeException e) { guavaException = e; } finally { // This works because we are both using the immediate dispatcher and the direct executor // Note: we always want to dequeue here to avoid any memory leaks subscriberException = catchableExceptionHandler.caughtException(); } if (guavaException != null) { throw guavaException; } if (subscriberException != null) { throw new EventBusException(subscriberException); } } else if (!(event instanceof DeadEvent)) { // the event had no subscribers and was not itself a DeadEvent post(new DeadEvent(this, event)); } } @Override public String toString() { return "EventBus {" + "identifier='" + identifier + '\'' + '}'; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/package-info.java
utils/src/main/java/org/killbill/commons/eventbus/package-info.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ /** * This package contains verbatim copy of Guava's <a href="https://guava.dev/releases/18.0/api/docs/index.html?com/google/common/eventbus/package-summary.html">Event Bus</a>. */ package org.killbill.commons.eventbus;
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/DefaultCatchableSubscriberExceptionsHandler.java
utils/src/main/java/org/killbill/commons/eventbus/DefaultCatchableSubscriberExceptionsHandler.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.lang.reflect.InvocationTargetException; class DefaultCatchableSubscriberExceptionsHandler implements CatchableSubscriberExceptionHandler { private final ThreadLocal<Exception> lastException = new ThreadLocal<>() {}; private final SubscriberExceptionHandler loggerHandler = LoggingHandler.INSTANCE; @Override public void handleException(final Throwable exception, final SubscriberExceptionContext context) { // By convention, re-throw the very first exception if (lastException.get() == null) { // Wrapping for legacy reasons lastException.set(new InvocationTargetException(exception)); } loggerHandler.handleException(exception, context); } @Override public Exception caughtException() { final Exception exception = lastException.get(); reset(); return exception; } @Override public void reset() { lastException.set(null); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/DeadEvent.java
utils/src/main/java/org/killbill/commons/eventbus/DeadEvent.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import org.killbill.commons.utils.Preconditions; /** * Wraps an event that was posted, but which had no subscribers and thus could not be delivered. * * <p>Registering a DeadEvent subscriber is useful for debugging or logging, as it can detect * misconfigurations in a system's event distribution. * * @author Cliff Biffle * @since 10.0 */ public class DeadEvent { private final Object source; private final Object event; /** * Creates a new DeadEvent. * * @param source object broadcasting the DeadEvent (generally the {@link EventBus}). * @param event the event that could not be delivered. */ public DeadEvent(final Object source, final Object event) { this.source = Preconditions.checkNotNull(source); this.event = Preconditions.checkNotNull(event); } /** * Returns the object that originated this event (<em>not</em> the object that originated the * wrapped event). This is generally an {@link EventBus}. * * @return the source of this event. */ public Object getSource() { return source; } /** * Returns the wrapped, 'dead' event, which the system was unable to deliver to any registered * subscriber. * * @return the 'dead' event that could not be delivered. */ public Object getEvent() { return event; } @Override public String toString() { return "DeadEvent {" + "source=" + source + ", event=" + event + '}'; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/CatchableSubscriberExceptionHandler.java
utils/src/main/java/org/killbill/commons/eventbus/CatchableSubscriberExceptionHandler.java
/* * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; /** * An implementation of this instance should be used in order to work with {@link EventBus#postWithException(Object)}. */ public interface CatchableSubscriberExceptionHandler extends SubscriberExceptionHandler { Exception caughtException(); void reset(); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/SubscriberExceptionHandler.java
utils/src/main/java/org/killbill/commons/eventbus/SubscriberExceptionHandler.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; /** * Handler for exceptions thrown by event subscribers. * * @since 16.0 */ public interface SubscriberExceptionHandler { /** * Handles exceptions thrown by subscribers. */ void handleException(Throwable exception, SubscriberExceptionContext context); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/SubscriberExceptionContext.java
utils/src/main/java/org/killbill/commons/eventbus/SubscriberExceptionContext.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.lang.reflect.Method; import org.killbill.commons.utils.Preconditions; /** * Context for an exception thrown by a subscriber. * * @since 16.0 */ public class SubscriberExceptionContext { private final EventBus eventBus; private final Object event; private final Object subscriber; private final Method subscriberMethod; /** * @param eventBus The {@link EventBus} that handled the event and the subscriber. Useful for * broadcasting a new event based on the error. * @param event The event object that caused the subscriber to throw. * @param subscriber The source subscriber context. * @param subscriberMethod the subscribed method. */ SubscriberExceptionContext(final EventBus eventBus, final Object event, final Object subscriber, final Method subscriberMethod) { this.eventBus = Preconditions.checkNotNull(eventBus); this.event = Preconditions.checkNotNull(event); this.subscriber = Preconditions.checkNotNull(subscriber); this.subscriberMethod = Preconditions.checkNotNull(subscriberMethod); } /** * @return The {@link EventBus} that handled the event and the subscriber. Useful for broadcasting * a new event based on the error. */ public EventBus getEventBus() { return eventBus; } /** * @return The event object that caused the subscriber to throw. */ public Object getEvent() { return event; } /** * @return The object context that the subscriber was called on. */ public Object getSubscriber() { return subscriber; } /** * @return The subscribed method that threw the exception. */ Method getSubscriberMethod() { return subscriberMethod; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/SubscriberRegistry.java
utils/src/main/java/org/killbill/commons/eventbus/SubscriberRegistry.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; import javax.annotation.CheckForNull; import org.killbill.commons.utils.Preconditions; import org.killbill.commons.utils.Primitives; import org.killbill.commons.utils.TypeToken; import org.killbill.commons.utils.annotation.VisibleForTesting; import org.killbill.commons.utils.cache.Cache; import org.killbill.commons.utils.cache.DefaultCache; import org.killbill.commons.utils.cache.DefaultSynchronizedCache; import org.killbill.commons.utils.collect.Iterators; import org.killbill.commons.utils.collect.MultiValueHashMap; import org.killbill.commons.utils.collect.MultiValueMap; /** * Registry of subscribers to a single event bus. * * @author Colin Decker */ final class SubscriberRegistry { /** * All registered subscribers, indexed by event type. * * <p>The {@link CopyOnWriteArraySet} values make it easy and relatively lightweight to get an * immutable snapshot of all current subscribers to an event without any locking. */ private final ConcurrentMap<Class<?>, CopyOnWriteArraySet<Subscriber>> subscribers = new ConcurrentHashMap<>(); /** The event bus this registry belongs to. */ private final EventBus bus; SubscriberRegistry(final EventBus bus) { this.bus = Preconditions.checkNotNull(bus); } /** Registers all subscriber methods on the given listener object. */ void register(final Object listener) { final MultiValueMap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener); for (final Entry<Class<?>, List<Subscriber>> entry : listenerMethods.entrySet()) { final Class<?> eventType = entry.getKey(); final Collection<Subscriber> eventMethodsInListener = entry.getValue(); CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType); if (eventSubscribers == null) { final CopyOnWriteArraySet<Subscriber> newSet = new CopyOnWriteArraySet<>(); eventSubscribers = Objects.requireNonNullElse(subscribers.putIfAbsent(eventType, newSet), newSet); } eventSubscribers.addAll(eventMethodsInListener); } } /** Unregisters all subscribers on the given listener object. */ void unregister(final Object listener) { final MultiValueMap<Class<?>, Subscriber> listenerMethods = findAllSubscribers(listener); for (final Entry<Class<?>, List<Subscriber>> entry : listenerMethods.entrySet()) { final Class<?> eventType = entry.getKey(); final Collection<Subscriber> listenerMethodsForType = entry.getValue(); final CopyOnWriteArraySet<Subscriber> currentSubscribers = subscribers.get(eventType); if (currentSubscribers == null || !currentSubscribers.removeAll(listenerMethodsForType)) { // if removeAll returns true, all we really know is that at least one subscriber was // removed... however, barring something very strange we can assume that if at least one // subscriber was removed, all subscribers on listener for that event type were... after // all, the definition of subscribers on a particular class is totally static throw new IllegalArgumentException("missing event subscriber for an annotated method. Is " + listener + " registered?"); } // don't try to remove the set if it's empty; that can't be done safely without a lock // anyway, if the set is empty it'll just be wrapping an array of length 0 } } @VisibleForTesting Set<Subscriber> getSubscribersForTesting(final Class<?> eventType) { return Objects.requireNonNullElse(subscribers.get(eventType), Collections.emptySet()); } /** * Gets an iterator representing an immutable snapshot of all subscribers to the given event at * the time this method is called. */ Iterator<Subscriber> getSubscribers(final Object event) { final Set<Class<?>> eventTypes = flattenHierarchy(event.getClass()); final List<Iterator<Subscriber>> subscriberIterators = new ArrayList<>(eventTypes.size()); for (final Class<?> eventType : eventTypes) { final CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType); if (eventSubscribers != null) { // eager no-copy snapshot subscriberIterators.add(eventSubscribers.iterator()); } } return Iterators.concat(subscriberIterators.iterator()); } /** * A thread-safe cache that contains the mapping from each class to all methods in that class and * all super-classes, that are annotated with {@code @Subscribe}. The cache is shared across all * instances of this class; this greatly improves performance if multiple EventBus instances are * created and objects of the same class are registered on all of them. */ private static final Cache<Class<?>, List<Method>> subscriberMethodsCache = new DefaultSynchronizedCache<>( Integer.MAX_VALUE, DefaultCache.NO_TIMEOUT, SubscriberRegistry::getAnnotatedMethodsNotCached ); /** * Returns all subscribers for the given listener grouped by the type of event they subscribe to. */ private MultiValueMap<Class<?>, Subscriber> findAllSubscribers(final Object listener) { final MultiValueMap<Class<?>, Subscriber> methodsInListener = new MultiValueHashMap<>(); final Class<?> clazz = listener.getClass(); for (final Method method : subscriberMethodsCache.get(clazz)) { final Class<?>[] parameterTypes = method.getParameterTypes(); final Class<?> eventType = parameterTypes[0]; methodsInListener.putElement(eventType, Subscriber.create(bus, listener, method)); } return methodsInListener; } private static List<Method> getAnnotatedMethodsNotCached(final Class<?> clazz) { final Set<? extends Class<?>> supertypes = TypeToken.getRawTypes(clazz); final Map<MethodIdentifier, Method> identifiers = new HashMap<>(); for (final Class<?> supertype : supertypes) { for (final Method method : supertype.getDeclaredMethods()) { if (method.isAnnotationPresent(Subscribe.class) && !method.isSynthetic()) { // TODO(cgdecker): Should check for a generic parameter type and error out final Class<?>[] parameterTypes = method.getParameterTypes(); Preconditions.checkArgument(parameterTypes.length == 1, "Method %s has @Subscribe annotation but has %s parameters. Subscriber methods must have exactly 1 parameter.", method, parameterTypes.length); Preconditions.checkArgument(!parameterTypes[0].isPrimitive(), "@Subscribe method %s's parameter is %s. Subscriber methods cannot accept primitives. Consider changing the parameter to %s.", method, parameterTypes[0].getName(), Primitives.wrap(parameterTypes[0]).getSimpleName()); final MethodIdentifier ident = new MethodIdentifier(method); if (!identifiers.containsKey(ident)) { identifiers.put(ident, method); } } } } return List.copyOf(identifiers.values()); } /** * Global cache of classes to their flattened hierarchy of supertypes. * * <a href="https://github.com/google/guava/blob/master/guava/src/com/google/common/eventbus/SubscriberRegistry.java#L218">Guava version</a> * */ private static final Cache<Class<?>, Set<Class<?>>> flattenHierarchyCache = new DefaultSynchronizedCache<>( // max size in our cache is mandatory. OTOH, guava version of flattenHierarchyCache have no maxSize. Integer.MAX_VALUE, DefaultCache.NO_TIMEOUT, // Note Issue: 1615: Originally, flattenHierarchyCache data type was "LoadingCache" from Guava: // https://github.com/google/guava/blob/master/guava/src/com/google/common/eventbus/SubscriberRegistry.java#L219 // CacheLoader used ImmutableSet as return value. Somehow ImmutableSet maintains its order, where // HashSet isn't. This is why we have LinkedHashSet here. key -> new LinkedHashSet<>(TypeToken.getRawTypes(key))); /** * Flattens a class's type hierarchy into a set of {@code Class} objects including all * superclasses (transitively) and all interfaces implemented by these superclasses. */ @VisibleForTesting static Set<Class<?>> flattenHierarchy(final Class<?> concreteClass) { return flattenHierarchyCache.get(concreteClass); } private static final class MethodIdentifier { private final String name; private final List<Class<?>> parameterTypes; MethodIdentifier(final Method method) { this.name = method.getName(); this.parameterTypes = Arrays.asList(method.getParameterTypes()); } @Override public int hashCode() { return Objects.hash(name, parameterTypes); } @Override public boolean equals(@CheckForNull final Object o) { if (o instanceof MethodIdentifier) { final MethodIdentifier ident = (MethodIdentifier) o; return name.equals(ident.name) && parameterTypes.equals(ident.parameterTypes); } return false; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/Subscriber.java
utils/src/main/java/org/killbill/commons/eventbus/Subscriber.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.Executor; import javax.annotation.CheckForNull; import org.killbill.commons.utils.Preconditions; import org.killbill.commons.utils.annotation.VisibleForTesting; /** * A subscriber method on a specific object, plus the executor that should be used for dispatching * events to it. * * <p>Two subscribers are equivalent when they refer to the same method on the same object (not * class). This property is used to ensure that no subscriber method is registered more than once. * * @author Colin Decker */ class Subscriber { /** * The object with the subscriber method. */ @VisibleForTesting final Object target; /** * Subscriber method. */ private final Method method; /** * Executor to use for dispatching events to this subscriber. */ private final Executor executor; /** * The event bus this subscriber belongs to. */ private final EventBus bus; private Subscriber(final EventBus bus, final Object target, final Method method) { this.bus = bus; this.target = Preconditions.checkNotNull(target); this.method = method; method.setAccessible(true); this.executor = bus.executor(); } /** * Creates a {@code Subscriber} for {@code method} on {@code listener}. */ static Subscriber create(final EventBus bus, final Object listener, final Method method) { return isDeclaredThreadSafe(method) ? new Subscriber(bus, listener, method) : new SynchronizedSubscriber(bus, listener, method); } /** * Checks whether {@code method} is thread-safe, as indicated by the presence of the {@link * AllowConcurrentEvents} annotation. */ private static boolean isDeclaredThreadSafe(final Method method) { return method.getAnnotation(AllowConcurrentEvents.class) != null; } /** * Dispatches {@code event} to this subscriber using the proper executor. */ final void dispatchEvent(final Object event) { executor.execute( () -> { try { invokeSubscriberMethod(event); } catch (final InvocationTargetException e) { bus.handleSubscriberException(e.getCause(), context(event)); } }); } /** * Invokes the subscriber method. This method can be overridden to make the invocation * synchronized. */ @VisibleForTesting void invokeSubscriberMethod(final Object event) throws InvocationTargetException { try { method.invoke(target, Preconditions.checkNotNull(event)); } catch (final IllegalArgumentException e) { throw new Error("Method rejected target/argument: " + event, e); } catch (final IllegalAccessException e) { throw new Error("Method became inaccessible: " + event, e); } catch (final InvocationTargetException e) { if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } throw e; } } /** * Gets the context for the given event. */ private SubscriberExceptionContext context(final Object event) { return new SubscriberExceptionContext(bus, event, target, method); } @Override public final int hashCode() { return (31 + method.hashCode()) * 31 + System.identityHashCode(target); } @Override public final boolean equals(@CheckForNull final Object obj) { if (obj instanceof Subscriber) { final Subscriber that = (Subscriber) obj; // Use == so that different equal instances will still receive events. // We only guard against the case that the same object is registered // multiple times return target == that.target && method.equals(that.method); } return false; } /** * Subscriber that synchronizes invocations of a method to ensure that only one thread may enter * the method at a time. */ @VisibleForTesting static final class SynchronizedSubscriber extends Subscriber { private SynchronizedSubscriber(final EventBus bus, final Object target, final Method method) { super(bus, target, method); } @Override void invokeSubscriberMethod(final Object event) throws InvocationTargetException { synchronized (this) { super.invokeSubscriberMethod(event); } } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/LoggingHandler.java
utils/src/main/java/org/killbill/commons/eventbus/LoggingHandler.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; /** * This class originally exist as nested static class in {@link EventBus} as default {@link SubscriberExceptionHandler} * implementation. */ class LoggingHandler implements SubscriberExceptionHandler { static final SubscriberExceptionHandler INSTANCE = new LoggingHandler(); private static Logger logger(final SubscriberExceptionContext context) { return Logger.getLogger(EventBus.class.getName() + "." + context.getEventBus().identifier()); } private static String message(final SubscriberExceptionContext context) { final Method method = context.getSubscriberMethod(); return "Exception thrown by subscriber method " + method.getName() + '(' + method.getParameterTypes()[0].getName() + ')' + " on subscriber " + context.getSubscriber() + " when dispatching event: " + context.getEvent(); } @Override public void handleException(final Throwable exception, final SubscriberExceptionContext context) { final Logger logger = logger(context); if (logger.isLoggable(Level.SEVERE)) { logger.log(Level.SEVERE, message(context), exception); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/utils/src/main/java/org/killbill/commons/eventbus/Subscribe.java
utils/src/main/java/org/killbill/commons/eventbus/Subscribe.java
/* * Copyright (C) 2007 The Guava Authors * Copyright 2020-2022 Equinix, Inc * Copyright 2014-2022 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.eventbus; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks a method as an event subscriber. * * <p>The type of event will be indicated by the method's first (and only) parameter, which cannot * be primitive. If this annotation is applied to methods with zero parameters, or more than one * parameter, the object containing the method will not be able to register for event delivery from * the {@link EventBus}. * * <p>Unless also annotated with @{@link AllowConcurrentEvents}, event subscriber methods will be * invoked serially by each event bus that they are registered with. * * @author Cliff Biffle * @since 10.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Subscribe {}
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/test/java/org/killbill/commons/concurrent/TestDynamicThreadPoolExecutorWithLoggingOnExceptions.java
concurrent/src/test/java/org/killbill/commons/concurrent/TestDynamicThreadPoolExecutorWithLoggingOnExceptions.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.concurrent; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestDynamicThreadPoolExecutorWithLoggingOnExceptions { private BlockingQueue<Runnable> queue; private ThreadPoolExecutor executor; @BeforeMethod(groups = "fast") public void beforeMethod() { final ThreadFactory threadFactory = new ThreadFactory() { @Override public Thread newThread(final Runnable r) { return new Thread(new ThreadGroup("TestThreadGroup"), r, "-test"); } }; final RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler() { @Override public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) { } }; queue = new LinkedBlockingQueue<Runnable>(); executor = new DynamicThreadPoolExecutorWithLoggingOnExceptions(1, 3, 1, TimeUnit.MINUTES, queue, threadFactory, rejectedExecutionHandler); //executor = new ThreadPoolExecutor(1, 3, 1, TimeUnit.MINUTES, queue, threadFactory, rejectedExecutionHandler); } @AfterMethod(groups = "fast") public void afterMethod() { } @Test(groups = "fast") public void testPoolWitMaximumPoolSize() throws InterruptedException { final CountDownLatch startSignal = new CountDownLatch(1); final CountDownLatch doneSignal = new CountDownLatch(4); // Should be handled by corePoolSize ( = 1) thread executor.submit(new TestCallable(startSignal, doneSignal)); Assert.assertEquals(queue.size(), 0); // Should spawn two new threads up to maximumPoolSize (= 3) executor.submit(new TestCallable(startSignal, doneSignal)); Assert.assertEquals(queue.size(), 0); executor.submit(new TestCallable(startSignal, doneSignal)); Assert.assertEquals(queue.size(), 0); // Submit a new task, queue should grow to 1 as other threads are busy. executor.submit(new TestCallable(startSignal, doneSignal)); Assert.assertEquals(queue.size(), 1); // Release other threads startSignal.countDown(); // Wait for all threads to complete doneSignal.await(); Assert.assertEquals(queue.size(), 0); } public static class TestCallable implements Callable<Object> { private final CountDownLatch startSignal; private final CountDownLatch doneSignal; public TestCallable(final CountDownLatch startSignal, final CountDownLatch doneSignal) { this.startSignal = startSignal; this.doneSignal = doneSignal; } @Override public Object call() throws Exception { startSignal.await(); doneSignal.countDown(); return null; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/test/java/org/killbill/commons/concurrent/TestExecutors.java
concurrent/src/test/java/org/killbill/commons/concurrent/TestExecutors.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.concurrent; import java.io.ByteArrayOutputStream; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; import org.apache.log4j.WriterAppender; import org.testng.Assert; import org.testng.annotations.Test; @Test(singleThreaded = true) public class TestExecutors { private void registerAppenders(final Logger loggingLogger, final Logger failsafeLogger, final WriterAppender dummyAppender) { dummyAppender.setImmediateFlush(true); loggingLogger.setLevel(Level.DEBUG); failsafeLogger.setLevel(Level.DEBUG); loggingLogger.addAppender(dummyAppender); failsafeLogger.addAppender(dummyAppender); } private void unregisterAppenders(final ExecutorService executorService, final Logger loggingLogger, final Logger failsafeLogger, final WriterAppender dummyAppender) throws InterruptedException { executorService.shutdown(); Assert.assertTrue(executorService.isShutdown()); Assert.assertTrue(executorService.awaitTermination(10, TimeUnit.SECONDS)); Assert.assertEquals(executorService.shutdownNow().size(), 0); Assert.assertTrue(executorService.isTerminated()); loggingLogger.removeAppender(dummyAppender); failsafeLogger.removeAppender(dummyAppender); } private void runtimeTest(final ExecutorService executorService) throws Exception { final Logger loggingLogger = Logger.getLogger(LoggingExecutor.class); final Logger failsafeLogger = Logger.getLogger(FailsafeScheduledExecutor.class); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final WriterAppender dummyAppender = new WriterAppender(new SimpleLayout(), bos); registerAppenders(loggingLogger, failsafeLogger, dummyAppender); Future<?> future = executorService.submit(new Runnable() { @Override public void run() { throw new RuntimeException("Fail!"); } }); try { future.get(); Assert.fail("Expected exception"); } catch (final ExecutionException e) { Assert.assertEquals(e.getCause().toString(), "java.lang.RuntimeException: Fail!"); } future = executorService.submit(new Runnable() { @Override public void run() { } }, "bright"); Assert.assertEquals(future.get(), "bright"); future = executorService.submit(new Runnable() { @Override public void run() { throw new RuntimeException("Again!"); } }, "Unimportant"); try { future.get(); Assert.fail("Expected exception"); } catch (final ExecutionException e) { Assert.assertEquals(e.getCause().toString(), "java.lang.RuntimeException: Again!"); } unregisterAppenders(executorService, loggingLogger, failsafeLogger, dummyAppender); final String actual = bos.toString(); assertPattern(actual, Pattern.compile("ERROR - Thread\\[TestLoggingExecutor-[^\\]]+\\] ended abnormally with an exception\r?\njava.lang.RuntimeException: Fail!\r?\n")); assertPattern(actual, Pattern.compile("DEBUG - Thread\\[TestLoggingExecutor-[^\\]]+\\] finished executing$")); } private void errorTest(final ExecutorService executorService) throws Exception { final Logger loggingLogger = Logger.getLogger(LoggingExecutor.class); final Logger failsafeLogger = Logger.getLogger(FailsafeScheduledExecutor.class); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final WriterAppender dummyAppender = new WriterAppender(new SimpleLayout(), bos); registerAppenders(loggingLogger, failsafeLogger, dummyAppender); executorService.execute(new Runnable() { @Override public void run() { throw new OutOfMemoryError("Poof!"); } }); unregisterAppenders(executorService, loggingLogger, failsafeLogger, dummyAppender); final String actual = bos.toString(); assertPattern(actual, Pattern.compile("ERROR - Thread\\[TestLoggingExecutor-[^\\]]+\\] ended abnormally with an exception\r?\njava.lang.OutOfMemoryError: Poof!\r?\n")); assertPattern(actual, Pattern.compile("DEBUG - Thread\\[TestLoggingExecutor-[^\\]]+\\] finished executing$")); } private void callableTest(final ExecutorService executorService) throws Exception { final Logger loggingLogger = Logger.getLogger(LoggingExecutor.class); final Logger failsafeLogger = Logger.getLogger(FailsafeScheduledExecutor.class); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final WriterAppender dummyAppender = new WriterAppender(new SimpleLayout(), bos); registerAppenders(loggingLogger, failsafeLogger, dummyAppender); Future<?> future = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { throw new Exception("Oops!"); } }); try { future.get(); Assert.fail("Expected exception"); } catch (final ExecutionException e) { Assert.assertEquals(e.getCause().toString(), "java.lang.Exception: Oops!"); } future = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { throw new OutOfMemoryError("Uh oh!"); } }); try { future.get(); Assert.fail("Expected exception"); } catch (final ExecutionException e) { Assert.assertEquals(e.getCause().toString(), "java.lang.OutOfMemoryError: Uh oh!"); } unregisterAppenders(executorService, loggingLogger, failsafeLogger, dummyAppender); final String actual = bos.toString(); assertPattern(actual, Pattern.compile("DEBUG - Thread\\[TestLoggingExecutor-[^\\]]+\\] ended with an exception\r?\njava.lang.Exception: Oops!\r?\n")); assertPattern(actual, Pattern.compile("ERROR - Thread\\[TestLoggingExecutor-[^\\]]+\\] ended with an exception\r?\njava.lang.OutOfMemoryError: Uh oh!\r?\n")); assertPattern(actual, Pattern.compile("DEBUG - Thread\\[TestLoggingExecutor-[^\\]]+\\] finished executing$")); } private void scheduledTest(final ScheduledExecutorService executorService) throws Exception { final Logger loggingLogger = Logger.getLogger(LoggingExecutor.class); final Logger failsafeLogger = Logger.getLogger(FailsafeScheduledExecutor.class); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final WriterAppender dummyAppender = new WriterAppender(new SimpleLayout(), bos); registerAppenders(loggingLogger, failsafeLogger, dummyAppender); final CountDownLatch scheduleLatch = new CountDownLatch(1); final CountDownLatch fixedDelayLatch = new CountDownLatch(2); final CountDownLatch fixedRateLatch = new CountDownLatch(2); final Future<?> future = executorService.schedule(new Callable<Void>() { @Override public Void call() throws Exception { throw new Exception("Pow!"); } }, 1, TimeUnit.MILLISECONDS); executorService.schedule(new Runnable() { @Override public void run() { scheduleLatch.countDown(); throw new RuntimeException("D'oh!"); } }, 1, TimeUnit.MILLISECONDS); executorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { fixedDelayLatch.countDown(); if (fixedDelayLatch.getCount() != 0) { throw new OutOfMemoryError("Zoinks!"); } else { throw new RuntimeException("Eep!"); } } }, 1, 1, TimeUnit.MILLISECONDS); executorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { fixedRateLatch.countDown(); if (fixedRateLatch.getCount() != 0) { throw new OutOfMemoryError("Zounds!"); } else { throw new RuntimeException("Egad!"); } } }, 1, 1, TimeUnit.MILLISECONDS); try { future.get(); Assert.fail("Expected exception"); } catch (final ExecutionException e) { Assert.assertEquals(e.getCause().toString(), "java.lang.Exception: Pow!"); } scheduleLatch.await(); fixedDelayLatch.await(); fixedRateLatch.await(); unregisterAppenders(executorService, loggingLogger, failsafeLogger, dummyAppender); final String actual = bos.toString(); assertPattern(actual, Pattern.compile("ERROR - Thread\\[TestLoggingExecutor-[^\\]]+\\] ended abnormally with an exception\r?\njava.lang.RuntimeException: D'oh!\r?\n")); assertPattern(actual, Pattern.compile("ERROR - Thread\\[TestLoggingExecutor-[^\\]]+\\] ended abnormally with an exception\r?\njava.lang.OutOfMemoryError: Zoinks!\r?\n")); assertPattern(actual, Pattern.compile("ERROR - Thread\\[TestLoggingExecutor-[^\\]]+\\] ended abnormally with an exception\r?\njava.lang.RuntimeException: Eep!\r?\n")); assertPattern(actual, Pattern.compile("ERROR - Thread\\[TestLoggingExecutor-[^\\]]+\\] ended abnormally with an exception\r?\njava.lang.OutOfMemoryError: Zounds!\r?\n")); assertPattern(actual, Pattern.compile("ERROR - Thread\\[TestLoggingExecutor-[^\\]]+\\] ended abnormally with an exception\r?\njava.lang.RuntimeException: Egad!\r?\n")); assertPattern(actual, Pattern.compile("DEBUG - Thread\\[TestLoggingExecutor-[^\\]]+\\] finished executing$")); } private void assertPattern(final String actual, final Pattern expected) { Assert.assertTrue(expected.matcher(actual).find(), String.format("Expected to see:\n%s\nin:\n%s", indent(expected.toString()), indent(actual))); } private String indent(final String str) { return "\t" + str.replaceAll("\n", "\n\t"); } @Test(groups = "fast") public void testSingleThreadExecutorRuntimeException() throws Exception { runtimeTest(Executors.newSingleThreadExecutor("TestLoggingExecutor")); } @Test(groups = "fast") public void testSingleThreadExecutorError() throws Exception { errorTest(Executors.newSingleThreadExecutor("TestLoggingExecutor")); } @Test(groups = "fast") public void testSingleThreadExecutorCallable() throws Exception { callableTest(Executors.newSingleThreadExecutor("TestLoggingExecutor")); } @Test(groups = "fast") public void testCachedThreadPoolRuntimeException() throws Exception { runtimeTest(Executors.newCachedThreadPool("TestLoggingExecutor")); } @Test(groups = "fast") public void testCachedThreadPoolError() throws Exception { errorTest(Executors.newCachedThreadPool("TestLoggingExecutor")); } @Test(groups = "fast") public void testCachedThreadPoolCallable() throws Exception { callableTest(Executors.newCachedThreadPool("TestLoggingExecutor")); } @Test(groups = "fast") public void testFixedThreadPoolRuntimeException() throws Exception { runtimeTest(Executors.newFixedThreadPool(10, "TestLoggingExecutor")); } @Test(groups = "fast") public void testFixedThreadPoolError() throws Exception { errorTest(Executors.newFixedThreadPool(10, "TestLoggingExecutor")); } @Test(groups = "fast") public void testFixedThreadPoolCallable() throws Exception { callableTest(Executors.newFixedThreadPool(10, "TestLoggingExecutor")); } @Test(groups = "fast") public void testScheduledThreadPoolRuntimeException() throws Exception { runtimeTest(Executors.newScheduledThreadPool(10, "TestLoggingExecutor")); } @Test(groups = "fast") public void testScheduledThreadPoolError() throws Exception { errorTest(Executors.newScheduledThreadPool(10, "TestLoggingExecutor")); } @Test(groups = "fast") public void testScheduledThreadPoolCallable() throws Exception { callableTest(Executors.newScheduledThreadPool(10, "TestLoggingExecutor")); } @Test(groups = "fast") public void testScheduledThreadPoolScheduled() throws Exception { scheduledTest(Executors.newScheduledThreadPool(10, "TestLoggingExecutor")); } @Test(groups = "fast") public void testSingleThreadScheduledExecutorRuntimeException() throws Exception { runtimeTest(Executors.newSingleThreadScheduledExecutor("TestLoggingExecutor")); } @Test(groups = "fast") public void testSingleThreadScheduledExecutorError() throws Exception { errorTest(Executors.newSingleThreadScheduledExecutor("TestLoggingExecutor")); } @Test(groups = "fast") public void testSingleThreadScheduledExecutorCallable() throws Exception { callableTest(Executors.newSingleThreadScheduledExecutor("TestLoggingExecutor")); } @Test(groups = "fast") public void testSingleThreadScheduledExecutorScheduled() throws Exception { scheduledTest(Executors.newSingleThreadScheduledExecutor("TestLoggingExecutor")); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/test/java/org/killbill/commons/profiling/TestProfilingFeature.java
concurrent/src/test/java/org/killbill/commons/profiling/TestProfilingFeature.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.profiling; import org.testng.annotations.Test; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public class TestProfilingFeature { @Test(groups = "fast") public void testSimpleFeature() { final ProfilingFeature f = new ProfilingFeature("API"); assertTrue(f.isProfilingAPI()); assertFalse(f.isProfilingDAO()); assertFalse(f.isProfilingDAOWithDetails()); assertFalse(f.isProfilingPlugin()); } @Test(groups = "fast") public void testTwoFeatures() { final ProfilingFeature f = new ProfilingFeature("API,DAO"); assertTrue(f.isProfilingAPI()); assertTrue(f.isProfilingDAO()); assertFalse(f.isProfilingDAOWithDetails()); assertFalse(f.isProfilingPlugin()); } @Test(groups = "fast") public void testThreeFeatures() { final ProfilingFeature f = new ProfilingFeature(" API, DAO, PLUGIN"); assertTrue(f.isProfilingAPI()); assertTrue(f.isProfilingDAO()); assertFalse(f.isProfilingDAOWithDetails()); assertTrue(f.isProfilingPlugin()); } @Test(groups = "fast") public void testThreeFeatures2() { final ProfilingFeature f = new ProfilingFeature(" API, DAO_DETAILS, PLUGIN"); assertTrue(f.isProfilingAPI()); assertTrue(f.isProfilingDAO()); assertTrue(f.isProfilingDAOWithDetails()); assertTrue(f.isProfilingPlugin()); } @Test(groups = "fast") public void testTwoRealFeatures2() { final ProfilingFeature f = new ProfilingFeature(" API, FOO, PLUGIN"); assertTrue(f.isProfilingAPI()); assertFalse(f.isProfilingDAO()); assertFalse(f.isProfilingDAOWithDetails()); assertTrue(f.isProfilingPlugin()); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/concurrent/WrappedRunnable.java
concurrent/src/main/java/org/killbill/commons/concurrent/WrappedRunnable.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.concurrent; import org.slf4j.Logger; class WrappedRunnable implements Runnable { private final Logger log; private final Runnable runnable; private volatile Throwable exception; private WrappedRunnable(final Logger log, final Runnable runnable) { this.log = log; this.runnable = runnable; } public static WrappedRunnable wrap(final Logger log, final Runnable runnable) { return runnable instanceof WrappedRunnable ? (WrappedRunnable) runnable : new WrappedRunnable(log, runnable); } Throwable getException() { return exception; } @Override public void run() { final Thread currentThread = Thread.currentThread(); try { runnable.run(); } catch (final Throwable e) { log.error(currentThread + " ended abnormally with an exception", e); exception = e; } log.debug("{} finished executing", currentThread); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/concurrent/WrappedCallable.java
concurrent/src/main/java/org/killbill/commons/concurrent/WrappedCallable.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.concurrent; import java.util.concurrent.Callable; import org.slf4j.Logger; class WrappedCallable<T> implements Callable<T> { private final Logger log; private final Callable<T> callable; private WrappedCallable(final Logger log, final Callable<T> callable) { this.log = log; this.callable = callable; } public static <T> Callable<T> wrap(final Logger log, final Callable<T> callable) { return callable instanceof WrappedCallable ? callable : new WrappedCallable<T>(log, callable); } @Override public T call() throws Exception { final Thread currentThread = Thread.currentThread(); try { return callable.call(); } catch (final Exception e) { // since callables are expected to sometimes throw exceptions, log this at DEBUG instead of ERROR log.debug(currentThread + " ended with an exception", e); throw e; } catch (final Error e) { log.error(currentThread + " ended with an exception", e); throw e; } finally { log.debug("{} finished executing", currentThread); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/concurrent/LoggingExecutor.java
concurrent/src/main/java/org/killbill/commons/concurrent/LoggingExecutor.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.concurrent; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Extension of {@link java.util.concurrent.ThreadPoolExecutor} that ensures any uncaught exceptions are logged. */ public class LoggingExecutor extends ThreadPoolExecutor { private static final Logger LOG = LoggerFactory.getLogger(LoggingExecutor.class); public LoggingExecutor(final int corePoolSize, final int maximumPoolSize, final String name, final long keepAliveTime, final TimeUnit unit) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(name)); } public LoggingExecutor(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, final ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new LinkedBlockingQueue<Runnable>(), threadFactory); } public LoggingExecutor(final int corePoolSize, final int maximumPoolSize, final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, new NamedThreadFactory(name)); } public LoggingExecutor(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); } public LoggingExecutor(final int corePoolSize, final int maximumPoolSize, final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, new NamedThreadFactory(name), handler); } public LoggingExecutor(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory, final RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); } @Override public <T> Future<T> submit(final Callable<T> task) { return super.submit(WrappedCallable.wrap(LOG, task)); } @Override public <T> Future<T> submit(final Runnable task, final T result) { final WrappedRunnable runnable = WrappedRunnable.wrap(LOG, task); final Future<T> future = super.submit(runnable, result); return WrappedRunnableFuture.wrap(runnable, future); } @Override public Future<?> submit(final Runnable task) { final WrappedRunnable runnable = WrappedRunnable.wrap(LOG, task); final Future<?> future = super.submit(runnable); return WrappedRunnableFuture.wrap(runnable, future); } @Override public void execute(final Runnable command) { super.execute(WrappedRunnable.wrap(LOG, command)); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/concurrent/Executors.java
concurrent/src/main/java/org/killbill/commons/concurrent/Executors.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.concurrent; import java.util.Collection; import java.util.List; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Similar to Java's {@link java.util.concurrent.Executors}, but ensures either a {@link LoggingExecutor} or named {@link FailsafeScheduledExecutor} is used. */ @SuppressWarnings("UnusedDeclaration") public class Executors { /* * Fixed ThreadPool */ public static ExecutorService newFixedThreadPool(final int nThreads, final String name) { return new LoggingExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(name)); } public static ExecutorService newFixedThreadPool(final int nThreads, final String name, final long keepAliveTime, final TimeUnit unit) { return new LoggingExecutor(nThreads, nThreads, keepAliveTime, unit, new NamedThreadFactory(name)); } public static ExecutorService newFixedThreadPool(final int nThreads, final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue) { return new LoggingExecutor(nThreads, nThreads, keepAliveTime, unit, workQueue, new NamedThreadFactory(name)); } public static ExecutorService newFixedThreadPool(final int nThreads, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory) { return new LoggingExecutor(nThreads, nThreads, keepAliveTime, unit, workQueue, threadFactory); } public static ExecutorService newFixedThreadPool(final int nThreads, final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final RejectedExecutionHandler handler) { return new LoggingExecutor(nThreads, nThreads, keepAliveTime, unit, workQueue, new NamedThreadFactory(name), handler); } public static ExecutorService newFixedThreadPool(final int nThreads, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory, final RejectedExecutionHandler handler) { return new LoggingExecutor(nThreads, nThreads, keepAliveTime, unit, workQueue, threadFactory, handler); } /* * Single threaded (fixed ThreadPool of 1) */ public static ExecutorService newSingleThreadExecutor(final String name) { return new FinalizableDelegatedExecutorService(newFixedThreadPool(1, name)); } public static ExecutorService newSingleThreadExecutor(final String name, final long keepAliveTime, final TimeUnit unit) { return new FinalizableDelegatedExecutorService(newFixedThreadPool(1, name, keepAliveTime, unit)); } public static ExecutorService newSingleThreadExecutor(final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue) { return new FinalizableDelegatedExecutorService(newFixedThreadPool(1, name, keepAliveTime, unit, workQueue)); } public static ExecutorService newSingleThreadExecutor(final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory) { return new FinalizableDelegatedExecutorService(newFixedThreadPool(1, keepAliveTime, unit, workQueue, threadFactory)); } public static ExecutorService newSingleThreadExecutor(final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final RejectedExecutionHandler handler) { return new FinalizableDelegatedExecutorService(newFixedThreadPool(1, name, keepAliveTime, unit, workQueue, handler)); } public static ExecutorService newSingleThreadExecutor(final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory, final RejectedExecutionHandler handler) { return new FinalizableDelegatedExecutorService(newFixedThreadPool(1, keepAliveTime, unit, workQueue, threadFactory, handler)); } /* * Cached ThreadPool */ public static ExecutorService newCachedThreadPool(final String name) { return new LoggingExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory(name)); } public static ExecutorService newCachedThreadPool(final int minThreads, final int maxThreads, final String name) { return new LoggingExecutor(minThreads, maxThreads, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new NamedThreadFactory(name)); } public static ExecutorService newCachedThreadPool(final int minThreads, final int maxThreads, final String name, final long keepAliveTime, final TimeUnit unit) { return new LoggingExecutor(minThreads, maxThreads, keepAliveTime, unit, new SynchronousQueue<Runnable>(), new NamedThreadFactory(name)); } public static ExecutorService newCachedThreadPool(final int minThreads, final int maxThreads, final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue) { return new LoggingExecutor(minThreads, maxThreads, keepAliveTime, unit, workQueue, new NamedThreadFactory(name)); } public static ExecutorService newCachedThreadPool(final int minThreads, final int maxThreads, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory) { return new LoggingExecutor(minThreads, maxThreads, keepAliveTime, unit, workQueue, threadFactory); } public static ExecutorService newCachedThreadPool(final int minThreads, final int maxThreads, final String name, final long keepAliveTime, final TimeUnit unit, final RejectedExecutionHandler handler) { return new LoggingExecutor(minThreads, maxThreads, keepAliveTime, unit, new SynchronousQueue<Runnable>(), new NamedThreadFactory(name), handler); } public static ExecutorService newCachedThreadPool(final int minThreads, final int maxThreads, final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final RejectedExecutionHandler handler) { return new LoggingExecutor(minThreads, maxThreads, keepAliveTime, unit, workQueue, new NamedThreadFactory(name), handler); } public static ExecutorService newCachedThreadPool(final int minThreads, final int maxThreads, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory, final RejectedExecutionHandler handler) { return new LoggingExecutor(minThreads, maxThreads, keepAliveTime, unit, workQueue, threadFactory, handler); } /* * Single threaded scheduled executor */ public static ScheduledExecutorService newSingleThreadScheduledExecutor(final String name) { return new DelegatedScheduledExecutorService(new FailsafeScheduledExecutor(name)); } public static ScheduledExecutorService newSingleThreadScheduledExecutor(final ThreadFactory threadFactory) { return new DelegatedScheduledExecutorService(new FailsafeScheduledExecutor(1, threadFactory)); } public static ScheduledExecutorService newSingleThreadScheduledExecutor(final String name, final RejectedExecutionHandler handler) { return new DelegatedScheduledExecutorService(new FailsafeScheduledExecutor(1, name, handler)); } public static ScheduledExecutorService newSingleThreadScheduledExecutor(final ThreadFactory threadFactory, final RejectedExecutionHandler handler) { return new DelegatedScheduledExecutorService(new FailsafeScheduledExecutor(1, threadFactory, handler)); } /* * Scheduled ThreadPool */ public static ScheduledExecutorService newScheduledThreadPool(final int corePoolSize, final String name) { return new FailsafeScheduledExecutor(corePoolSize, name); } public static ScheduledExecutorService newScheduledThreadPool(final int corePoolSize, final ThreadFactory threadFactory) { return new FailsafeScheduledExecutor(corePoolSize, threadFactory); } public static ScheduledExecutorService newScheduledThreadPool(final int corePoolSize, final String name, final RejectedExecutionHandler handler) { return new FailsafeScheduledExecutor(corePoolSize, name, handler); } public static ScheduledExecutorService newScheduledThreadPool(final int corePoolSize, final ThreadFactory threadFactory, final RejectedExecutionHandler handler) { return new FailsafeScheduledExecutor(corePoolSize, threadFactory, handler); } private static class DelegatedExecutorService extends AbstractExecutorService { private final ExecutorService e; DelegatedExecutorService(final ExecutorService executor) { e = executor; } @Override public void execute(final Runnable command) { e.execute(command); } @Override public void shutdown() { e.shutdown(); } @Override public List<Runnable> shutdownNow() { return e.shutdownNow(); } @Override public boolean isShutdown() { return e.isShutdown(); } @Override public boolean isTerminated() { return e.isTerminated(); } @Override public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException { return e.awaitTermination(timeout, unit); } @Override public Future<?> submit(final Runnable task) { return e.submit(task); } @Override public <T> Future<T> submit(final Callable<T> task) { return e.submit(task); } @Override public <T> Future<T> submit(final Runnable task, final T result) { return e.submit(task, result); } @Override public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks) throws InterruptedException { return e.invokeAll(tasks); } @Override public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit) throws InterruptedException { return e.invokeAll(tasks, timeout, unit); } @Override public <T> T invokeAny(final Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return e.invokeAny(tasks); } @Override public <T> T invokeAny(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return e.invokeAny(tasks, timeout, unit); } } private static class FinalizableDelegatedExecutorService extends DelegatedExecutorService { FinalizableDelegatedExecutorService(final ExecutorService executor) { super(executor); } @Override protected void finalize() throws Throwable { super.shutdown(); super.finalize(); } } private static class DelegatedScheduledExecutorService extends DelegatedExecutorService implements ScheduledExecutorService { private final ScheduledExecutorService e; DelegatedScheduledExecutorService(final ScheduledExecutorService executor) { super(executor); e = executor; } @Override public ScheduledFuture<?> schedule(final Runnable command, final long delay, final TimeUnit unit) { return e.schedule(command, delay, unit); } @Override public <V> ScheduledFuture<V> schedule(final Callable<V> callable, final long delay, final TimeUnit unit) { return e.schedule(callable, delay, unit); } @Override public ScheduledFuture<?> scheduleAtFixedRate(final Runnable command, final long initialDelay, final long period, final TimeUnit unit) { return e.scheduleAtFixedRate(command, initialDelay, period, unit); } @Override public ScheduledFuture<?> scheduleWithFixedDelay(final Runnable command, final long initialDelay, final long delay, final TimeUnit unit) { return e.scheduleWithFixedDelay(command, initialDelay, delay, unit); } } private Executors() {} }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/concurrent/NamedThreadFactory.java
concurrent/src/main/java/org/killbill/commons/concurrent/NamedThreadFactory.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.concurrent; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Factory that sets the name of each thread it creates to {@code [name]-[id]}. * This makes debugging stack traces much easier. */ public class NamedThreadFactory implements ThreadFactory { private final AtomicInteger count = new AtomicInteger(0); private final String name; public NamedThreadFactory(final String name) { this.name = name; } @Override public Thread newThread(final Runnable runnable) { final Thread thread = new Thread(runnable); thread.setName(name + "-" + count.incrementAndGet()); return thread; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/concurrent/WithProfilingThreadPoolExecutor.java
concurrent/src/main/java/org/killbill/commons/concurrent/WithProfilingThreadPoolExecutor.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.concurrent; import org.killbill.commons.profiling.Profiling; import java.util.concurrent.BlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; public class WithProfilingThreadPoolExecutor extends DynamicThreadPoolExecutorWithLoggingOnExceptions { public WithProfilingThreadPoolExecutor(final int corePoolSize, final int maximumPoolSize, final String name, final long keepAliveTime, final TimeUnit unit) { super(corePoolSize, maximumPoolSize, name, keepAliveTime, unit); } public WithProfilingThreadPoolExecutor(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, final ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, threadFactory); } public WithProfilingThreadPoolExecutor(final int corePoolSize, final int maximumPoolSize, final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, name, keepAliveTime, unit, workQueue); } public WithProfilingThreadPoolExecutor(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); } public WithProfilingThreadPoolExecutor(final int corePoolSize, final int maximumPoolSize, final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, name, keepAliveTime, unit, workQueue, handler); } public WithProfilingThreadPoolExecutor(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory, final RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); } protected void beforeExecute(final Thread t, final Runnable runnable) { // Allocate the thread local data Profiling.setPerThreadProfilingData(); super.beforeExecute(t, runnable); } protected void afterExecute(final Runnable runnable, final Throwable exception) { super.afterExecute(runnable, exception); // Clear the thread local data Profiling.resetPerThreadProfilingData(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/concurrent/FailsafeScheduledExecutor.java
concurrent/src/main/java/org/killbill/commons/concurrent/FailsafeScheduledExecutor.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.concurrent; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Extension of {@link java.util.concurrent.ScheduledThreadPoolExecutor} that will continue to schedule a task even if the previous run had an exception. * Also ensures that uncaught exceptions are logged. */ public class FailsafeScheduledExecutor extends ScheduledThreadPoolExecutor { private static final Logger LOG = LoggerFactory.getLogger(FailsafeScheduledExecutor.class); /** * Creates a new single-threaded executor with a {@link NamedThreadFactory} of the given name. * * @param name thread name base */ public FailsafeScheduledExecutor(final String name) { this(1, name); } /** * Creates a new executor with a {@link NamedThreadFactory} of the given name. * * @param corePoolSize number of threads in the pool * @param name thread name base */ public FailsafeScheduledExecutor(final int corePoolSize, final String name) { this(corePoolSize, new NamedThreadFactory(name)); } /** * Creates a new executor with the given thread factory. * * @param corePoolSize number of threads in the pool * @param threadFactory a thread factory to use */ public FailsafeScheduledExecutor(final int corePoolSize, final ThreadFactory threadFactory) { super(corePoolSize, threadFactory); } /** * Creates a new executor with the given thread factory. * * @param corePoolSize number of threads in the pool * @param name thread name base * @param handler a rejected execution handler to use */ public FailsafeScheduledExecutor(final int corePoolSize, final String name, final RejectedExecutionHandler handler) { super(corePoolSize, new NamedThreadFactory(name), handler); } /** * Creates a new executor with the given thread factory. * * @param corePoolSize number of threads in the pool * @param threadFactory a thread factory to use * @param handler a rejected execution handler to use */ public FailsafeScheduledExecutor(final int corePoolSize, final ThreadFactory threadFactory, final RejectedExecutionHandler handler) { super(corePoolSize, threadFactory, handler); } @Override public <T> Future<T> submit(final Callable<T> task) { return super.submit(WrappedCallable.wrap(LOG, task)); } @Override public <T> Future<T> submit(final Runnable task, final T result) { final WrappedRunnable runnable = WrappedRunnable.wrap(LOG, task); final Future<T> future = super.submit(runnable, result); return WrappedRunnableFuture.wrap(runnable, future); } @Override public Future<?> submit(final Runnable task) { final WrappedRunnable runnable = WrappedRunnable.wrap(LOG, task); final Future<?> future = super.submit(runnable); return WrappedRunnableFuture.wrap(runnable, future); } @Override public void execute(final Runnable command) { super.execute(WrappedRunnable.wrap(LOG, command)); } @Override public ScheduledFuture<?> scheduleWithFixedDelay(final Runnable command, final long initialDelay, final long delay, final TimeUnit unit) { return super.scheduleWithFixedDelay(WrappedRunnable.wrap(LOG, command), initialDelay, delay, unit); } @Override public ScheduledFuture<?> scheduleAtFixedRate(final Runnable command, final long initialDelay, final long period, final TimeUnit unit) { return super.scheduleAtFixedRate(WrappedRunnable.wrap(LOG, command), initialDelay, period, unit); } @Override public <V> ScheduledFuture<V> schedule(final Callable<V> callable, final long delay, final TimeUnit unit) { return super.schedule(WrappedCallable.wrap(LOG, callable), delay, unit); } @Override public ScheduledFuture<?> schedule(final Runnable command, final long delay, final TimeUnit unit) { return super.schedule(WrappedRunnable.wrap(LOG, command), delay, unit); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/concurrent/DynamicThreadPoolExecutorWithLoggingOnExceptions.java
concurrent/src/main/java/org/killbill/commons/concurrent/DynamicThreadPoolExecutorWithLoggingOnExceptions.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.concurrent; import java.util.concurrent.BlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; // See http://stackoverflow.com/questions/19528304/how-to-get-the-threadpoolexecutor-to-increase-threads-to-max-before-queueing/19538899#19538899 public class DynamicThreadPoolExecutorWithLoggingOnExceptions extends LoggingExecutor { private final int inputSpecifiedCorePoolSize; private int currentTasks; public DynamicThreadPoolExecutorWithLoggingOnExceptions(final int corePoolSize, final int maximumPoolSize, final String name, final long keepAliveTime, final TimeUnit unit) { super(corePoolSize, maximumPoolSize, name, keepAliveTime, unit); this.inputSpecifiedCorePoolSize = corePoolSize; } public DynamicThreadPoolExecutorWithLoggingOnExceptions(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, final ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, threadFactory); this.inputSpecifiedCorePoolSize = corePoolSize; } public DynamicThreadPoolExecutorWithLoggingOnExceptions(final int corePoolSize, final int maximumPoolSize, final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, name, keepAliveTime, unit, workQueue); this.inputSpecifiedCorePoolSize = corePoolSize; } public DynamicThreadPoolExecutorWithLoggingOnExceptions(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); this.inputSpecifiedCorePoolSize = corePoolSize; } public DynamicThreadPoolExecutorWithLoggingOnExceptions(final int corePoolSize, final int maximumPoolSize, final String name, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, name, keepAliveTime, unit, workQueue, handler); this.inputSpecifiedCorePoolSize = corePoolSize; } public DynamicThreadPoolExecutorWithLoggingOnExceptions(final int corePoolSize, final int maximumPoolSize, final long keepAliveTime, final TimeUnit unit, final BlockingQueue<Runnable> workQueue, final ThreadFactory threadFactory, final RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); this.inputSpecifiedCorePoolSize = corePoolSize; } @Override public void execute(final Runnable runnable) { synchronized (this) { currentTasks++; setCorePoolSizeToTaskCountWithinBounds(); } super.execute(runnable); } @Override protected void afterExecute(final Runnable runnable, final Throwable throwable) { super.afterExecute(runnable, throwable); synchronized (this) { currentTasks--; setCorePoolSizeToTaskCountWithinBounds(); } } private void setCorePoolSizeToTaskCountWithinBounds() { int updatedCorePoolSize = currentTasks; if (updatedCorePoolSize < inputSpecifiedCorePoolSize) { updatedCorePoolSize = inputSpecifiedCorePoolSize; } if (updatedCorePoolSize > getMaximumPoolSize()) { updatedCorePoolSize = getMaximumPoolSize(); } setCorePoolSize(updatedCorePoolSize); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/concurrent/WrappedRunnableFuture.java
concurrent/src/main/java/org/killbill/commons/concurrent/WrappedRunnableFuture.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.concurrent; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class WrappedRunnableFuture<V> implements Future<V> { private final WrappedRunnable runnable; private final Future<V> delegate; private WrappedRunnableFuture(final WrappedRunnable runnable, final Future<V> delegate) { this.runnable = runnable; this.delegate = delegate; } public static <V> Future<V> wrap(final WrappedRunnable runnable, final Future<V> delegate) { return new WrappedRunnableFuture<V>(runnable, delegate); } @Override public boolean cancel(final boolean mayInterruptIfRunning) { return delegate.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return delegate.isCancelled(); } @Override public boolean isDone() { return delegate.isDone(); } @Override public V get() throws InterruptedException, ExecutionException { final V result = delegate.get(); checkForException(); return result; } @Override public V get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { final V result = delegate.get(timeout, unit); checkForException(); return result; } private void checkForException() throws InterruptedException, ExecutionException { final Throwable exception = runnable.getException(); if (exception != null) { if (exception instanceof InterruptedException) { throw (InterruptedException) exception; } if (exception instanceof ExecutionException) { throw (ExecutionException) exception; } throw new ExecutionException(exception); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/profiling/ProfilingFeature.java
concurrent/src/main/java/org/killbill/commons/profiling/ProfilingFeature.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.profiling; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ProfilingFeature { private static final int JAXRS_MASK = 0x1; private static final int API_MASK = 0x2; private static final int DAO_MASK = 0x4; private static final int DAO_DETAILS_MASK = 0x8; private static final int GLOCK_MASK = 0x10; private static final int PLUGIN_MASK = 0x20; private static final int DAO_CONNECTION_MASK = 0x40; public enum ProfilingFeatureType { JAXRS(JAXRS_MASK), API(API_MASK), DAO(DAO_MASK), DAO_DETAILS(DAO_MASK, DAO_DETAILS_MASK), DAO_CONNECTION(DAO_CONNECTION_MASK), GLOCK(GLOCK_MASK), PLUGIN(PLUGIN_MASK); private final int mask; ProfilingFeatureType(final int... masks) { int tmp = 0; for (final int mask1 : masks) { tmp |= mask1; } this.mask = tmp; } public int getMask() { return mask; } } private final Pattern featurePattern = Pattern.compile("\\s*,?\\s*((?:[A-Z])+(?:_)?+(?:[A-Z])*)"); private final int profilingBits; public ProfilingFeature() { int tmp = 0; for (final ProfilingFeatureType cur : ProfilingFeatureType.values()) { tmp |= cur.getMask(); } this.profilingBits = tmp; } public ProfilingFeature(final String features) { int tmp = 0; final Matcher matcher = featurePattern.matcher(features); while (matcher.find()) { final String cur = matcher.group(1); try { final ProfilingFeatureType featureType = ProfilingFeatureType.valueOf(cur); tmp |= featureType.getMask(); } catch (final IllegalArgumentException e) { // Ignore bad entry like 'FOO' } } this.profilingBits = tmp; } public boolean isDefined(final ProfilingFeatureType type) { return (profilingBits & type.getMask()) == type.getMask(); } public boolean isProfilingJAXRS() { return isDefined(ProfilingFeatureType.JAXRS); } public boolean isProfilingAPI() { return isDefined(ProfilingFeatureType.API); } public boolean isProfilingDAO() { return isDefined(ProfilingFeatureType.DAO); } public boolean isProfilingDAOWithDetails() { return isDefined(ProfilingFeatureType.DAO_DETAILS); } public boolean isProfilingPlugin() { return isDefined(ProfilingFeatureType.PLUGIN); } public boolean isProfilingGlock() { return isDefined(ProfilingFeatureType.GLOCK); } public boolean isProfilingDaoConnection() { return isDefined(ProfilingFeatureType.DAO_CONNECTION); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/profiling/ProfilingData.java
concurrent/src/main/java/org/killbill/commons/profiling/ProfilingData.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.profiling; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nullable; public class ProfilingData { private final List<ProfilingDataItem> rawData; private final ProfilingFeature profileFeature; public ProfilingData(final ProfilingFeature profileFeature) { this.profileFeature = profileFeature; this.rawData = new ArrayList<ProfilingDataItem>(); } public void merge(@Nullable final ProfilingData otherData) { if (otherData == null || otherData.getRawData().isEmpty()) { return; } rawData.addAll(otherData.getRawData()); Collections.sort(rawData, new Comparator<ProfilingDataItem>() { @Override public int compare(final ProfilingDataItem o1, final ProfilingDataItem o2) { return o1.getTimestampNsec().compareTo(o2.getTimestampNsec()); } }); } public void addStart(final ProfilingFeature.ProfilingFeatureType profileType, final String id) { rawData.add(new ProfilingDataItem(profileType, id, LogLineType.START)); } public void addEnd(final ProfilingFeature.ProfilingFeatureType profileType, final String id) { rawData.add(new ProfilingDataItem(profileType, id, LogLineType.END)); } public List<ProfilingDataItem> getRawData() { if (rawData == null || rawData.isEmpty()) { return Collections.emptyList(); } return rawData.stream() .filter(input -> input != null && profileFeature.isDefined(input.getProfileType())) .collect(Collectors.toList()); } public ProfilingFeature getProfileFeature() { return profileFeature; } public static class ProfilingDataItem { private final ProfilingFeature.ProfilingFeatureType profileType; private final String id; private final Long timestampNsec; private final LogLineType lineType; private ProfilingDataItem(final ProfilingFeature.ProfilingFeatureType profileType, final String id, final LogLineType lineType) { this.profileType = profileType; this.id = id; this.lineType = lineType; this.timestampNsec = System.nanoTime(); } public ProfilingFeature.ProfilingFeatureType getProfileType() { return profileType; } public String getKey() { return profileType + ":" + id; } public Long getTimestampNsec() { return timestampNsec; } public LogLineType getLineType() { return lineType; } } public enum LogLineType { START, END } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/profiling/Profiling.java
concurrent/src/main/java/org/killbill/commons/profiling/Profiling.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.profiling; public class Profiling<ReturnType, ExceptionType extends Throwable> { private static final ThreadLocal<ProfilingData> perThreadProfilingData = new ThreadLocal<ProfilingData>(); public interface WithProfilingCallback<ReturnType, ExceptionType extends Throwable> { public ReturnType execute() throws ExceptionType; } public ReturnType executeWithProfiling(final ProfilingFeature.ProfilingFeatureType profilingType, final String profilingId, final WithProfilingCallback<ReturnType, ExceptionType> callback) throws ExceptionType { // Nothing to do final ProfilingData profilingData = Profiling.getPerThreadProfilingData(); if (profilingData == null) { return callback.execute(); } profilingData.addStart(profilingType, profilingId); try { return callback.execute(); } finally { profilingData.addEnd(profilingType, profilingId); } } public static ProfilingData getPerThreadProfilingData() { return perThreadProfilingData.get(); } public static void setPerThreadProfilingData() { final ProfilingFeature profilingFeature = new ProfilingFeature(); perThreadProfilingData.set(new ProfilingData(profilingFeature)); } public static void setPerThreadProfilingData(final String profileFeatures) { final ProfilingFeature profilingFeature = new ProfilingFeature(profileFeatures); perThreadProfilingData.set(new ProfilingData(profilingFeature)); } public static void resetPerThreadProfilingData() { perThreadProfilingData.set(null); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/request/RequestData.java
concurrent/src/main/java/org/killbill/commons/request/RequestData.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.request; public class RequestData { private final String requestId; public RequestData(final String requestId) { this.requestId = requestId; } public String getRequestId() { return requestId; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/concurrent/src/main/java/org/killbill/commons/request/Request.java
concurrent/src/main/java/org/killbill/commons/request/Request.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.commons.request; public class Request { private static final ThreadLocal<RequestData> perThreadRequest = new ThreadLocal<RequestData>(); public static RequestData getPerThreadRequestData() { return perThreadRequest.get(); } public static void setPerThreadRequestData(final RequestData requestData) { perThreadRequest.set(requestData); } public static void resetPerThreadRequestData() { perThreadRequest.set(null); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/TestSetup.java
queue/src/test/java/org/killbill/TestSetup.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Map; import org.killbill.bus.api.PersistentBusConfig; import org.killbill.clock.ClockMock; import org.killbill.commons.embeddeddb.EmbeddedDB; import org.killbill.commons.embeddeddb.h2.H2EmbeddedDB; import org.killbill.commons.embeddeddb.mysql.MySQLEmbeddedDB; import org.killbill.commons.embeddeddb.postgresql.PostgreSQLEmbeddedDB; import org.killbill.commons.jdbi.notification.DatabaseTransactionNotificationApi; import org.killbill.commons.jdbi.transaction.NotificationTransactionHandler; import org.killbill.commons.metrics.api.MetricRegistry; import org.killbill.commons.metrics.impl.NoOpMetricRegistry; import org.killbill.commons.utils.io.ByteStreams; import org.killbill.commons.utils.io.Resources; import org.killbill.notificationq.api.NotificationQueueConfig; import org.killbill.queue.InTransaction; import org.skife.config.ConfigSource; import org.skife.config.AugmentedConfigurationObjectFactory; import org.skife.config.SimplePropertyConfigSource; import org.skife.jdbi.v2.DBI; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import static org.testng.Assert.assertNotNull; public class TestSetup { private static final String TEST_DB_PROPERTY_PREFIX = "org.killbill.billing.dbi.test."; protected static final Long SEARCH_KEY_1 = 1L; protected static final Long SEARCH_KEY_2 = 2L; protected EmbeddedDB embeddedDB; protected DBI dbi; protected PersistentBusConfig persistentBusConfig; protected NotificationQueueConfig notificationQueueConfig; protected ClockMock clock; protected final MetricRegistry metricRegistry = new NoOpMetricRegistry(); protected DatabaseTransactionNotificationApi databaseTransactionNotificationApi; @BeforeClass(groups = "slow") public void beforeClass() throws Exception { loadSystemPropertiesFromClasspath("/org/killbill/queue/queue.properties"); clock = new ClockMock(); // See also PlatformDBTestingHelper if ("true".equals(System.getProperty(TEST_DB_PROPERTY_PREFIX + "h2"))) { embeddedDB = new H2EmbeddedDB("killbillq", "killbillq", "killbillq"); } else if ("true".equals(System.getProperty(TEST_DB_PROPERTY_PREFIX + "postgresql"))) { embeddedDB = new PostgreSQLEmbeddedDB("killbillq", "killbillq"); } else { embeddedDB = new MySQLEmbeddedDB("killbillq", "killbillq", "killbillq"); } embeddedDB.initialize(); embeddedDB.start(); if (embeddedDB.getDBEngine() == EmbeddedDB.DBEngine.POSTGRESQL) { embeddedDB.executeScript("CREATE DOMAIN datetime AS timestamp without time zone;" + "CREATE OR REPLACE FUNCTION last_insert_id() RETURNS BIGINT AS $$\n" + " DECLARE\n" + " result BIGINT;\n" + " BEGIN\n" + " SELECT lastval() INTO result;\n" + " RETURN result;\n" + " EXCEPTION WHEN OTHERS THEN\n" + " SELECT NULL INTO result;\n" + " RETURN result;\n" + " END;\n" + "$$ LANGUAGE plpgsql VOLATILE;"); } final String ddl = toString(Resources.getResource("org/killbill/queue/ddl.sql").openStream()); embeddedDB.executeScript(ddl); embeddedDB.refreshTableNames(); databaseTransactionNotificationApi = new DatabaseTransactionNotificationApi(); dbi = new DBI(embeddedDB.getDataSource()); InTransaction.setupDBI(dbi); dbi.setTransactionHandler(new NotificationTransactionHandler(databaseTransactionNotificationApi)); final ConfigSource configSource = new SimplePropertyConfigSource(System.getProperties()); persistentBusConfig = new AugmentedConfigurationObjectFactory(configSource).buildWithReplacements( PersistentBusConfig.class, Map.of("instanceName", "main")); notificationQueueConfig = new AugmentedConfigurationObjectFactory(configSource).buildWithReplacements( NotificationQueueConfig.class, Map.of("instanceName", "main")); } @BeforeMethod(groups = "slow") public void beforeMethod() throws Exception { CreatorName.reset(); System.clearProperty(CreatorName.QUEUE_CREATOR_NAME); embeddedDB.cleanupAllTables(); clock.resetDeltaFromReality(); } @AfterClass(groups = "slow") public void afterClass() throws Exception { embeddedDB.stop(); } public static String toString(final InputStream inputStream) throws IOException { try { return new String(ByteStreams.toByteArray(inputStream), StandardCharsets.UTF_8); } finally { inputStream.close(); } } public DBI getDBI() { return dbi; } public PersistentBusConfig getPersistentBusConfig() { return persistentBusConfig; } public NotificationQueueConfig getNotificationQueueConfig() { return notificationQueueConfig; } private static void loadSystemPropertiesFromClasspath(final String resource) { final URL url = TestSetup.class.getResource(resource); assertNotNull(url); try { System.getProperties().load(url.openStream()); } catch (final IOException e) { throw new RuntimeException(e); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/TestCreatorName.java
queue/src/test/java/org/killbill/TestCreatorName.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill; import org.testng.Assert; import org.testng.annotations.Test; public class TestCreatorName { @Test(groups = "fast") public void testNameTooLong() { final String oldProperty = System.getProperty(CreatorName.QUEUE_CREATOR_NAME); CreatorName.reset(); try { System.setProperty(CreatorName.QUEUE_CREATOR_NAME, "testing-worker-linux-08b40318-1-526-linux-12-55205367"); Assert.assertEquals(CreatorName.get(), "testing-worker-linux-08b40318-1-526-linux-12-"); } finally { if (oldProperty != null) { System.setProperty(CreatorName.QUEUE_CREATOR_NAME, oldProperty); } CreatorName.reset(); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/notificationq/MockNotificationQueueService.java
queue/src/test/java/org/killbill/notificationq/MockNotificationQueueService.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.List; import javax.inject.Inject; import org.killbill.CreatorName; import org.killbill.clock.Clock; import org.killbill.commons.metrics.api.MetricRegistry; import org.killbill.notificationq.api.NotificationEvent; import org.killbill.notificationq.api.NotificationQueue; import org.killbill.notificationq.api.NotificationQueueConfig; import org.killbill.notificationq.dao.NotificationEventModelDao; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.dispatching.EventEntryDeserializer; import org.skife.jdbi.v2.DBI; public class MockNotificationQueueService extends NotificationQueueServiceBase { @Inject public MockNotificationQueueService(final Clock clock, final NotificationQueueConfig config, final DBI dbi, final MetricRegistry metricRegistry) { super(clock, config, dbi, metricRegistry); } @Override protected NotificationQueue createNotificationQueueInternal(final String svcName, final String queueName, final NotificationQueueHandler handler) { return new MockNotificationQueue(clock, svcName, queueName, handler, this); } @Override public DispatchResultMetrics doDispatchEvents() { int retry = 2; do { try { int result = 0; for (final String queueName : queues.keySet()) { final NotificationQueue cur = queues.get(queueName); if (cur != null) { result += doProcessEventsForQueue((MockNotificationQueue) cur); } } return new DispatchResultMetrics(result, -1); } catch (final ConcurrentModificationException e) { retry--; } } while (retry > 0); return new DispatchResultMetrics(0, -1); } private int doProcessEventsForQueue(final MockNotificationQueue queue) { int result = 0; final List<NotificationEventModelDao> processedNotifications = new ArrayList<NotificationEventModelDao>(); final List<NotificationEventModelDao> oldNotifications = new ArrayList<NotificationEventModelDao>(); final List<NotificationEventModelDao> readyNotifications = queue.getReadyNotifications(); for (final NotificationEventModelDao cur : readyNotifications) { final NotificationEvent key = EventEntryDeserializer.deserialize(cur, objectReader); queue.getHandler().handleReadyNotification(key, cur.getEffectiveDate(), cur.getFutureUserToken(), cur.getSearchKey1(), cur.getSearchKey2()); final NotificationEventModelDao processedNotification = new NotificationEventModelDao(cur.getRecordId(), CreatorName.get(), CreatorName.get(), clock.getUTCNow(), getClock().getUTCNow().plus(CLAIM_TIME_MS), PersistentQueueEntryLifecycleState.PROCESSED, cur.getClassName(), cur.getEventJson(), 0L, cur.getUserToken(), cur.getSearchKey1(), cur.getSearchKey2(), cur.getFutureUserToken(), cur.getEffectiveDate(), "MockQueue"); oldNotifications.add(cur); processedNotifications.add(processedNotification); result++; } queue.markProcessedNotifications(oldNotifications, processedNotifications); return result; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/notificationq/TestNotificationQueue.java
queue/src/test/java/org/killbill/notificationq/TestNotificationQueue.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.joda.time.DateTime; import org.joda.time.Period; import org.killbill.TestSetup; import org.killbill.billing.util.queue.QueueRetryException; import org.killbill.clock.DefaultClock; import org.killbill.commons.utils.collect.Iterables; import org.killbill.commons.utils.collect.Iterators; import org.killbill.notificationq.api.NotificationEvent; import org.killbill.notificationq.api.NotificationEventWithMetadata; import org.killbill.notificationq.api.NotificationQueue; import org.killbill.notificationq.api.NotificationQueueService; import org.killbill.notificationq.api.NotificationQueueService.NotificationQueueHandler; import org.killbill.notificationq.dao.NotificationEventModelDao; import org.killbill.notificationq.dao.NotificationSqlDao; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.retry.RetryableHandler; import org.killbill.queue.retry.RetryableService; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionStatus; import org.skife.jdbi.v2.tweak.HandleCallback; import org.skife.jdbi.v2.util.IntegerMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import static java.util.concurrent.TimeUnit.MINUTES; import static org.awaitility.Awaitility.await; import static org.testng.Assert.assertTrue; public class TestNotificationQueue extends TestSetup { private final Logger log = LoggerFactory.getLogger(TestNotificationQueue.class); private static final UUID TOKEN_ID = UUID.randomUUID(); private static final long SEARCH_KEY_1 = 65; private static final long SEARCH_KEY_2 = 34; private NotificationQueueService queueService; private RetryableNotificationQueueService retryableQueueService; private volatile int eventsReceived; private static final class RetryableNotificationQueueService extends RetryableService { public RetryableNotificationQueueService(final NotificationQueueService notificationQueueService) { super(notificationQueueService); } } private static final class TestNotificationKey implements NotificationEvent, Comparable<TestNotificationKey> { private final String value; @JsonCreator public TestNotificationKey(@JsonProperty("value") final String value) { super(); this.value = value; } public String getValue() { return value; } @Override public int compareTo(final TestNotificationKey arg0) { return value.compareTo(arg0.value); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(value); return sb.toString(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof TestNotificationKey)) { return false; } final TestNotificationKey that = (TestNotificationKey) o; if (value != null ? !value.equals(that.value) : that.value != null) { return false; } return true; } @Override public int hashCode() { return value != null ? value.hashCode() : 0; } } @Override @BeforeMethod(groups = "slow") public void beforeMethod() throws Exception { super.beforeMethod(); queueService = new DefaultNotificationQueueService(getDBI(), clock, getNotificationQueueConfig(), metricRegistry); retryableQueueService = new RetryableNotificationQueueService(queueService); eventsReceived = 0; } /** * Test that we can post a notification in the future from a transaction and get the notification * callback with the correct key when the time is ready * * @throws Exception */ @Test(groups = "slow") public void testSimpleNotification() throws Exception { final Map<NotificationEvent, Boolean> expectedNotifications = new TreeMap<NotificationEvent, Boolean>(); final NotificationQueue queue = queueService.createNotificationQueue("test-svc", "foo", new NotificationQueueHandler() { @Override public void handleReadyNotification(final NotificationEvent eventJson, final DateTime eventDateTime, final UUID userToken, final Long searchKey1, final Long searchKey2) { synchronized (expectedNotifications) { log.info("Handler received key: " + eventJson); expectedNotifications.put(eventJson, Boolean.TRUE); expectedNotifications.notify(); } } }); final UUID key1 = UUID.randomUUID(); final NotificationEvent eventJson1 = new TestNotificationKey(key1.toString()); expectedNotifications.put(eventJson1, Boolean.FALSE); final UUID key2 = UUID.randomUUID(); final NotificationEvent eventJson2 = new TestNotificationKey(key2.toString()); expectedNotifications.put(eventJson2, Boolean.FALSE); final UUID key3 = UUID.randomUUID(); final NotificationEvent eventJson3 = new TestNotificationKey(key3.toString()); expectedNotifications.put(eventJson3, Boolean.FALSE); final UUID key4 = UUID.randomUUID(); final NotificationEvent eventJson4 = new TestNotificationKey(key4.toString()); expectedNotifications.put(eventJson4, Boolean.FALSE); final UUID key5 = UUID.randomUUID(); final NotificationEvent eventJson5 = new TestNotificationKey(key5.toString()); expectedNotifications.put(eventJson5, Boolean.FALSE); queue.startQueue(); // ms will be truncated in the database final DateTime now = DefaultClock.truncateMs(new DateTime()); final DateTime readyTime = now.plusMillis(2000); final DBI dbi = getDBI(); dbi.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(final Handle conn, final TransactionStatus status) throws Exception { queue.recordFutureNotificationFromTransaction(conn.getConnection(), readyTime, eventJson1, TOKEN_ID, 1L, SEARCH_KEY_2); log.info("Posted key: " + eventJson1); return null; } }); dbi.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(final Handle conn, final TransactionStatus status) throws Exception { queue.recordFutureNotificationFromTransaction(conn.getConnection(), readyTime, eventJson2, TOKEN_ID, SEARCH_KEY_1, 1L); log.info("Posted key: " + eventJson2); return null; } }); dbi.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(final Handle conn, final TransactionStatus status) throws Exception { queue.recordFutureNotificationFromTransaction(conn.getConnection(), readyTime, eventJson3, TOKEN_ID, SEARCH_KEY_1, SEARCH_KEY_2); log.info("Posted key: " + eventJson3); return null; } }); dbi.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(final Handle conn, final TransactionStatus status) throws Exception { queue.recordFutureNotificationFromTransaction(conn.getConnection(), readyTime, eventJson4, TOKEN_ID, SEARCH_KEY_1, SEARCH_KEY_2); log.info("Posted key: " + eventJson4); return null; } }); dbi.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(final Handle conn, final TransactionStatus status) throws Exception { queue.recordFutureNotificationFromTransaction(conn.getConnection(), readyTime.plusMonths(1), eventJson5, TOKEN_ID, 1L, 1L); log.info("Posted key: " + eventJson5); return null; } }); Assert.assertEquals(Iterables.<NotificationEventWithMetadata<TestNotificationKey>>size(queue.getInProcessingNotifications()), 0); Assert.assertEquals(queue.getNbReadyEntries(readyTime), 4); final List<NotificationEventWithMetadata<?>> futuresAll = Iterables.toUnmodifiableList(queue.getFutureNotificationForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2)); Assert.assertEquals(futuresAll.size(), 2); int found = 0; for (int i = 0; i < 2; i++) { final TestNotificationKey testNotificationKey = (TestNotificationKey) futuresAll.get(i).getEvent(); if (testNotificationKey.getValue().equals(key3.toString()) || testNotificationKey.getValue().equals(key4.toString())) { found++; } } Assert.assertEquals(found, 2); final List<NotificationEventWithMetadata<?>> futures2 = Iterables.toUnmodifiableList(queue.getFutureNotificationForSearchKey2(null, SEARCH_KEY_2)); Assert.assertEquals(futures2.size(), 3); found = 0; for (int i = 0; i < 3; i++) { final TestNotificationKey testNotificationKey = (TestNotificationKey) futures2.get(i).getEvent(); if (testNotificationKey.getValue().equals(key3.toString()) || testNotificationKey.getValue().equals(key4.toString()) || testNotificationKey.getValue().equals(key1.toString())) { found++; } } Assert.assertEquals(found, 3); // Move time in the future after the notification effectiveDate clock.setDeltaFromReality(3000); // Notification should have kicked but give it at least a sec' for thread scheduling await().atMost(1, MINUTES) .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { synchronized (expectedNotifications) { return expectedNotifications.get(eventJson1) && expectedNotifications.get(eventJson2) && expectedNotifications.get(eventJson3) && expectedNotifications.get(eventJson4) && queue.getNbReadyEntries(readyTime) == 0; } } } ); // No-op Assert.assertEquals(Iterables.size(queue.getFutureNotificationForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2)), 0); queue.removeFutureNotificationsForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2); Assert.assertEquals(Iterables.size(queue.getFutureNotificationForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2)), 0); Assert.assertEquals(Iterables.size(queue.getFutureNotificationForSearchKeys(1L, 1L)), 1); queue.removeFutureNotificationsForSearchKeys(1L, 1L); Assert.assertEquals(Iterables.size(queue.getFutureNotificationForSearchKeys(1L, 1L)), 0); queue.stopQueue(); } @Test(groups = "slow") public void testManyNotifications() throws Exception { final Map<String, Boolean> expectedNotifications = new TreeMap<String, Boolean>(); final NotificationQueue queue = queueService.createNotificationQueue("test-svc", "many", new NotificationQueueHandler() { @Override public void handleReadyNotification(final NotificationEvent eventJson, final DateTime eventDateTime, final UUID userToken, final Long searchKey1, final Long searchKey2) { synchronized (expectedNotifications) { log.info("Handler received key: " + eventJson.toString()); expectedNotifications.put(((TestNotificationKey)eventJson).getValue(), Boolean.TRUE); expectedNotifications.notify(); } } }); queue.startQueue(); final DateTime now = clock.getUTCNow(); final int MAX_NOTIFICATIONS = 100; for (int i = 0; i < MAX_NOTIFICATIONS; i++) { final String value = new Integer(i).toString(); expectedNotifications.put(value, Boolean.FALSE); } for (int i = 0; i < MAX_NOTIFICATIONS; i++) { final int nextReadyTimeIncrementMs = 1000; final int currentIteration = i; final String value = new Integer(i).toString(); final NotificationEvent eventJson = new TestNotificationKey(value); final DBI dbi = getDBI(); dbi.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(final Handle conn, final TransactionStatus status) throws Exception { queue.recordFutureNotificationFromTransaction(conn.getConnection(), now.plus((currentIteration + 1) * nextReadyTimeIncrementMs), eventJson, TOKEN_ID, SEARCH_KEY_1, SEARCH_KEY_2); return null; } }); // Move time in the future after the notification effectiveDate if (i == 0) { clock.setDeltaFromReality(nextReadyTimeIncrementMs); } else { clock.addDeltaFromReality(nextReadyTimeIncrementMs); } } // Wait a little longer since there are a lot of callback that need to happen int nbTry = MAX_NOTIFICATIONS + 1; boolean success = false; do { synchronized (expectedNotifications) { final Collection<Boolean> completed = expectedNotifications.values().stream() .filter(input -> input) .collect(Collectors.toUnmodifiableList()); if (completed.size() == MAX_NOTIFICATIONS) { success = true; break; } log.info(String.format("BEFORE WAIT : Got %d notifications at time %s (real time %s), nbTry=%d", completed.size(), clock.getUTCNow(), new DateTime(), nbTry)); expectedNotifications.wait(1000); } } while (!success); queue.stopQueue(); log.info("GOT SIZE : {}", expectedNotifications.values().stream().filter(input -> input).collect(Collectors.toUnmodifiableList())); assertTrue(success); } /** * Test that we can post a notification in the future from a transaction and get the notification * callback with the correct key when the time is ready * * @throws Exception */ @Test(groups = "slow") public void testMultipleHandlerNotification() throws Exception { final Map<NotificationEvent, Boolean> expectedNotificationsFred = new TreeMap<>(); final Map<NotificationEvent, Boolean> expectedNotificationsBarney = new TreeMap<>(); final NotificationQueue queueFred = queueService.createNotificationQueue("UtilTest", "Fred", new NotificationQueueHandler() { @Override public void handleReadyNotification(final NotificationEvent eventJson, final DateTime eventDateTime, final UUID userToken, final Long searchKey1, final Long searchKey2) { log.info("Fred received key: " + eventJson); expectedNotificationsFred.put(eventJson, Boolean.TRUE); eventsReceived++; } }); final NotificationQueue queueBarney = queueService.createNotificationQueue("UtilTest", "Barney", new NotificationQueueHandler() { @Override public void handleReadyNotification(final NotificationEvent eventJson, final DateTime eventDateTime, final UUID userToken, final Long searchKey1, final Long searchKey2) { log.info("Barney received key: " + eventJson); expectedNotificationsBarney.put(eventJson, Boolean.TRUE); eventsReceived++; } }); queueFred.startQueue(); // We don't start Barney so it can never pick up notifications final UUID key = UUID.randomUUID(); final DateTime now = new DateTime(); final DateTime readyTime = now.plusMillis(2000); final NotificationEvent eventJsonFred = new TestNotificationKey("Fred"); final NotificationEvent eventJsonBarney = new TestNotificationKey("Barney"); expectedNotificationsFred.put(eventJsonFred, Boolean.FALSE); expectedNotificationsFred.put(eventJsonBarney, Boolean.FALSE); final DBI dbi = getDBI(); dbi.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(final Handle conn, final TransactionStatus status) throws Exception { queueFred.recordFutureNotificationFromTransaction(conn.getConnection(), readyTime, eventJsonFred, TOKEN_ID, SEARCH_KEY_1, SEARCH_KEY_2); log.info("posted key: " + eventJsonFred.toString()); queueBarney.recordFutureNotificationFromTransaction(conn.getConnection(), readyTime, eventJsonBarney, TOKEN_ID, SEARCH_KEY_1, SEARCH_KEY_2); log.info("posted key: " + eventJsonBarney.toString()); return null; } }); // Move time in the future after the notification effectiveDate clock.setDeltaFromReality(3000); // Note the timeout is short on this test, but expected behaviour is that it times out. // We are checking that the Fred queue does not pick up the Barney event try { await().atMost(5, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return eventsReceived >= 2; } }); Assert.fail("There should only have been one event for the queue to pick up - it got more than that"); } catch (final Exception e) { // expected behavior } queueFred.stopQueue(); Assert.assertTrue(expectedNotificationsFred.get(eventJsonFred)); Assert.assertFalse(expectedNotificationsFred.get(eventJsonBarney)); } private class NotificationQueueHandlerWithExceptions implements NotificationQueueHandler { private final List<Period> retrySchedule; private final int nbTotalExceptionsToThrow; private int nbExceptionsThrown; public boolean shouldFail = true; public NotificationQueueHandlerWithExceptions(final List<Period> retrySchedule) { this(retrySchedule, 0, 0); } public NotificationQueueHandlerWithExceptions(final int nbTotalExceptionsToThrow) { this(null, nbTotalExceptionsToThrow, 0); } public NotificationQueueHandlerWithExceptions(final List<Period> retrySchedule, final int nbTotalExceptionsToThrow, final int nbExceptionsThrown) { this.retrySchedule = retrySchedule; this.nbTotalExceptionsToThrow = nbTotalExceptionsToThrow; this.nbExceptionsThrown = nbExceptionsThrown; } @Override public void handleReadyNotification(final NotificationEvent eventJson, final DateTime eventDateTime, final UUID userToken, final Long searchKey1, final Long searchKey2) { if (!shouldFail) { eventsReceived++; return; } final NullPointerException exceptionForTests = new NullPointerException("Expected exception for tests"); if (retrySchedule != null) { throw new QueueRetryException(exceptionForTests, retrySchedule); } if (nbExceptionsThrown < nbTotalExceptionsToThrow) { nbExceptionsThrown++; throw exceptionForTests; } eventsReceived++; } public void shouldFail(final boolean shouldFail) { this.shouldFail = shouldFail; } } @Test(groups = "slow") public void testWithExceptionAndRetrySuccess() throws Exception { final NotificationQueue queueWithExceptionAndRetrySuccess = queueService.createNotificationQueue("ExceptionAndRetrySuccess", "svc", new NotificationQueueHandlerWithExceptions(1)); try { queueWithExceptionAndRetrySuccess.startQueue(); final DateTime now = new DateTime(); final DateTime readyTime = now.plusMillis(2000); final NotificationEvent eventJson = new TestNotificationKey("Foo"); queueWithExceptionAndRetrySuccess.recordFutureNotification(readyTime, eventJson, TOKEN_ID, SEARCH_KEY_1, SEARCH_KEY_2); // Move time in the future after the notification effectiveDate clock.setDeltaFromReality(3000); await().atMost(5, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { final Integer retryCount = dbi.withHandle(new HandleCallback<Integer>() { @Override public Integer withHandle(final Handle handle) throws Exception { return handle.createQuery(String.format("select error_count from %s", notificationQueueConfig.getHistoryTableName())).map(IntegerMapper.FIRST).first(); } }); return retryCount != null && retryCount == 1 && eventsReceived == 1; } }); } finally { queueWithExceptionAndRetrySuccess.stopQueue(); } } @Test(groups = "slow") public void testWithExceptionAndFailed() throws Exception { final NotificationQueue queueWithExceptionAndFailed = queueService.createNotificationQueue("ExceptionAndRetrySuccess", "svc", new NotificationQueueHandlerWithExceptions(3)); try { queueWithExceptionAndFailed.startQueue(); final DateTime now = new DateTime(); final DateTime readyTime = now.plusMillis(2000); final NotificationEvent eventJson = new TestNotificationKey("Foo"); queueWithExceptionAndFailed.recordFutureNotification(readyTime, eventJson, TOKEN_ID, SEARCH_KEY_1, SEARCH_KEY_2); // Move time in the future after the notification effectiveDate clock.setDeltaFromReality(3000); await().atMost(10, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { final Integer retryCount = dbi.withHandle(new HandleCallback<Integer>() { @Override public Integer withHandle(final Handle handle) throws Exception { return handle.createQuery(String.format("select error_count from %s", notificationQueueConfig.getHistoryTableName())).map(IntegerMapper.FIRST).first(); } }); return retryCount != null && retryCount == 3; } }); } finally { queueWithExceptionAndFailed.stopQueue(); } } @Test(groups = "slow") public void testRetryStateForNotifications() throws Exception { // 4 retries final NotificationQueueHandlerWithExceptions handlerDelegate = new NotificationQueueHandlerWithExceptions(List.of(Period.millis(1), Period.millis(1), Period.millis(1), Period.days(1))); final NotificationQueueHandler retryableHandler = new RetryableHandler(clock, retryableQueueService, handlerDelegate); final NotificationQueue queueWithExceptionAndFailed = queueService.createNotificationQueue("svc", "queueName", retryableHandler); try { retryableQueueService.initialize(queueWithExceptionAndFailed.getQueueName(), handlerDelegate); retryableQueueService.start(); queueWithExceptionAndFailed.startQueue(); final DateTime now = new DateTime(); final DateTime readyTime = now.plusMillis(2000); final NotificationEvent eventJson = new TestNotificationKey("Foo"); queueWithExceptionAndFailed.recordFutureNotification(readyTime, eventJson, TOKEN_ID, SEARCH_KEY_1, SEARCH_KEY_2); // Move time in the future after the notification effectiveDate clock.setDeltaFromReality(3000); final NotificationSqlDao notificationSqlDao = dbi.onDemand(NotificationSqlDao.class); // Make sure all notifications are processed await().atMost(10, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return Iterators.size(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("svc:queueName", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())) == 1 && Iterators.size(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("notifications-retries:queueName", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())) == 3; } }); // Initial event was processed once List<NotificationEventModelDao> historicalEntriesForOriginalEvent = Iterators.toUnmodifiableList(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("svc:queueName", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())); Assert.assertEquals(historicalEntriesForOriginalEvent.size(), 1); Assert.assertEquals((long) historicalEntriesForOriginalEvent.get(0).getErrorCount(), (long) 0); // State is initially FAILED Assert.assertEquals(historicalEntriesForOriginalEvent.get(0).getProcessingState(), PersistentQueueEntryLifecycleState.FAILED); // Retry events List<NotificationEventModelDao> historicalEntriesForRetries = Iterators.toUnmodifiableList(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("notifications-retries:queueName", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())); Assert.assertEquals(historicalEntriesForRetries.size(), 3); for (final NotificationEventModelDao historicalEntriesForRetry : historicalEntriesForRetries) { Assert.assertEquals((long) historicalEntriesForRetry.getErrorCount(), (long) 0); Assert.assertEquals(historicalEntriesForRetry.getProcessingState(), PersistentQueueEntryLifecycleState.FAILED); } // Make the next retry work handlerDelegate.shouldFail(false); clock.addDays(1); // Make sure all notifications are processed await().atMost(10, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return Iterators.size(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("svc:queueName", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())) == 1 && Iterators.size(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("notifications-retries:queueName", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())) == 4; } }); // Initial event was processed once historicalEntriesForOriginalEvent = Iterators.toUnmodifiableList(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("svc:queueName", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())); Assert.assertEquals(historicalEntriesForOriginalEvent.size(), 1); Assert.assertEquals((long) historicalEntriesForOriginalEvent.get(0).getErrorCount(), (long) 0); // State is still FAILED Assert.assertEquals(historicalEntriesForOriginalEvent.get(0).getProcessingState(), PersistentQueueEntryLifecycleState.FAILED); // Retry events historicalEntriesForRetries = Iterators.toUnmodifiableList(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("notifications-retries:queueName", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())); Assert.assertEquals(historicalEntriesForRetries.size(), 4); for (int i = 0; i < historicalEntriesForRetries.size(); i++) { final NotificationEventModelDao historicalEntriesForRetry = historicalEntriesForRetries.get(i); Assert.assertEquals((long) historicalEntriesForRetry.getErrorCount(), (long) 0); Assert.assertEquals(historicalEntriesForRetry.getProcessingState(), i == historicalEntriesForRetries.size() - 1 ? PersistentQueueEntryLifecycleState.PROCESSED : PersistentQueueEntryLifecycleState.FAILED); } } finally { queueWithExceptionAndFailed.stopQueue(); retryableQueueService.stop(); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/notificationq/MockNotificationQueue.java
queue/src/test/java/org/killbill/notificationq/MockNotificationQueue.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2021 Equinix, Inc * Copyright 2014-2021 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import org.joda.time.DateTime; import org.killbill.CreatorName; import org.killbill.clock.Clock; import org.killbill.notificationq.api.NotificationEvent; import org.killbill.notificationq.api.NotificationEventWithMetadata; import org.killbill.notificationq.api.NotificationQueue; import org.killbill.notificationq.api.NotificationQueueService.NotificationQueueHandler; import org.killbill.notificationq.dao.NotificationEventModelDao; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.dispatching.EventEntryDeserializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; public class MockNotificationQueue implements NotificationQueue { private final Logger log = LoggerFactory.getLogger("MockNotificationQueue"); private static final ObjectMapper objectMapper = new ObjectMapper(); private final String hostname; private final TreeSet<NotificationEventModelDao> notifications; private final Clock clock; private final String svcName; private final String queueName; private final NotificationQueueHandler handler; private final MockNotificationQueueService queueService; private final AtomicLong recordIds; private volatile boolean isStarted; public MockNotificationQueue(final Clock clock, final String svcName, final String queueName, final NotificationQueueHandler handler, final MockNotificationQueueService mockNotificationQueueService) { this.svcName = svcName; this.queueName = queueName; this.handler = handler; this.clock = clock; this.hostname = CreatorName.get(); this.queueService = mockNotificationQueueService; this.recordIds = new AtomicLong(); notifications = new TreeSet<NotificationEventModelDao>(new Comparator<NotificationEventModelDao>() { @Override public int compare(final NotificationEventModelDao o1, final NotificationEventModelDao o2) { if (o1.getEffectiveDate().equals(o2.getEffectiveDate())) { return o1.getRecordId().compareTo(o2.getRecordId()); } else { return o1.getEffectiveDate().compareTo(o2.getEffectiveDate()); } } }); } @Override public void recordFutureNotification(final DateTime futureNotificationTime, final NotificationEvent eventJson, final UUID userToken, final Long searchKey1, final Long searchKey2) throws IOException { final String json = objectMapper.writeValueAsString(eventJson); final Long searchKey2WithNull = Objects.requireNonNullElse(searchKey2, 0L); final NotificationEventModelDao notification = new NotificationEventModelDao(recordIds.incrementAndGet(), "MockQueue", hostname, clock.getUTCNow(), null, PersistentQueueEntryLifecycleState.AVAILABLE, eventJson.getClass().getName(), json, 0L, userToken, searchKey1, searchKey2WithNull, UUID.randomUUID(), futureNotificationTime, "MockQueue"); synchronized (notifications) { notifications.add(notification); } } @Override public void recordFutureNotificationFromTransaction(final Connection connection, final DateTime futureNotificationTime, final NotificationEvent eventJson, final UUID userToken, final Long searchKey1, final Long searchKey2) throws IOException { recordFutureNotification(futureNotificationTime, eventJson, userToken, searchKey1, searchKey2); } @Override public void updateFutureNotification(final Long recordId, final NotificationEvent eventJson, final Long searchKey1, final Long searchKey2) throws IOException { return; } @Override public void updateFutureNotificationFromTransaction(final Connection connection, final Long recordId, final NotificationEvent eventJson, final Long searchKey1, final Long searchKey2) throws IOException { return; } @Override public <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getFutureNotificationForSearchKeys(final Long searchKey1, final Long searchKey2) { return null; } @Override public <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getFutureNotificationFromTransactionForSearchKeys(final Long searchKey1, final Long searchKey2, final Connection connection) { return null; } @Override public <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getFutureNotificationForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2) { return null; } @Override public <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getFutureNotificationFromTransactionForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2, final Connection connection) { return null; } @Override public <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getInProcessingNotifications() { return null; } @Override public <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationForSearchKeys(final Long searchKey1, final Long searchKey2) { return null; } @Override public <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationFromTransactionForSearchKeys(final Long searchKey1, final Long searchKey2, final Connection connection) { return null; } @Override public <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2) { return null; } @Override public <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationFromTransactionForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2, final Connection connection) { return null; } @Override public <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getHistoricalNotificationForSearchKeys(final Long searchKey1, final Long searchKey2) { return null; } @Override public <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getHistoricalNotificationForSearchKey2(final DateTime minEffectiveDate, final Long searchKey2) { return null; } private <T extends NotificationEvent> List<NotificationEventWithMetadata<T>> getFutureNotificationsInternal(final Class<T> type, final Long searchKey1, final Connection connection) { final List<NotificationEventWithMetadata<T>> result = new ArrayList<NotificationEventWithMetadata<T>>(); synchronized (notifications) { for (final NotificationEventModelDao notification : notifications) { if (notification.getSearchKey1().equals(searchKey1) && type.getName().equals(notification.getClassName()) && notification.getEffectiveDate().isAfter(clock.getUTCNow())) { final T event = EventEntryDeserializer.deserialize(notification, objectMapper.reader()); final NotificationEventWithMetadata<T> foo = new NotificationEventWithMetadata<T>(notification.getRecordId(), notification.getUserToken(), notification.getCreatedDate(), notification.getSearchKey1(), notification.getSearchKey2(), event, notification.getFutureUserToken(), notification.getEffectiveDate(), notification.getQueueName()); result.add(foo); } } } return result; } @Override public long getNbReadyEntries(final DateTime maxEffectiveDate) { return 0; } @Override public void removeNotification(final Long recordId) { removeNotificationFromTransaction(null, recordId); } @Override public void removeNotificationFromTransaction(final Connection connection, final Long recordId) { synchronized (notifications) { for (final NotificationEventModelDao cur : notifications) { if (cur.getRecordId().equals(recordId)) { notifications.remove(cur); break; } } } } @Override public void removeFutureNotificationsForSearchKeys(final Long searchKey1, final Long searchKey2) { } @Override public String getFullQName() { return NotificationQueueDispatcher.getCompositeName(svcName, queueName); } @Override public String getServiceName() { return svcName; } @Override public String getQueueName() { return queueName; } @Override public NotificationQueueHandler getHandler() { return handler; } @Override public boolean initQueue() { return true; } @Override public boolean startQueue() { isStarted = true; queueService.startQueue(); return true; } @Override public boolean stopQueue() { isStarted = false; return queueService.stopQueue(); } @Override public boolean isStarted() { return isStarted; } public List<NotificationEventModelDao> getReadyNotifications() { final List<NotificationEventModelDao> readyNotifications = new ArrayList<NotificationEventModelDao>(); synchronized (notifications) { for (final NotificationEventModelDao cur : notifications) { if (cur.getEffectiveDate().isBefore(clock.getUTCNow()) && cur.isAvailableForProcessing(clock.getUTCNow())) { log.info("MockNotificationQ getReadyNotifications found notification: NOW = " + clock.getUTCNow() + " recordId = " + cur.getRecordId() + ", state = " + cur.getProcessingState() + ", effectiveDate = " + cur.getEffectiveDate()); readyNotifications.add(cur); } } } return readyNotifications; } public void markProcessedNotifications(final List<NotificationEventModelDao> toBeremoved, final List<NotificationEventModelDao> toBeAdded) { synchronized (notifications) { notifications.removeAll(toBeremoved); notifications.addAll(toBeAdded); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/notificationq/dao/TestNotificationSqlDao.java
queue/src/test/java/org/killbill/notificationq/dao/TestNotificationSqlDao.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq.dao; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.killbill.CreatorName; import org.killbill.TestSetup; import org.killbill.clock.DefaultClock; import org.killbill.commons.utils.collect.Iterators; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.dao.QueueSqlDao; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionStatus; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; public class TestNotificationSqlDao extends TestSetup { private static final String hostname = "Yop"; private static final long SEARCH_KEY_2 = 37; private NotificationSqlDao dao; @BeforeClass(groups = "slow") public void beforeClass() throws Exception { super.beforeClass(); dao = getDBI().onDemand(NotificationSqlDao.class); } @Test(groups = "slow", description = "Verify SQL bound arguments are properly serialized") public void testQueryGeneratesNoWarning() throws Exception { final Handle handle = getDBI().open(); try { final Date date = new DateTime().toDate(); handle.inTransaction(new TransactionCallback<Object>() { @Override public Object inTransaction(final Handle conn, final TransactionStatus status) throws Exception { final NotificationSqlDao notificationSqlDao = conn.attach(NotificationSqlDao.class); final List<NotificationEventModelDao> entries = notificationSqlDao.getReadyEntries(date, 3, hostname, notificationQueueConfig.getTableName()); assertNull(conn.getConnection().getWarnings()); assertEquals(entries.size(), 0); return null; } }); } finally { handle.close(); } } @Test(groups = "slow") public void testBasic() throws InterruptedException { final long searchKey1 = 1242L; final String ownerId = UUID.randomUUID().toString(); final String eventJson = UUID.randomUUID().toString(); // ms will be truncated in the database final DateTime effDt = DefaultClock.truncateMs(new DateTime()); final NotificationEventModelDao notif = new NotificationEventModelDao(hostname, clock.getUTCNow(), eventJson.getClass().getName(), eventJson, UUID.randomUUID(), searchKey1, SEARCH_KEY_2, UUID.randomUUID(), effDt, "testBasic"); dao.insertEntry(notif, notificationQueueConfig.getTableName()); Thread.sleep(1000); // ms will be truncated in the database final DateTime now = DefaultClock.truncateMs(new DateTime()); final List<NotificationEventModelDao> notifications = dao.getReadyEntries(now.toDate(), 3, hostname, notificationQueueConfig.getTableName()); assertNotNull(notifications); assertEquals(notifications.size(), 1); final long nbEntries = dao.getNbReadyEntries(now.toDate(), hostname, notificationQueueConfig.getTableName()); assertEquals(nbEntries, 1); NotificationEventModelDao notification = notifications.get(0); assertEquals(notification.getEventJson(), eventJson); validateDate(notification.getEffectiveDate(), effDt); assertEquals(notification.getProcessingOwner(), null); assertEquals(notification.getProcessingState(), PersistentQueueEntryLifecycleState.AVAILABLE); assertEquals(notification.getNextAvailableDate(), null); final DateTime nextAvailable = now.plusMinutes(5); final int res = dao.claimEntry(notification.getRecordId(), ownerId, nextAvailable.toDate(), notificationQueueConfig.getTableName()); assertEquals(res, 1); dao.claimEntry(notification.getRecordId(), ownerId, nextAvailable.toDate(), notificationQueueConfig.getTableName()); notification = dao.getByRecordId(notification.getRecordId(), notificationQueueConfig.getTableName()); assertEquals(notification.getEventJson(), eventJson); validateDate(notification.getEffectiveDate(), effDt); assertEquals(notification.getProcessingOwner(), ownerId); assertEquals(notification.getProcessingState(), PersistentQueueEntryLifecycleState.IN_PROCESSING); validateDate(notification.getNextAvailableDate(), nextAvailable); final DateTime processedTime = clock.getUTCNow(); NotificationEventModelDao notificationHistory = new NotificationEventModelDao(notification, CreatorName.get(), processedTime, PersistentQueueEntryLifecycleState.PROCESSED); dao.insertEntry(notificationHistory, notificationQueueConfig.getHistoryTableName()); notificationHistory = dao.getByRecordId(notification.getRecordId(), notificationQueueConfig.getHistoryTableName()); assertEquals(notificationHistory.getEventJson(), eventJson); validateDate(notificationHistory.getEffectiveDate(), effDt); assertEquals(notificationHistory.getProcessingOwner(), CreatorName.get()); assertEquals(notificationHistory.getProcessingState(), PersistentQueueEntryLifecycleState.PROCESSED); validateDate(notificationHistory.getNextAvailableDate(), processedTime); dao.removeEntry(notification.getRecordId(), notificationQueueConfig.getTableName()); notification = dao.getByRecordId(notification.getRecordId(), notificationQueueConfig.getTableName()); assertNull(notification); } @Test(groups = "slow") public void testBatchOperations() throws InterruptedException { final long searchKey1 = 1242L; final String eventJson = UUID.randomUUID().toString(); final DateTime effDt = new DateTime(); NotificationEventModelDao notif1 = new NotificationEventModelDao(hostname, clock.getUTCNow(), eventJson.getClass().getName(), eventJson, UUID.randomUUID(), searchKey1, SEARCH_KEY_2, UUID.randomUUID(), effDt, "testBasic1"); final List<NotificationEventModelDao> entries = new ArrayList<NotificationEventModelDao>(); notif1 = insertEntry(notif1, notificationQueueConfig.getTableName()); entries.add(notif1); NotificationEventModelDao notif2 = new NotificationEventModelDao(hostname, clock.getUTCNow(), eventJson.getClass().getName(), eventJson, UUID.randomUUID(), searchKey1, SEARCH_KEY_2, UUID.randomUUID(), effDt, "testBasic2"); notif2 = insertEntry(notif2, notificationQueueConfig.getTableName()); entries.add(notif2); NotificationEventModelDao notif3 = new NotificationEventModelDao(hostname, clock.getUTCNow(), eventJson.getClass().getName(), eventJson, UUID.randomUUID(), searchKey1, SEARCH_KEY_2, UUID.randomUUID(), effDt, "testBasic3"); notif3 = insertEntry(notif3, notificationQueueConfig.getTableName()); entries.add(notif3); final Collection<Long> entryIds = entries.stream() .map(NotificationEventModelDao::getRecordId) .collect(Collectors.toUnmodifiableList()); dao.removeEntries(entryIds, notificationQueueConfig.getTableName()); for (final Long entry : entryIds) { final NotificationEventModelDao result = dao.getByRecordId(entry, notificationQueueConfig.getTableName()); assertNull(result); } dao.insertEntries(entries, notificationQueueConfig.getHistoryTableName()); for (final Long entry : entryIds) { final NotificationEventModelDao result = dao.getByRecordId(entry, notificationQueueConfig.getHistoryTableName()); assertNotNull(result); } } @Test(groups = "slow") public void testLargeBatchOperations() { final long searchKey1 = 1242L; final String ownerId = UUID.randomUUID().toString(); final List<NotificationEventModelDao> entries = new ArrayList<NotificationEventModelDao>(); final String eventJson = UUID.randomUUID().toString(); final DateTime effDt = new DateTime(); for (int i = 0; i < 2000; i++) { NotificationEventModelDao cur = new NotificationEventModelDao(hostname, clock.getUTCNow(), eventJson.getClass().getName(), eventJson, UUID.randomUUID(), searchKey1, SEARCH_KEY_2, UUID.randomUUID(), effDt, "testBasic1"); entries.add(cur); } dao.insertEntries(entries, notificationQueueConfig.getTableName()); final Iterator<NotificationEventModelDao> result = dao.getReadyQueueEntriesForSearchKeys("testBasic1", searchKey1, SEARCH_KEY_2, notificationQueueConfig.getTableName()); assertEquals(Iterators.size(result), 2000); } @Test(groups = "slow") public void testUpdateEvent() throws InterruptedException { final long searchKey1 = 14542L; final String eventJsonInitial = "Initial value"; final DateTime effDt = new DateTime(); final NotificationEventModelDao notif = new NotificationEventModelDao(hostname, clock.getUTCNow(), eventJsonInitial.getClass().getName(), eventJsonInitial, UUID.randomUUID(), searchKey1, SEARCH_KEY_2, UUID.randomUUID(), effDt, "testUpdateEvent"); dao.insertEntry(notif, notificationQueueConfig.getTableName()); Iterator<NotificationEventModelDao> notifications = dao.getReadyOrInProcessingQueueEntriesForSearchKeys(notif.getQueueName(), searchKey1, SEARCH_KEY_2, notificationQueueConfig.getTableName()); assertTrue(notifications.hasNext()); final NotificationEventModelDao notification = notifications.next(); assertEquals(notification.getEventJson(), eventJsonInitial); assertFalse(notifications.hasNext()); final String eventJsonUpdated = "Updated value"; dao.updateEntry(notification.getRecordId(), eventJsonUpdated, searchKey1, SEARCH_KEY_2, notificationQueueConfig.getTableName()); notifications = dao.getReadyOrInProcessingQueueEntriesForSearchKeys(notif.getQueueName(), searchKey1, SEARCH_KEY_2, notificationQueueConfig.getTableName()); assertTrue(notifications.hasNext()); final NotificationEventModelDao updatedNotification = notifications.next(); assertEquals(updatedNotification.getEventJson(), eventJsonUpdated); assertFalse(notifications.hasNext()); } private NotificationEventModelDao insertEntry(final NotificationEventModelDao input, final String tableName) { return dao.inTransaction(new Transaction<NotificationEventModelDao, QueueSqlDao<NotificationEventModelDao>>() { @Override public NotificationEventModelDao inTransaction(final QueueSqlDao<NotificationEventModelDao> transactional, final TransactionStatus status) throws Exception { final Long recordId = transactional.insertEntry(input, tableName); return transactional.getByRecordId(recordId, notificationQueueConfig.getTableName()); } }); } private void validateDate(DateTime input, DateTime expected) { if (input == null && expected != null) { Assert.fail("Got input date null"); } if (input != null && expected == null) { Assert.fail("Was expecting null date"); } expected = truncateAndUTC(expected); input = truncateAndUTC(input); Assert.assertEquals(input, expected); } private DateTime truncateAndUTC(final DateTime input) { if (input == null) { return null; } final DateTime result = input.minus(input.getMillisOfSecond()); return result.toDateTime(DateTimeZone.UTC); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/queue/TestDBBackedQueueWithInflightQ.java
queue/src/test/java/org/killbill/queue/TestDBBackedQueueWithInflightQ.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2021 Equinix, Inc * Copyright 2014-2021 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.queue; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.killbill.CreatorName; import org.killbill.TestSetup; import org.killbill.bus.api.PersistentBusConfig; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.bus.dao.PersistentBusSqlDao; import org.skife.config.TimeSpan; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class TestDBBackedQueueWithInflightQ extends TestSetup { private DBBackedQueueWithInflightQueue<BusEventModelDao> queue; private PersistentBusSqlDao sqlDao; @BeforeClass(groups = "slow") public void beforeClass() throws Exception { super.beforeClass(); sqlDao = getDBI().onDemand(PersistentBusSqlDao.class); } @BeforeMethod(groups = "slow") public void beforeMethod() throws Exception { super.beforeMethod(); final List<BusEventModelDao> ready = sqlDao.getReadyEntries(clock.getUTCNow().toDate(), 100, null, "bus_events"); assertEquals(ready.size(), 0); } @Test(groups = "slow") public void testInflightQWithExistingEntries() { final int NB_ENTRIES = 2345; final PersistentBusConfig config = createConfig(); queue = new DBBackedQueueWithInflightQueue<BusEventModelDao>(clock, dbi, PersistentBusSqlDao.class, config, "testInflightQWithExistingEntries", metricRegistry, databaseTransactionNotificationApi); // Insert entries prior initialization for (int i = 0; i < NB_ENTRIES; i++) { final BusEventModelDao input = createEntry(new Long(i + 5)); sqlDao.insertEntry(input, config.getTableName()); } final long readyEntries = queue.getNbReadyEntries(); assertEquals(readyEntries, NB_ENTRIES); queue.initialize(); assertEquals(queue.getInflightQSize(), NB_ENTRIES); } private BusEventModelDao createEntry(final Long searchKey1, final String owner) { final String json = "json"; return new BusEventModelDao(owner, clock.getUTCNow(), String.class.getName(), json, UUID.randomUUID(), searchKey1, 1L); } private BusEventModelDao createEntry(final Long searchKey1) { return createEntry(searchKey1, CreatorName.get()); } private PersistentBusConfig createConfig() { return new PersistentBusConfig() { @Override public boolean isInMemory() { return false; } @Override public int getMaxFailureRetries() { return 0; } @Override public int getMinInFlightEntries() { return 1; } @Override public int getMaxInFlightEntries() { return 100; } @Override public int getMaxEntriesClaimed() { return 100; } @Override public PersistentQueueMode getPersistentQueueMode() { return PersistentQueueMode.STICKY_EVENTS; } @Override public TimeSpan getClaimedTime() { return new TimeSpan("5m"); } @Override public long getPollingSleepTimeMs() { return -1; } @Override public boolean isProcessingOff() { return false; } @Override public int geMaxDispatchThreads() { return 1; } @Override public int geNbLifecycleDispatchThreads() { return 1; } @Override public int geNbLifecycleCompleteThreads() { return 1; } @Override public int getEventQueueCapacity() { return -1; } @Override public String getTableName() { return "bus_events"; } @Override public String getHistoryTableName() { return "bus_events_history"; } @Override public TimeSpan getReapThreshold() { return new TimeSpan(5, TimeUnit.MINUTES); } @Override public int getMaxReDispatchCount() { return 10; } @Override public TimeSpan getReapSchedule() { return new TimeSpan(3, TimeUnit.MINUTES); } @Override public TimeSpan getShutdownTimeout() { return new TimeSpan(5, TimeUnit.SECONDS); } }; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/queue/TestReaperIntegration.java
queue/src/test/java/org/killbill/queue/TestReaperIntegration.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2021 Equinix, Inc * Copyright 2014-2021 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.queue; import java.util.HashSet; import java.util.Set; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.awaitility.Awaitility; import org.joda.time.DateTime; import org.killbill.CreatorName; import org.killbill.TestSetup; import org.killbill.bus.DefaultPersistentBus; import org.killbill.bus.api.BusEvent; import org.killbill.bus.api.BusEventWithMetadata; import org.killbill.bus.api.PersistentBus.EventBusException; import org.killbill.bus.api.PersistentBusConfig; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.bus.dao.PersistentBusSqlDao; import org.killbill.commons.eventbus.AllowConcurrentEvents; import org.killbill.commons.eventbus.Subscribe; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.skife.config.TimeSpan; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; public class TestReaperIntegration extends TestSetup { private PersistentBusConfig config; private DefaultPersistentBus bus; private PersistentBusSqlDao sqlDao; private DummyHandler handler; @BeforeClass(groups = "slow") public void beforeClass() throws Exception { super.beforeClass(); sqlDao = getDBI().onDemand(PersistentBusSqlDao.class); } @BeforeMethod(groups = "slow") public void beforeMethod() throws Exception { super.beforeMethod(); config = createConfig(); bus = new DefaultPersistentBus(dbi, clock, config, metricRegistry, databaseTransactionNotificationApi); bus.startQueue(); handler = new DummyHandler(); bus.register(handler); } @AfterMethod(groups = "slow") public void afterMethod() throws Exception { bus.stopQueue(); } @Test(groups = "slow") public void testWithStuckEntryProcessedByAnotherNode() throws EventBusException, JsonProcessingException, InterruptedException { final DateTime now = clock.getUTCNow(); // Verify bus is working final BusEvent event1 = new DummyEvent(); bus.post(event1); handler.waitFor(event1); handler.assertSeenEvents(1); // Insert stuck entry processed by another node final BusEvent event2 = new DummyEvent(); sqlDao.insertEntry(createEntry("thatOtherNode", "thatOtherNode", now, event2, PersistentQueueEntryLifecycleState.IN_PROCESSING), config.getTableName()); handler.ensureNotSeen(event2); handler.assertSeenEvents(1); // Post another event final BusEvent event3 = new DummyEvent(); bus.post(event3); handler.waitFor(event3); handler.ensureNotSeen(event2); handler.assertSeenEvents(2); // Trigger reaper clock.addDeltaFromReality(config.getReapThreshold().getMillis()); handler.waitFor(event2); handler.assertSeenEvents(3); } @Test(groups = "slow") public void testWithStuckEntryNonExistingNode() throws EventBusException, JsonProcessingException, InterruptedException { final DateTime now = clock.getUTCNow(); // Verify bus is working final BusEvent event1 = new DummyEvent(); bus.post(event1); handler.waitFor(event1); handler.assertSeenEvents(1); // Insert entry processed by no-one final BusEvent event2 = new DummyEvent(); sqlDao.insertEntry(createEntry("aws-compute-123456.internal", null, now, event2, PersistentQueueEntryLifecycleState.AVAILABLE), config.getTableName()); handler.ensureNotSeen(event2); handler.assertSeenEvents(1); // Post another event final BusEvent event3 = new DummyEvent(); bus.post(event3); handler.waitFor(event3); handler.ensureNotSeen(event2); handler.assertSeenEvents(2); // Trigger reaper clock.addDeltaFromReality(config.getReapThreshold().getMillis()); handler.waitFor(event2); handler.assertSeenEvents(3); } @Test(groups = "slow") public void testWithStuckEntryProcessedByThisNode() throws EventBusException, JsonProcessingException, InterruptedException { final DateTime now = clock.getUTCNow(); // Verify bus is working final BusEvent event1 = new DummyEvent(); bus.post(event1); handler.waitFor(event1); handler.assertSeenEvents(1); // Insert stuck entry processed by this node final BusEvent event2 = new DummyEvent(); sqlDao.insertEntry(createEntry(CreatorName.get(), CreatorName.get(), now, event2, PersistentQueueEntryLifecycleState.IN_PROCESSING), config.getTableName()); handler.ensureNotSeen(event2); handler.assertSeenEvents(1); // Post another event final BusEvent event3 = new DummyEvent(); bus.post(event3); handler.waitFor(event3); handler.ensureNotSeen(event2); handler.assertSeenEvents(2); // Trigger reaper clock.addDeltaFromReality(config.getReapThreshold().getMillis()); // Give a chance to the reaper to run Thread.sleep(500); clock.addDeltaFromReality(1000); handler.waitFor(event2); // See https://github.com/killbill/killbill-commons/issues/169 handler.assertSeenEvents(3); final Iterable<BusEventWithMetadata<BusEvent>> result = bus.getHistoricalBusEventsForSearchKey2(now, SEARCH_KEY_2); final long nbItems = result.spliterator().getExactSizeIfKnown(); assertEquals(nbItems, 4); } @Test(groups = "slow") public void testWithLateBusOnThisNode() throws EventBusException, JsonProcessingException, InterruptedException { final DateTime now = clock.getUTCNow(); // Verify bus is working final BusEvent event1 = new DummyEvent(); bus.post(event1); handler.waitFor(event1); handler.assertSeenEvents(1); // Insert old entry not yet processed by this node final BusEvent event2 = new DummyEvent(); // PersistentQueueEntryLifecycleState.AVAILABLE would be more accurate, but this is just to trick the bus not to pick that entry up sqlDao.insertEntry(createEntry(CreatorName.get(), null, now.minusHours(2), null, event2, PersistentQueueEntryLifecycleState.IN_PROCESSING), config.getTableName()); handler.ensureNotSeen(event2); handler.assertSeenEvents(1); // Post another event final BusEvent event3 = new DummyEvent(); bus.post(event3); handler.waitFor(event3); handler.ensureNotSeen(event2); handler.assertSeenEvents(2); // The reaper will never reap it clock.addDeltaFromReality(config.getReapThreshold().getMillis()); handler.ensureNotSeen(event2); handler.assertSeenEvents(2); } @Test(groups = "slow") public void testWithLateBusOnAnotherNode() throws EventBusException, JsonProcessingException, InterruptedException { final DateTime now = clock.getUTCNow(); // Verify bus is working final BusEvent event1 = new DummyEvent(); bus.post(event1); handler.waitFor(event1); handler.assertSeenEvents(1); // Insert old entry processed by another node (nextAvailableDate reflects that it just got picked up) final BusEvent event2 = new DummyEvent(); sqlDao.insertEntry(createEntry("thatOtherNode", "thatOtherNode", now.minusHours(2), now.plus(config.getClaimedTime().getMillis()), event2, PersistentQueueEntryLifecycleState.IN_PROCESSING), config.getTableName()); handler.ensureNotSeen(event2); handler.assertSeenEvents(1); // Post another event final BusEvent event3 = new DummyEvent(); bus.post(event3); handler.waitFor(event3); handler.ensureNotSeen(event2); handler.assertSeenEvents(2); // After a while though, the reaper will be triggered clock.addDeltaFromReality(config.getReapThreshold().getMillis()); handler.waitFor(event2); handler.assertSeenEvents(3); } private BusEventModelDao createEntry(final String creatingOwner, final String processingOwner, final DateTime createdDate, final BusEvent event, final PersistentQueueEntryLifecycleState state) throws JsonProcessingException { final DateTime processingAvailableDate = createdDate.plus(config.getClaimedTime().getMillis()); return createEntry(creatingOwner, processingOwner, createdDate, processingAvailableDate, event, state); } private BusEventModelDao createEntry(final String creatingOwner, final String processingOwner, final DateTime createdDate, final DateTime processingAvailableDate, final BusEvent event, final PersistentQueueEntryLifecycleState state) throws JsonProcessingException { return new BusEventModelDao(null, creatingOwner, processingOwner, createdDate, processingAvailableDate, state, event.getClass().getName(), QueueObjectMapper.get().writeValueAsString(event), 0L, event.getUserToken(), event.getSearchKey1(), event.getSearchKey2()); } public static class DummyEvent implements BusEvent { private final String name; private final Long searchKey1; private final Long searchKey2; private final UUID userToken; @JsonCreator public DummyEvent(@JsonProperty("name") final String name, @JsonProperty("searchKey1") final Long searchKey1, @JsonProperty("searchKey2") final Long searchKey2, @JsonProperty("userToken") final UUID userToken) { this.name = name; this.searchKey2 = searchKey2; this.searchKey1 = searchKey1; this.userToken = userToken; } public DummyEvent() { this(UUID.randomUUID().toString(), SEARCH_KEY_1, SEARCH_KEY_2, UUID.randomUUID()); } public String getName() { return name; } @Override public Long getSearchKey1() { return searchKey1; } @Override public Long getSearchKey2() { return searchKey2; } @Override public UUID getUserToken() { return userToken; } @Override public String toString() { final StringBuffer sb = new StringBuffer("DummyEvent{"); sb.append("name='").append(name).append('\''); sb.append(", searchKey1=").append(searchKey1); sb.append(", searchKey2=").append(searchKey2); sb.append(", userToken=").append(userToken); sb.append('}'); return sb.toString(); } } public static class DummyHandler { private final Set<UUID> receivedEvents; DummyHandler() { receivedEvents = new HashSet<>(); } @AllowConcurrentEvents @Subscribe public void processEvent(final BusEvent event) { receivedEvents.add(event.getUserToken()); } void waitFor(final BusEvent event) { Awaitility.await().atMost(15, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return receivedEvents.contains(event.getUserToken()); } }); } void ensureNotSeen(final BusEvent event) throws InterruptedException { Thread.sleep(1000); assertFalse(receivedEvents.contains(event.getUserToken())); } void assertSeenEvents(final int expected) { assertEquals(receivedEvents.size(), expected); } } private PersistentBusConfig createConfig() { return new PersistentBusConfig() { @Override public boolean isInMemory() { return false; } @Override public int getMaxFailureRetries() { return 0; } @Override public int getMinInFlightEntries() { return 0; } @Override public int getMaxInFlightEntries() { return 0; } @Override public int getMaxEntriesClaimed() { return 10; } @Override public PersistentQueueMode getPersistentQueueMode() { return PersistentQueueMode.STICKY_POLLING; } @Override public TimeSpan getClaimedTime() { return new TimeSpan("1m"); } @Override public long getPollingSleepTimeMs() { return 1; } @Override public boolean isProcessingOff() { return false; } @Override public int geMaxDispatchThreads() { return 1; } @Override public int geNbLifecycleDispatchThreads() { return 1; } @Override public int geNbLifecycleCompleteThreads() { return 1; } @Override public int getEventQueueCapacity() { return 1; } @Override public String getTableName() { return "bus_events"; } @Override public String getHistoryTableName() { return "bus_events_history"; } @Override public TimeSpan getReapThreshold() { return new TimeSpan(5, TimeUnit.MINUTES); } @Override public int getMaxReDispatchCount() { return 10; } @Override public TimeSpan getReapSchedule() { // Aggressive on purpose return new TimeSpan(1, TimeUnit.SECONDS); } @Override public TimeSpan getShutdownTimeout() { return new TimeSpan(5, TimeUnit.SECONDS); } }; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/queue/TestReaper.java
queue/src/test/java/org/killbill/queue/TestReaper.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2021 Equinix, Inc * Copyright 2014-2021 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.queue; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.joda.time.DateTime; import org.killbill.CreatorName; import org.killbill.TestSetup; import org.killbill.bus.api.PersistentBusConfig; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.bus.dao.PersistentBusSqlDao; import org.killbill.commons.utils.collect.Iterators; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.skife.config.TimeSpan; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; public class TestReaper extends TestSetup { private DBBackedQueue<BusEventModelDao> queue; private PersistentBusSqlDao sqlDao; @BeforeClass(groups = "slow") public void beforeClass() throws Exception { super.beforeClass(); sqlDao = getDBI().onDemand(PersistentBusSqlDao.class); } @BeforeMethod(groups = "slow") public void beforeMethod() throws Exception { super.beforeMethod(); final List<BusEventModelDao> ready = sqlDao.getReadyEntries(clock.getUTCNow().toDate(), 100, null, "bus_events"); assertEquals(ready.size(), 0); } @Test(groups = "slow") public void testReapEntries() { final PersistentBusConfig config = createConfig(); queue = new DBBackedQueueWithPolling<BusEventModelDao>(clock, dbi, PersistentBusSqlDao.class, config, "testReapEntries", metricRegistry); final DateTime now = clock.getUTCNow(); // Insert ready entry (not yet reapable) sqlDao.insertEntry(createEntry(1L, CreatorName.get(), null, now, PersistentQueueEntryLifecycleState.AVAILABLE), config.getTableName()); // Insert ready entry from another node (not yet reapable) sqlDao.insertEntry(createEntry(2L, "thatOtherNode", null, now, PersistentQueueEntryLifecycleState.AVAILABLE), config.getTableName()); // Insert in-processing entry (not yet reapable) sqlDao.insertEntry(createEntry(3L, CreatorName.get(), CreatorName.get(), now, PersistentQueueEntryLifecycleState.IN_PROCESSING), config.getTableName()); // Insert in-processing entry from another node (not yet reapable) sqlDao.insertEntry(createEntry(4L, "thatOtherNode", "thatOtherNode", now, PersistentQueueEntryLifecycleState.IN_PROCESSING), config.getTableName()); // Insert in-processing entry sqlDao.insertEntry(createEntryForReaping(5L, CreatorName.get(), CreatorName.get(), now, config.getReapThreshold().getMillis(), PersistentQueueEntryLifecycleState.IN_PROCESSING), config.getTableName()); // Insert in-processing entry from another node (reapable) sqlDao.insertEntry(createEntryForReaping(6L, "thatOtherNode", "thatOtherNode", now, config.getReapThreshold().getMillis(), PersistentQueueEntryLifecycleState.IN_PROCESSING), config.getTableName()); // Check ready entries final List<BusEventModelDao> readyEntries = sqlDao.getReadyEntries(now.toDate(), 10, CreatorName.get(), config.getTableName()); // One ready entry (STICKY_POLLING mode) assertEquals(readyEntries.size(), 1); assertEquals(readyEntries.get(0).getRecordId(), (Long) 1L); // Check ready and in processing entries final List<BusEventModelDao> readyOrInProcessingBeforeReaping = Iterators.toUnmodifiableList(sqlDao.getReadyOrInProcessingQueueEntriesForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2, config.getTableName())); assertEquals(readyOrInProcessingBeforeReaping.size(), 6); assertEquals(readyOrInProcessingBeforeReaping.get(0).getRecordId(), (Long) 1L); assertEquals(readyOrInProcessingBeforeReaping.get(1).getRecordId(), (Long) 2L); assertEquals(readyOrInProcessingBeforeReaping.get(2).getRecordId(), (Long) 3L); assertEquals(readyOrInProcessingBeforeReaping.get(3).getRecordId(), (Long) 4L); assertEquals(readyOrInProcessingBeforeReaping.get(4).getRecordId(), (Long) 5L); assertEquals(readyOrInProcessingBeforeReaping.get(5).getRecordId(), (Long) 6L); // Check history table assertFalse(sqlDao.getHistoricalQueueEntriesForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2, config.getHistoryTableName()).hasNext()); queue.reapEntries(now.minus(config.getReapThreshold().getMillis()).toDate()); final List<BusEventModelDao> readyEntriesAfterReaping = sqlDao.getReadyEntries(now.toDate(), 10, CreatorName.get(), config.getTableName()); assertEquals(readyEntriesAfterReaping.size(), 3); assertEquals(readyEntriesAfterReaping.get(0).getRecordId(), (Long) 1L); assertTrue(readyEntriesAfterReaping.get(1).getRecordId() > (Long) 6L); assertTrue(readyEntriesAfterReaping.get(2).getRecordId() > (Long) 6L); final List<BusEventModelDao> readyOrInProcessingAfterReaping = Iterators.toUnmodifiableList(sqlDao.getReadyOrInProcessingQueueEntriesForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2, config.getTableName())); assertEquals(readyOrInProcessingAfterReaping.size(), 6); assertEquals(readyOrInProcessingAfterReaping.get(0).getRecordId(), (Long) 1L); assertEquals(readyOrInProcessingAfterReaping.get(1).getRecordId(), (Long) 2L); assertEquals(readyOrInProcessingAfterReaping.get(2).getRecordId(), (Long) 3L); assertEquals(readyOrInProcessingAfterReaping.get(3).getRecordId(), (Long) 4L); // New (reaped) ones assertTrue(readyOrInProcessingAfterReaping.get(4).getRecordId() > (Long) 6L); assertTrue(readyOrInProcessingAfterReaping.get(5).getRecordId() > (Long) 6L); // Check history table final List<BusEventModelDao> historicalQueueEntries = Iterators.toUnmodifiableList(sqlDao.getHistoricalQueueEntriesForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2, config.getHistoryTableName())); assertEquals(historicalQueueEntries.size(), 2); assertEquals(historicalQueueEntries.get(0).getProcessingState(), PersistentQueueEntryLifecycleState.REAPED); assertEquals(historicalQueueEntries.get(0).getUserToken(), readyOrInProcessingAfterReaping.get(4).getUserToken()); assertEquals(historicalQueueEntries.get(1).getProcessingState(), PersistentQueueEntryLifecycleState.REAPED); assertEquals(historicalQueueEntries.get(1).getUserToken(), readyOrInProcessingAfterReaping.get(5).getUserToken()); } private BusEventModelDao createEntry(final long recordId, final String creatingOwner, final String processingOwner, final DateTime createdDate, final PersistentQueueEntryLifecycleState state) { return new BusEventModelDao(recordId, creatingOwner, processingOwner, createdDate, createdDate, // Shouldn't matter state, String.class.getName(), "{}", 0L, UUID.randomUUID(), SEARCH_KEY_1, SEARCH_KEY_2); } private BusEventModelDao createEntryForReaping(final long recordId, final String creatingOwner, final String processingOwner, final DateTime now, final long reapThresholdMillis, final PersistentQueueEntryLifecycleState state) { final DateTime createdDate = now.minus(reapThresholdMillis); // For reaping, processingAvailableDate needs to be <= now final DateTime processingAvailableDate = now; return new BusEventModelDao(recordId, creatingOwner, processingOwner, createdDate, processingAvailableDate, state, String.class.getName(), "{}", 0L, UUID.randomUUID(), SEARCH_KEY_1, SEARCH_KEY_2); } private PersistentBusConfig createConfig() { return new PersistentBusConfig() { @Override public boolean isInMemory() { return false; } @Override public int getMaxFailureRetries() { return 0; } @Override public int getMinInFlightEntries() { return 1; } @Override public int getMaxInFlightEntries() { return 100; } @Override public int getMaxEntriesClaimed() { return 100; } @Override public PersistentQueueMode getPersistentQueueMode() { return PersistentQueueMode.STICKY_POLLING; } @Override public TimeSpan getClaimedTime() { return new TimeSpan("1m"); } @Override public long getPollingSleepTimeMs() { return -1; } @Override public boolean isProcessingOff() { return false; } @Override public int geMaxDispatchThreads() { return 1; } @Override public int geNbLifecycleDispatchThreads() { return 1; } @Override public int geNbLifecycleCompleteThreads() { return 1; } @Override public int getEventQueueCapacity() { return -1; } @Override public String getTableName() { return "bus_events"; } @Override public String getHistoryTableName() { return "bus_events_history"; } @Override public TimeSpan getReapThreshold() { return new TimeSpan(5, TimeUnit.MINUTES); } @Override public int getMaxReDispatchCount() { return 10; } @Override public TimeSpan getReapSchedule() { return new TimeSpan(3, TimeUnit.MINUTES); } @Override public TimeSpan getShutdownTimeout() { return new TimeSpan(5, TimeUnit.SECONDS); } }; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/queue/TestLoadDBBackedQueue.java
queue/src/test/java/org/killbill/queue/TestLoadDBBackedQueue.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2021 Equinix, Inc * Copyright 2014-2021 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.queue; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import org.killbill.CreatorName; import org.killbill.TestSetup; import org.killbill.bus.api.PersistentBusConfig; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.bus.dao.PersistentBusSqlDao; import org.killbill.queue.DBBackedQueue.ReadyEntriesWithMetrics; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.skife.config.TimeSpan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.killbill.queue.api.PersistentQueueConfig.PersistentQueueMode; import static org.testng.Assert.assertEquals; public class TestLoadDBBackedQueue extends TestSetup { private static final Logger log = LoggerFactory.getLogger(TestLoadDBBackedQueue.class); private static final String OWNER = CreatorName.get(); private DBBackedQueue<BusEventModelDao> queue; private PersistentBusSqlDao sqlDao; // Need to explicitly disable these as they are somehow picked up on CI with specific JDKs @BeforeClass(groups = "load", enabled = false) public void beforeClass() throws Exception { super.beforeClass(); sqlDao = getDBI().onDemand(PersistentBusSqlDao.class); } @BeforeMethod(groups = "load", enabled = false) public void beforeMethod() throws Exception { super.beforeMethod(); final List<BusEventModelDao> ready = sqlDao.getReadyEntries(clock.getUTCNow().toDate(), 100, null, "bus_events"); assertEquals(ready.size(), 0); } @Test(groups = "load", enabled = false) public void testPollingLoad() { final int NB_EVENTS = 1000; final int CLAIMED_EVENTS = 10; final PersistentBusConfig config = createConfig(CLAIMED_EVENTS, -1, PersistentQueueMode.POLLING); queue = new DBBackedQueueWithPolling<BusEventModelDao>(clock, dbi, PersistentBusSqlDao.class, config, "perf-bus_event", metricRegistry); queue.initialize(); for (int i = 0; i < NB_EVENTS; i++) { final BusEventModelDao input = createEntry(new Long(i)); queue.insertEntry(input); } log.error("Starting load test"); final long ini = System.nanoTime(); long cumlGetReadyEntries = 0; long cumlMoveEntriesToHistory = 0; for (int i = 0; i < NB_EVENTS / CLAIMED_EVENTS; i++) { final long t1 = System.nanoTime(); final ReadyEntriesWithMetrics<BusEventModelDao> result = queue.getReadyEntries(); final List<BusEventModelDao> ready = result.getEntries(); assertEquals(ready.size(), CLAIMED_EVENTS); final long t2 = System.nanoTime(); cumlGetReadyEntries += (t2 - t1); final Iterable<BusEventModelDao> processed = ready.stream() .map(input -> new BusEventModelDao(input, CreatorName.get(), clock.getUTCNow(), PersistentQueueEntryLifecycleState.PROCESSED)) .collect(Collectors.toUnmodifiableList()); final long t3 = System.nanoTime(); queue.moveEntriesToHistory(processed); final long t4 = System.nanoTime(); cumlMoveEntriesToHistory += (t4 - t3); } final long fini = System.nanoTime(); log.error("Load test took " + ((fini - ini) / 1000000) + " ms, getReadyEntry = " + (cumlGetReadyEntries / 1000000) + " ms, moveEntriesToHistory = " + (cumlMoveEntriesToHistory / 1000000)); } @Test(groups = "load", enabled = false) public void testInflightQLoad() throws InterruptedException { final int nbEntries = 10000; final PersistentBusConfig config = createConfig(10, nbEntries, PersistentQueueMode.STICKY_EVENTS); queue = new DBBackedQueueWithInflightQueue<BusEventModelDao>(clock, dbi, PersistentBusSqlDao.class, config, "multipleReaderMultipleWriter-bus_event", metricRegistry, databaseTransactionNotificationApi); queue.initialize(); for (int i = 0; i < nbEntries; i++) { final BusEventModelDao input = createEntry(new Long(i + 5)); queue.insertEntry(input); } final int maxThreads = 3; final Thread[] readers = new Thread[maxThreads]; final AtomicLong consumed = new AtomicLong(0); for (int i = 0; i < maxThreads; i++) { readers[i] = new Thread(new ReaderRunnable(consumed, nbEntries, queue)); } final long ini = System.currentTimeMillis(); for (int i = 0; i < maxThreads; i++) { readers[i].start(); } try { for (int i = 0; i < maxThreads; i++) { readers[i].join(); } } catch (final InterruptedException e) { e.printStackTrace(); } final long fini = System.currentTimeMillis(); final long elapsed = fini - ini; log.info(String.format("Processed %s events in %s msec => rate = %s", nbEntries, elapsed, ((double) (nbEntries) / (double) elapsed) * 1000)); final List<BusEventModelDao> ready = sqlDao.getReadyEntries(clock.getUTCNow().toDate(), 1000, OWNER, "bus_events"); assertEquals(ready.size(), 0); } public class ReaderRunnable implements Runnable { private final DBBackedQueue<BusEventModelDao> queue; private final AtomicLong consumed; private final int maxEntries; private final List<Long> search1; public ReaderRunnable(final AtomicLong consumed, final int maxEntries, final DBBackedQueue<BusEventModelDao> queue) { this.queue = queue; this.consumed = consumed; this.maxEntries = maxEntries; this.search1 = new ArrayList<Long>(); } @Override public void run() { do { final ReadyEntriesWithMetrics<BusEventModelDao> result = queue.getReadyEntries(); final List<BusEventModelDao> entries = result.getEntries(); if (entries.isEmpty()) { try { Thread.sleep(10); } catch (final InterruptedException e) { } } else { for (final BusEventModelDao cur : entries) { search1.add(cur.getSearchKey1()); final BusEventModelDao history = new BusEventModelDao(cur, OWNER, clock.getUTCNow(), PersistentQueueEntryLifecycleState.PROCESSED); queue.moveEntryToHistory(history); } consumed.getAndAdd(entries.size()); } } while (consumed.get() < maxEntries); } } private BusEventModelDao createEntry(final Long searchKey1, final String owner) { final String json = "json"; return new BusEventModelDao(owner, clock.getUTCNow(), String.class.getName(), json, UUID.randomUUID(), searchKey1, 1L); } private BusEventModelDao createEntry(final Long searchKey1) { return createEntry(searchKey1, OWNER); } private PersistentBusConfig createConfig(final int claimed, final int qCapacity, final PersistentQueueMode mode) { return new PersistentBusConfig() { @Override public boolean isInMemory() { return false; } @Override public int getMaxFailureRetries() { return 0; } @Override public int getMinInFlightEntries() { return 1; } @Override public int getMaxInFlightEntries() { return claimed; } @Override public int getMaxEntriesClaimed() { return claimed; } @Override public PersistentQueueMode getPersistentQueueMode() { return mode; } @Override public TimeSpan getClaimedTime() { return new TimeSpan("5m"); } @Override public long getPollingSleepTimeMs() { return 100; } @Override public boolean isProcessingOff() { return false; } @Override public int geMaxDispatchThreads() { return 0; } @Override public int geNbLifecycleDispatchThreads() { return 1; } @Override public int geNbLifecycleCompleteThreads() { return 1; } @Override public int getEventQueueCapacity() { return qCapacity; } @Override public String getTableName() { return "bus_events"; } @Override public String getHistoryTableName() { return "bus_events_history"; } @Override public TimeSpan getReapThreshold() { return new TimeSpan(5, TimeUnit.MINUTES); } @Override public int getMaxReDispatchCount() { return 10; } @Override public TimeSpan getReapSchedule() { return new TimeSpan(3, TimeUnit.MINUTES); } @Override public TimeSpan getShutdownTimeout() { return new TimeSpan(5, TimeUnit.SECONDS); } }; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/queue/dispatching/TestDispatcher.java
queue/src/test/java/org/killbill/queue/dispatching/TestDispatcher.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2021 Equinix, Inc * Copyright 2014-2021 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.queue.dispatching; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.awaitility.Awaitility; import org.joda.time.DateTime; import org.killbill.bus.api.BusEvent; import org.killbill.bus.api.PersistentBusConfig; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.api.QueueEvent; import org.skife.config.TimeSpan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestDispatcher { private final int QUEUE_SIZE = 5; private Dispatcher<BusEvent, BusEventModelDao> dispatcher; private TestCallableCallback callback; @BeforeClass(groups = "fast") public void beforeClass() throws Exception { final ThreadFactory testThreadFactory = new ThreadFactory() { @Override public Thread newThread(final Runnable r) { return new Thread(new ThreadGroup("TestGrp"), r, "test-grp--th"); } }; this.callback = new TestCallableCallback(); this.dispatcher = new Dispatcher<>(1, createConfig(), 5, TimeUnit.MINUTES, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(QUEUE_SIZE), testThreadFactory, new TestBlockingRejectionExecutionHandler(callback), null, callback, null); this.dispatcher.start(); } @Test(groups = "fast") public void testBlockingRejectionHandler() { callback.block(); for (int i = 0; i < QUEUE_SIZE + 2; i++) { dispatch(i); } Awaitility.await().atMost(5, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { final int size = callback.getProcessed().size(); return size == QUEUE_SIZE + 2; } }); } private void dispatch(final int i) { final BusEventModelDao e1 = new BusEventModelDao("owner", new DateTime(), String.class.getName(), "e-" + i, UUID.randomUUID(), 1L, 1L); dispatcher.dispatch(e1); } private class TestBlockingRejectionExecutionHandler extends BlockingRejectionExecutionHandler { private final TestCallableCallback callback; public TestBlockingRejectionExecutionHandler(final TestCallableCallback callback) { this.callback = callback; } @Override public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) { callback.unblock(); super.rejectedExecution(r, executor); } } private class TestCallableCallback implements CallableCallback<BusEvent, BusEventModelDao> { private final Logger logger = LoggerFactory.getLogger(TestCallableCallback.class); private volatile boolean isBlocked; private final List<QueueEvent> processed; public void block() { synchronized (this) { this.isBlocked = true; } } public void unblock() { synchronized (this) { this.isBlocked = false; this.notifyAll(); } } public List<QueueEvent> getProcessed() { return processed; } public TestCallableCallback() { this.isBlocked = false; this.processed = new ArrayList<QueueEvent>(); } @Override public BusEvent deserialize(final BusEventModelDao modelDao) { return new TestEvent(modelDao.getEventJson(), modelDao.getSearchKey1(), modelDao.getSearchKey2(), modelDao.getUserToken()); } @Override public void dispatch(final BusEvent event, final BusEventModelDao modelDao) throws Exception { synchronized (this) { while (isBlocked) { logger.info("Thread " + Thread.currentThread().getId() + " blocking..."); this.wait(); logger.info("Thread " + Thread.currentThread().getId() + " unblocking..."); } } logger.info("Got entry " + modelDao.getEventJson()); processed.add(event); } @Override public BusEventModelDao buildEntry(final BusEventModelDao modelDao, final DateTime now, final PersistentQueueEntryLifecycleState newState, final long newErrorCount) { return null; } @Override public void moveCompletedOrFailedEvents(final Iterable<BusEventModelDao> entries) { } @Override public void updateRetriedEvents(final BusEventModelDao updatedEntry) { } } public static class TestEvent implements BusEvent { private final String json; private final Long searchKey1; private final Long searchKey2; private final UUID userToken; @JsonCreator public TestEvent(@JsonProperty("json") final String json, @JsonProperty("searchKey1") final Long searchKey1, @JsonProperty("searchKey2") final Long searchKey2, @JsonProperty("userToken") final UUID userToken) { this.json = json; this.searchKey2 = searchKey2; this.searchKey1 = searchKey1; this.userToken = userToken; } public String getJson() { return json; } @Override public Long getSearchKey1() { return searchKey1; } @Override public Long getSearchKey2() { return searchKey2; } @Override public UUID getUserToken() { return userToken; } } private PersistentBusConfig createConfig() { return new PersistentBusConfig() { @Override public boolean isInMemory() { return false; } @Override public int getMaxFailureRetries() { return 0; } @Override public int getMinInFlightEntries() { return 1; } @Override public int getMaxInFlightEntries() { return 1; } @Override public int getMaxEntriesClaimed() { return 1; } @Override public PersistentQueueMode getPersistentQueueMode() { return PersistentQueueMode.STICKY_EVENTS; } @Override public TimeSpan getClaimedTime() { return new TimeSpan("5m"); } @Override public long getPollingSleepTimeMs() { return 100; } @Override public boolean isProcessingOff() { return false; } @Override public int geMaxDispatchThreads() { return 1; } @Override public int geNbLifecycleDispatchThreads() { return 1; } @Override public int geNbLifecycleCompleteThreads() { return 1; } @Override public int getEventQueueCapacity() { return QUEUE_SIZE; } @Override public String getTableName() { return "bus_events"; } @Override public String getHistoryTableName() { return "bus_events_history"; } @Override public TimeSpan getReapThreshold() { return new TimeSpan(5, TimeUnit.MINUTES); } @Override public int getMaxReDispatchCount() { return 10; } @Override public TimeSpan getReapSchedule() { return new TimeSpan(3, TimeUnit.MINUTES); } @Override public TimeSpan getShutdownTimeout() { return new TimeSpan(5, TimeUnit.SECONDS); } }; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/bus/TestEventBusBase.java
queue/src/test/java/org/killbill/bus/TestEventBusBase.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.bus; import java.util.UUID; import org.killbill.commons.eventbus.AllowConcurrentEvents; import org.killbill.commons.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.killbill.bus.api.BusEvent; import org.killbill.bus.api.PersistentBus; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class TestEventBusBase { protected static final Logger log = LoggerFactory.getLogger(TestEventBusBase.class); private final PersistentBus eventBus; public TestEventBusBase(final PersistentBus eventBus) { this.eventBus = eventBus; } public static class MyEvent implements BusEvent { private final String name; private final Long value; private final String type; private final Long searchKey1; private final Long searchKey2; private final UUID userToken; @JsonCreator public MyEvent(@JsonProperty("name") final String name, @JsonProperty("value") final Long value, @JsonProperty("type") final String type, @JsonProperty("searchKey1") final Long searchKey1, @JsonProperty("searchKey2") final Long searchKey2, @JsonProperty("userToken") final UUID userToken) { this.name = name; this.value = value; this.type = type; this.searchKey2 = searchKey2; this.searchKey1 = searchKey1; this.userToken = userToken; } public String getName() { return name; } public Long getValue() { return value; } public String getType() { return type; } @Override public Long getSearchKey1() { return searchKey1; } @Override public Long getSearchKey2() { return searchKey2; } @Override public UUID getUserToken() { return userToken; } } public static final class MyOtherEvent implements BusEvent { private final String name; private final Double value; private final String type; private final Long searchKey1; private final Long searchKey2; private final UUID userToken; @JsonCreator public MyOtherEvent(@JsonProperty("name") final String name, @JsonProperty("value") final Double value, @JsonProperty("type") final String type, @JsonProperty("searchKey1") final Long searchKey1, @JsonProperty("searchKey2") final Long searchKey2, @JsonProperty("userToken") final UUID userToken) { this.name = name; this.value = value; this.type = type; this.searchKey2 = searchKey2; this.searchKey1 = searchKey1; this.userToken = userToken; } public String getName() { return name; } public Double getValue() { return value; } public String getType() { return type; } @Override public Long getSearchKey1() { return searchKey1; } @Override public Long getSearchKey2() { return searchKey2; } @Override public UUID getUserToken() { return userToken; } } public static class MyEventHandlerException extends RuntimeException { private static final long serialVersionUID = 156337823L; public MyEventHandlerException(final String msg) { super(msg); } } public static class MyEventHandler { private final int expectedEvents; private final int nbThrowExceptions; private volatile int gotEvents; private volatile int gotExceptions; public MyEventHandler(final int exp, final int nbThrowExceptions) { this.expectedEvents = exp; this.nbThrowExceptions = nbThrowExceptions; this.gotEvents = 0; this.gotExceptions = 0; } public synchronized int getEvents() { return gotEvents; } @AllowConcurrentEvents @Subscribe public void processMyEvent(final MyEvent event) { //log.debug("Got event {} {}", event.name, event.value); if (gotExceptions < nbThrowExceptions) { gotExceptions++; throw new MyEventHandlerException("FAIL"); } gotEvents++; } public synchronized boolean waitForCompletion(final long timeoutMs) { final long ini = System.currentTimeMillis(); long remaining = timeoutMs; while (gotEvents < expectedEvents && remaining > 0) { try { wait(1000); if (gotEvents == expectedEvents) { break; } remaining = timeoutMs - (System.currentTimeMillis() - ini); } catch (final InterruptedException ignore) { } } return (gotEvents == expectedEvents); } } public void testSimpleWithExceptionAndRetrySuccess() { try { final MyEventHandler handler = new MyEventHandler(1, 1); eventBus.register(handler); eventBus.post(new MyEvent("my-event", 1L, "MY_EVENT_TYPE", 1L, 2L, UUID.randomUUID())); final boolean completed = handler.waitForCompletion(5000); Assert.assertEquals(completed, true); } catch (final Exception ignored) { } } public void testSimpleWithExceptionAndFail() { try { final MyEventHandler handler = new MyEventHandler(1, 4); eventBus.register(handler); eventBus.post(new MyEvent("my-event", 1L, "MY_EVENT_TYPE", 1L, 2L, UUID.randomUUID())); final boolean completed = handler.waitForCompletion(5000); Assert.assertEquals(completed, false); } catch (final Exception ignored) { } } public void testSimple() { try { final int nbEvents = 5; final MyEventHandler handler = new MyEventHandler(nbEvents, 0); eventBus.register(handler); for (int i = 0; i < nbEvents; i++) { eventBus.post(new MyEvent("my-event", (long) i, "MY_EVENT_TYPE", 1L, 2L, UUID.randomUUID())); } final boolean completed = handler.waitForCompletion(10000); Assert.assertEquals(completed, true); } catch (final Exception e) { Assert.fail("", e); } } public void testDifferentType() { try { final MyEventHandler handler = new MyEventHandler(1, 0); eventBus.register(handler); for (int i = 0; i < 5; i++) { eventBus.post(new MyOtherEvent("my-other-event", (double) i, "MY_EVENT_TYPE", 1L, 2L, UUID.randomUUID())); } eventBus.post(new MyEvent("my-event", 11l, "MY_EVENT_TYPE", 1L, 2L, UUID.randomUUID())); final boolean completed = handler.waitForCompletion(10000); Assert.assertEquals(completed, true); } catch (final Exception e) { Assert.fail("", e); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/bus/TestRetries.java
queue/src/test/java/org/killbill/bus/TestRetries.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.bus; import java.util.List; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.joda.time.Period; import org.killbill.TestSetup; import org.killbill.billing.util.queue.QueueRetryException; import org.killbill.bus.TestEventBusBase.MyEvent; import org.killbill.bus.api.PersistentBus; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.bus.dao.PersistentBusSqlDao; import org.killbill.commons.eventbus.AllowConcurrentEvents; import org.killbill.commons.eventbus.Subscribe; import org.killbill.commons.utils.collect.Iterators; import org.killbill.notificationq.DefaultNotificationQueueService; import org.killbill.notificationq.api.NotificationQueueService; import org.killbill.notificationq.dao.NotificationEventModelDao; import org.killbill.notificationq.dao.NotificationSqlDao; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.retry.RetryableService; import org.killbill.queue.retry.RetryableSubscriber; import org.killbill.queue.retry.RetryableSubscriber.SubscriberAction; import org.killbill.queue.retry.RetryableSubscriber.SubscriberQueueHandler; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.awaitility.Awaitility.await; public class TestRetries extends TestSetup { private static final UUID TOKEN_ID = UUID.randomUUID(); private static final long SEARCH_KEY_1 = 65; private static final long SEARCH_KEY_2 = 34; private NotificationQueueService queueService; private PersistentBus busService; @Override @BeforeMethod(groups = "slow") public void beforeMethod() throws Exception { super.beforeMethod(); queueService = new DefaultNotificationQueueService(getDBI(), clock, getNotificationQueueConfig(), metricRegistry); busService = new DefaultPersistentBus(getDBI(), clock, getPersistentBusConfig(), metricRegistry, databaseTransactionNotificationApi); busService.startQueue(); } @AfterMethod(groups = "slow") public void afterMethod() throws Exception { busService.stopQueue(); } @Test(groups = "slow") public void testRetryStateForBus() throws Exception { final RetryableBusService retryableBusService = new RetryableBusService(queueService); retryableBusService.initialize(); busService.register(retryableBusService); try { retryableBusService.start(); final MyEvent myEvent = new MyEvent("Foo", 1L, "Baz", SEARCH_KEY_1, SEARCH_KEY_2, TOKEN_ID); busService.post(myEvent); final PersistentBusSqlDao busSqlDao = dbi.onDemand(PersistentBusSqlDao.class); final NotificationSqlDao notificationSqlDao = dbi.onDemand(NotificationSqlDao.class); // Make sure all retries are processed await().atMost(10, TimeUnit.SECONDS) .until(() -> Iterators.size(busSqlDao.getHistoricalQueueEntriesForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2, persistentBusConfig.getHistoryTableName())) == 1 && Iterators.size(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("notifications-retries:myEvent-listener", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())) == 3); // Initial event was processed once List<BusEventModelDao> historicalEntriesForOriginalEvent = Iterators.toUnmodifiableList(busSqlDao.getHistoricalQueueEntriesForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2, persistentBusConfig.getHistoryTableName())); Assert.assertEquals(historicalEntriesForOriginalEvent.size(), 1); Assert.assertEquals((long) historicalEntriesForOriginalEvent.get(0).getErrorCount(), (long) 0); // State is initially FAILED Assert.assertEquals(historicalEntriesForOriginalEvent.get(0).getProcessingState(), PersistentQueueEntryLifecycleState.FAILED); // Retry events List<NotificationEventModelDao> historicalEntriesForRetries = Iterators.toUnmodifiableList(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("notifications-retries:myEvent-listener", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())); Assert.assertEquals(historicalEntriesForRetries.size(), 3); for (final NotificationEventModelDao historicalEntriesForRetry : historicalEntriesForRetries) { Assert.assertEquals((long) historicalEntriesForRetry.getErrorCount(), (long) 0); Assert.assertEquals(historicalEntriesForRetry.getProcessingState(), PersistentQueueEntryLifecycleState.FAILED); } // Make the next retry work retryableBusService.shouldFail(false); clock.addDays(1); // Make sure all notifications are processed await().atMost(10, TimeUnit.SECONDS).until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return Iterators.size(busSqlDao.getHistoricalQueueEntriesForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2, persistentBusConfig.getHistoryTableName())) == 1 && Iterators.size(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("notifications-retries:myEvent-listener", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())) == 4; } }); // Initial event was processed once historicalEntriesForOriginalEvent = Iterators.toUnmodifiableList(busSqlDao.getHistoricalQueueEntriesForSearchKeys(SEARCH_KEY_1, SEARCH_KEY_2, persistentBusConfig.getHistoryTableName())); Assert.assertEquals(historicalEntriesForOriginalEvent.size(), 1); Assert.assertEquals((long) historicalEntriesForOriginalEvent.get(0).getErrorCount(), (long) 0); // State is still FAILED Assert.assertEquals(historicalEntriesForOriginalEvent.get(0).getProcessingState(), PersistentQueueEntryLifecycleState.FAILED); // Retry events historicalEntriesForRetries = Iterators.toUnmodifiableList(notificationSqlDao.getHistoricalQueueEntriesForSearchKeys("notifications-retries:myEvent-listener", SEARCH_KEY_1, SEARCH_KEY_2, notificationQueueConfig.getHistoryTableName())); Assert.assertEquals(historicalEntriesForRetries.size(), 4); for (int i = 0; i < historicalEntriesForRetries.size(); i++) { final NotificationEventModelDao historicalEntriesForRetry = historicalEntriesForRetries.get(i); Assert.assertEquals((long) historicalEntriesForRetry.getErrorCount(), (long) 0); Assert.assertEquals(historicalEntriesForRetry.getProcessingState(), i == historicalEntriesForRetries.size() - 1 ? PersistentQueueEntryLifecycleState.PROCESSED : PersistentQueueEntryLifecycleState.FAILED); } } finally { retryableBusService.stop(); } } private final class RetryableBusService extends RetryableService { private final SubscriberQueueHandler subscriberQueueHandler = new SubscriberQueueHandler(); private final RetryableSubscriber retryableSubscriber; private boolean shouldFail = true; public RetryableBusService(final NotificationQueueService notificationQueueService) { super(notificationQueueService); subscriberQueueHandler.subscribe(MyEvent.class, new SubscriberAction<MyEvent>() { @Override public void run(final MyEvent event) { if (!shouldFail) { return; } final NullPointerException exceptionForTests = new NullPointerException("Expected exception for tests"); // 4 retries throw new QueueRetryException(exceptionForTests, List.of(Period.millis(1), Period.millis(1), Period.millis(1), Period.days(1))); } }); retryableSubscriber = new RetryableSubscriber(clock, this, subscriberQueueHandler); } public void initialize() { super.initialize("myEvent-listener", subscriberQueueHandler); } @AllowConcurrentEvents @Subscribe public void handleMyEvent(final MyEvent event) { retryableSubscriber.handleEvent(event); } public void shouldFail(final boolean shouldFail) { this.shouldFail = shouldFail; } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/bus/TestInMemoryEventBus.java
queue/src/test/java/org/killbill/bus/TestInMemoryEventBus.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2021 Equinix, Inc * Copyright 2014-2021 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.bus; import java.util.concurrent.TimeUnit; import org.killbill.bus.api.PersistentBusConfig; import org.skife.config.TimeSpan; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.killbill.bus.api.PersistentBus; public class TestInMemoryEventBus { private TestEventBusBase testEventBusBase; private PersistentBus busService; @BeforeClass(groups = "fast") public void beforeClass() throws Exception { busService = new InMemoryPersistentBus(new PersistentBusConfig() { @Override public boolean isInMemory() { return false; } @Override public int getMaxFailureRetries() { return 0; } @Override public int getMinInFlightEntries() { return 1; } @Override public int getMaxInFlightEntries() { return 1; } @Override public int getMaxEntriesClaimed() { return 0; } @Override public PersistentQueueMode getPersistentQueueMode() { return PersistentQueueMode.POLLING; } @Override public TimeSpan getClaimedTime() { return null; } @Override public long getPollingSleepTimeMs() { return 0; } @Override public boolean isProcessingOff() { return false; } @Override public int geMaxDispatchThreads() { return 0; } @Override public int geNbLifecycleDispatchThreads() { return 1; } @Override public int geNbLifecycleCompleteThreads() { return 1; } @Override public int getEventQueueCapacity() { return 0; } @Override public String getTableName() { return "test"; } @Override public String getHistoryTableName() { return null; } @Override public TimeSpan getReapThreshold() { return new TimeSpan(5, TimeUnit.MINUTES); } @Override public int getMaxReDispatchCount() { return 10; } @Override public TimeSpan getReapSchedule() { return new TimeSpan(3, TimeUnit.MINUTES); } @Override public TimeSpan getShutdownTimeout() { return new TimeSpan(5, TimeUnit.SECONDS); } }); testEventBusBase = new TestEventBusBase(busService); } @BeforeMethod(groups = "fast") public void beforeMethod() throws Exception { busService.startQueue(); } @AfterMethod(groups = "fast") public void afterMethod() { busService.stopQueue(); } @Test(groups = "fast") public void testSimple() { testEventBusBase.testSimple(); } @Test(groups = "fast") public void testDifferentType() { testEventBusBase.testDifferentType(); } @Test(groups = "fast") public void testSimpleWithExceptionAndRetrySuccess() { testEventBusBase.testSimpleWithExceptionAndRetrySuccess(); } @Test(groups = "fast") public void testSimpleWithExceptionAndFail() { testEventBusBase.testSimpleWithExceptionAndFail(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/bus/TestPersistentEventBus.java
queue/src/test/java/org/killbill/bus/TestPersistentEventBus.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.bus; import org.killbill.TestSetup; import org.killbill.bus.api.PersistentBus; import org.killbill.commons.utils.collect.Iterables; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class TestPersistentEventBus extends TestSetup { private TestEventBusBase testEventBusBase; private PersistentBus busService; @Override @BeforeClass(groups = "slow") public void beforeClass() throws Exception { super.beforeClass(); } @Override @BeforeMethod(groups = "slow") public void beforeMethod() throws Exception { super.beforeMethod(); // Reinitialize to restart the pool busService = new DefaultPersistentBus(getDBI(), clock, getPersistentBusConfig(), metricRegistry, databaseTransactionNotificationApi); testEventBusBase = new TestEventBusBase(busService); busService.startQueue(); } @AfterMethod(groups = "slow") public void afterMethod() throws Exception { busService.stopQueue(); } @Test(groups = "slow") public void testSimple() { assertNoInProcessingEvent(); testEventBusBase.testSimple(); assertNoInProcessingEvent(); } @Test(groups = "slow") public void testSimpleWithExceptionAndRetrySuccess() { assertNoInProcessingEvent(); testEventBusBase.testSimpleWithExceptionAndRetrySuccess(); assertNoInProcessingEvent(); } @Test(groups = "slow") public void testSimpleWithExceptionAndFail() { assertNoInProcessingEvent(); testEventBusBase.testSimpleWithExceptionAndFail(); assertNoInProcessingEvent(); } private void assertNoInProcessingEvent() { Assert.assertEquals(Iterables.size(busService.getInProcessingBusEvents()), 0); Assert.assertEquals(busService.getNbReadyEntries(clock.getUTCNow()), 0); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/bus/TestPersistentBusDemo.java
queue/src/test/java/org/killbill/bus/TestPersistentBusDemo.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.bus; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import org.killbill.TestSetup; import org.killbill.bus.api.BusEvent; import org.killbill.bus.api.PersistentBus; import org.killbill.commons.embeddeddb.mysql.MySQLEmbeddedDB; import org.killbill.commons.eventbus.AllowConcurrentEvents; import org.killbill.commons.eventbus.Subscribe; import org.killbill.commons.utils.io.Resources; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; import java.util.UUID; public class TestPersistentBusDemo { private MySQLEmbeddedDB embeddedDB; private DefaultPersistentBus bus; private DataSource dataSource; @BeforeClass(groups = "slow") public void beforeClass() throws Exception { embeddedDB = new MySQLEmbeddedDB("killbillq", "killbillq", "killbillq"); embeddedDB.initialize(); embeddedDB.start(); final String ddl = TestSetup.toString(Resources.getResource("org/killbill/queue/ddl.sql").openStream()); embeddedDB.executeScript(ddl); final String ddlTest = TestSetup.toString(Resources.getResource("org/killbill/queue/ddl_test.sql").openStream()); embeddedDB.executeScript(ddlTest); embeddedDB.refreshTableNames(); dataSource = embeddedDB.getDataSource(); final Properties properties = new Properties(); properties.setProperty("org.killbill.persistent.bus.main.inMemory", "false"); properties.setProperty("org.killbill.persistent.bus.main.queue.mode", "STICKY_POLLING"); properties.setProperty("org.killbill.persistent.bus.main.max.failure.retry", "3"); properties.setProperty("org.killbill.persistent.bus.main.claimed", "100"); properties.setProperty("org.killbill.persistent.bus.main.claim.time", "5m"); properties.setProperty("org.killbill.persistent.bus.main.sleep", "100"); properties.setProperty("org.killbill.persistent.bus.main.off", "false"); properties.setProperty("org.killbill.persistent.bus.main.nbThreads", "1"); properties.setProperty("org.killbill.persistent.bus.main.queue.capacity", "3000"); properties.setProperty("org.killbill.persistent.bus.main.tableName", "bus_events"); properties.setProperty("org.killbill.persistent.bus.main.historyTableName", "bus_events_history"); bus = new DefaultPersistentBus(dataSource, properties); } @AfterClass public void afterClass() throws IOException { if (embeddedDB != null) { embeddedDB.stop(); } } @BeforeMethod(groups = "slow") public void beforeMethod() throws Exception { embeddedDB.cleanupAllTables(); bus.startQueue(); } @AfterMethod(groups = "slow") public void afterMethod() throws Exception { bus.stopQueue(); } @Test(groups = "slow") public void testDemo() throws SQLException, PersistentBus.EventBusException { // Create a Handler (with @Subscribe method) final DummyHandler handler = new DummyHandler(); bus.register(handler); // Extract connection from dataSource final Connection connection = dataSource.getConnection(); final DummyEvent event = new DummyEvent("foo", 1L, 2L, UUID.randomUUID()); PreparedStatement stmt = null; try { // In one transaction we both insert a dummy value in some table, and post the event (using same connection/transaction) connection.setAutoCommit(false); stmt = connection.prepareStatement("insert into dummy (dkey, dvalue) values (?, ?)"); stmt.setString(1, "Great!"); stmt.setLong(2, 47L); stmt.executeUpdate(); bus.postFromTransaction(event, connection); connection.commit(); } finally { if (stmt != null) { stmt.close(); } if (connection != null) { connection.close(); } } // // Verify we see the dummy value inserted and also received the event posted // final Connection connection2 = dataSource.getConnection(); PreparedStatement stmt2 = null; try { stmt2 = connection2.prepareStatement("select * from dummy where dkey = ?"); stmt2.setString(1, "Great!"); final ResultSet rs2 = stmt2.executeQuery(); int found = 0; while (rs2.next()) { found++; } Assert.assertEquals(found, 1); } finally { stmt2.close(); } if (connection2 != null) { connection2.close(); } Assert.assertTrue(handler.waitForCompletion(1, 3000)); } public static class DummyEvent implements BusEvent { private final String name; private final Long searchKey1; private final Long searchKey2; private final UUID userToken; @JsonCreator public DummyEvent(@JsonProperty("name") final String name, @JsonProperty("searchKey1") final Long searchKey1, @JsonProperty("searchKey2") final Long searchKey2, @JsonProperty("userToken") final UUID userToken) { this.name = name; this.searchKey2 = searchKey2; this.searchKey1 = searchKey1; this.userToken = userToken; } public String getName() { return name; } @Override public Long getSearchKey1() { return searchKey1; } @Override public Long getSearchKey2() { return searchKey2; } @Override public UUID getUserToken() { return userToken; } } public static class DummyHandler { private int nbEvents; public DummyHandler() { nbEvents = 0; } @AllowConcurrentEvents @Subscribe public void processEvent(final DummyEvent event) { //System.out.println("YEAH!!!!! event = " + event); nbEvents++; } public synchronized boolean waitForCompletion(final int expectedEvents, final long timeoutMs) { final long ini = System.currentTimeMillis(); long remaining = timeoutMs; while (nbEvents < expectedEvents && remaining > 0) { try { wait(1000); if (nbEvents == expectedEvents) { break; } remaining = timeoutMs - (System.currentTimeMillis() - ini); } catch (final InterruptedException ignore) { } } return (nbEvents == expectedEvents); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/bus/TestLoadDefaultPersistentBus.java
queue/src/test/java/org/killbill/bus/TestLoadDefaultPersistentBus.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.bus; import java.util.Map; import java.util.Properties; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.awaitility.Awaitility; import org.killbill.TestSetup; import org.killbill.bus.api.BusEvent; import org.killbill.bus.api.PersistentBus; import org.killbill.bus.api.PersistentBusConfig; import org.killbill.commons.eventbus.AllowConcurrentEvents; import org.killbill.commons.eventbus.Subscribe; import org.skife.config.AugmentedConfigurationObjectFactory; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.TransactionCallback; import org.skife.jdbi.v2.TransactionStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class TestLoadDefaultPersistentBus extends TestSetup { private static final Logger log = LoggerFactory.getLogger(TestLoadDefaultPersistentBus.class); PersistentBus eventBus; // Need to explicitly disable these as they are somehow picked up on CI with specific JDKs @BeforeClass(groups = "load", enabled = false) public void beforeClass() throws Exception { super.beforeClass(); final Properties properties = new Properties(); // See sleep time below in LoadHandler properties.setProperty("org.killbill.persistent.bus.main.inflight.claimed", "500"); properties.setProperty("org.killbill.persistent.bus.external.inMemory", "false"); properties.setProperty("org.killbill.persistent.bus.main.nbThreads", "200"); properties.setProperty("org.killbill.persistent.bus.main.queue.capacity", "20000"); properties.setProperty("org.killbill.persistent.bus.main.sleep", "0"); properties.setProperty("org.killbill.persistent.bus.main.sticky", "true"); properties.setProperty("org.killbill.persistent.bus.main.useInflightQ", "true"); final PersistentBusConfig busConfig = new AugmentedConfigurationObjectFactory(properties).buildWithReplacements(PersistentBusConfig.class, Map.of("instanceName", "main")); eventBus = new DefaultPersistentBus(dbi, clock, busConfig, metricRegistry, databaseTransactionNotificationApi); } @BeforeMethod(groups = "load", enabled = false) public void beforeMethod() throws Exception { super.beforeMethod(); eventBus.startQueue(); } @AfterMethod(groups = "load", enabled = false) public void afterMethod() throws Exception { eventBus.stopQueue(); } @Test(groups = "load", enabled = false) public void testMultiThreadedLoad() throws Exception { final LoadHandler consumer = new LoadHandler(); eventBus.register(consumer); final Long targetEventsPerSecond = 700L; final int testDurationMinutes = 2; final Long nbEvents = targetEventsPerSecond * testDurationMinutes * 60; final Producer producer = new Producer(nbEvents, targetEventsPerSecond); try { final Thread producerThread = new Thread(producer); producerThread.start(); consumer.waitForCompletion(nbEvents, testDurationMinutes * 60 * 1000); } finally { producer.stop(); } } public static final class LoadHandler { private final AtomicLong nbEvents = new AtomicLong(0); private final AtomicLong nbEventsForLogging = new AtomicLong(0); private final AtomicLong lastLogLineTime = new AtomicLong(System.currentTimeMillis()); @AllowConcurrentEvents @Subscribe public void processEvent(final LoadBusEvent event) { try { // Go to a Ruby plugin, database, etc. Thread.sleep(200L); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } nbEvents.incrementAndGet(); nbEventsForLogging.incrementAndGet(); final long delayMillis = System.currentTimeMillis() - lastLogLineTime.get(); if (delayMillis > 10000) { log.info("Consumer processed {} events in {}s", nbEventsForLogging, delayMillis / 1000.0); nbEventsForLogging.set(0); lastLogLineTime.set(System.currentTimeMillis()); } } public void waitForCompletion(final Long expectedEvents, final long timeoutMs) { Awaitility.await() .atMost(timeoutMs, TimeUnit.MILLISECONDS) .until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return nbEvents.get() == expectedEvents; } }); } } private static final class LoadBusEvent implements BusEvent { private final String payload; private final Long searchKey1; private final Long searchKey2; private final UUID userToken; public LoadBusEvent() { // Generate 540 bytes of data final StringBuilder payloadBuilder = new StringBuilder(); for (int i = 0; i < 15; i++) { payloadBuilder.append(UUID.randomUUID().toString()); } this.payload = payloadBuilder.toString(); this.searchKey2 = 12L; this.searchKey1 = 42L; this.userToken = UUID.randomUUID(); } @JsonCreator public LoadBusEvent(@JsonProperty("payload") final String payload, @JsonProperty("searchKey1") final Long searchKey1, @JsonProperty("searchKey2") final Long searchKey2, @JsonProperty("userToken") final UUID userToken) { this.payload = payload; this.searchKey2 = searchKey2; this.searchKey1 = searchKey1; this.userToken = userToken; } // Note! Getter required to have the value serialized to disk public String getPayload() { return payload; } @Override public Long getSearchKey1() { return searchKey1; } @Override public Long getSearchKey2() { return searchKey2; } @Override public UUID getUserToken() { return userToken; } } private final class Producer implements Runnable { private final AtomicBoolean isStarted = new AtomicBoolean(true); // Total number of events to send private final Long nbEvents; // Producer speed private final Long targetEventsPerSecond; public Producer(final Long nbEvents, final Long targetEventsPerSecond) { this.nbEvents = nbEvents; this.targetEventsPerSecond = targetEventsPerSecond; } public void stop() { isStarted.set(false); } @Override public void run() { final int batchLengthSeconds = 10; final long eventsPerBatch = batchLengthSeconds * targetEventsPerSecond; Long nbEventsSent = 0L; while (isStarted.get() && nbEventsSent < nbEvents) { final Long t1 = System.currentTimeMillis(); for (int i = 0; i < eventsPerBatch; i++) { postEvent(); } final Long delayMillis = System.currentTimeMillis() - t1; final int maxDelayMillis = batchLengthSeconds * 1000; if (delayMillis > maxDelayMillis) { log.warn("Generated {} entries in {}s - producer slow", eventsPerBatch, delayMillis / 1000.0); } else { log.info("Generated {} entries in {}s", eventsPerBatch, delayMillis / 1000.0); try { Thread.sleep(maxDelayMillis - delayMillis); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } } nbEventsSent += eventsPerBatch; } log.info("Producer shutting down - {} events sent", nbEventsSent); } private void postEvent() { dbi.inTransaction(new TransactionCallback<Void>() { @Override public Void inTransaction(final Handle conn, final TransactionStatus status) throws Exception { Assert.assertEquals(conn.select("select now();").size(), 1); final BusEvent event = new LoadBusEvent(); eventBus.postFromTransaction(event, conn.getConnection()); return null; } }); } } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/test/java/org/killbill/bus/dao/TestBusSqlDao.java
queue/src/test/java/org/killbill/bus/dao/TestBusSqlDao.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.bus.dao; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.killbill.TestSetup; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; public class TestBusSqlDao extends TestSetup { private static final String hostname = "Hip"; private static final long SEARCH_KEY_2 = 39; private PersistentBusSqlDao dao; @BeforeClass(groups = "slow") public void beforeClass() throws Exception { super.beforeClass(); dao = getDBI().onDemand(PersistentBusSqlDao.class); } // Verify we retrieve all existing ready recordIds -- with no dups -- using a batch approach. @Test(groups = "slow") public void testGetReadyEntryIds() { final long searchKey1 = 1242L; final int TOTAL_ENTRIES = 1543; final ArrayList<BusEventModelDao> entries = new ArrayList<>(TOTAL_ENTRIES); for (int i = 0; i < TOTAL_ENTRIES; i++) { final String eventJson = String.valueOf(i); final BusEventModelDao e = new BusEventModelDao(hostname, clock.getUTCNow(), eventJson.getClass().toString(), eventJson, UUID.randomUUID(), searchKey1, SEARCH_KEY_2); entries.add(e); } dao.insertEntries(entries, persistentBusConfig.getTableName()); int remaining = TOTAL_ENTRIES; final int BATCH_SIZE = 100; int totalEntries = 0; long fromRecordId = -1; while (remaining > 0) { //System.err.print(String.format("from = %d\n", fromRecordId)); final List<Long> curBatch = dao.getReadyEntryIds(clock.getUTCNow().toDate(), fromRecordId, BATCH_SIZE, hostname, persistentBusConfig.getTableName()); if (remaining / BATCH_SIZE > 0) { assertEquals(curBatch.size(), BATCH_SIZE); } else { assertEquals(curBatch.size(), remaining); } for (Long e : curBatch) { if (fromRecordId == -1) { fromRecordId = e; } else { assertEquals(e.longValue(), fromRecordId); } fromRecordId++; } remaining -= curBatch.size(); totalEntries += curBatch.size(); } assertEquals(totalEntries, TOTAL_ENTRIES); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/main/java/org/killbill/CreatorName.java
queue/src/main/java/org/killbill/CreatorName.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.UUID; import org.killbill.commons.utils.Strings; import org.killbill.commons.utils.annotation.VisibleForTesting; public class CreatorName { private static final Object lock = new Object(); // If set to true and QUEUE_CREATOR_NAME is not set, generate a UUID instead of using default hostname. static final String AUTO_GENERATED_QUEUE_CREATOR_NAME = "org.killbill.queue.creator.autoGeneratedName"; // Allow to override the default naming based on Hostname static final String QUEUE_CREATOR_NAME = "org.killbill.queue.creator.name"; private static String creatorName; public static String get() { if (creatorName == null) { synchronized (lock) { String tmpCreatorName = System.getProperty(QUEUE_CREATOR_NAME); if (Strings.emptyToNull(tmpCreatorName) == null) { final boolean autoGenerateCreatorName = Boolean.parseBoolean(System.getProperty(AUTO_GENERATED_QUEUE_CREATOR_NAME, "false")); if (autoGenerateCreatorName) { tmpCreatorName = UUID.randomUUID().toString(); } else { try { final InetAddress addr = InetAddress.getLocalHost(); tmpCreatorName = addr.getHostName(); } catch (final UnknownHostException e) { tmpCreatorName = "creatorName-unknown"; } } } creatorName = tmpCreatorName.length() > 45 ? tmpCreatorName.substring(0, 45) : tmpCreatorName; } } return creatorName; } @VisibleForTesting static synchronized void reset() { creatorName = null; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/main/java/org/killbill/notificationq/DefaultNotificationQueueService.java
queue/src/main/java/org/killbill/notificationq/DefaultNotificationQueueService.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq; import java.util.Map; import java.util.Properties; import javax.inject.Inject; import javax.inject.Named; import javax.sql.DataSource; import org.killbill.clock.Clock; import org.killbill.clock.DefaultClock; import org.killbill.commons.metrics.api.MetricRegistry; import org.killbill.commons.metrics.impl.NoOpMetricRegistry; import org.killbill.notificationq.api.NotificationQueue; import org.killbill.notificationq.api.NotificationQueueConfig; import org.killbill.queue.InTransaction; import org.skife.config.AugmentedConfigurationObjectFactory; import org.skife.config.SimplePropertyConfigSource; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.IDBI; /** * A factory to create notification queues. * An application will typically have a single instance and call <code>createNotificationQueue</code> * to create one or several queues. */ public class DefaultNotificationQueueService extends NotificationQueueServiceBase { private final DBI dbi; /** * @param idbi a DBI instance from the killbill-jdbi jar * @param clock a clock instance from the killbill-clock jar * @param config queues configuration * @param metricRegistry DropWizard metrics registry instance */ @Inject public DefaultNotificationQueueService(@Named(QUEUE_NAME) final IDBI idbi, final Clock clock, final NotificationQueueConfig config, final MetricRegistry metricRegistry) { super(clock, config, idbi, metricRegistry); this.dbi = (DBI) idbi; } /** * Simple constructor when the DBI instance, clock or registry objects don't need to be configured * * @param dataSource JDBC datasource * @param properties configuration properties */ public DefaultNotificationQueueService(final DataSource dataSource, final Properties properties) { this(InTransaction.buildDDBI(dataSource), new DefaultClock(), new AugmentedConfigurationObjectFactory(new SimplePropertyConfigSource(properties)).buildWithReplacements(NotificationQueueConfig.class, Map.of("instanceName", "main")), new NoOpMetricRegistry()); } @Override protected NotificationQueue createNotificationQueueInternal(final String svcName, final String queueName, final NotificationQueueHandler handler) { return new DefaultNotificationQueue(svcName, queueName, handler, dbi, dao, this, clock, config); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/main/java/org/killbill/notificationq/NotificationQueueServiceBase.java
queue/src/main/java/org/killbill/notificationq/NotificationQueueServiceBase.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq; import java.util.ArrayList; import java.util.List; import org.killbill.clock.Clock; import org.killbill.commons.metrics.api.MetricRegistry; import org.killbill.notificationq.api.NotificationQueue; import org.killbill.notificationq.api.NotificationQueueConfig; import org.killbill.notificationq.api.NotificationQueueService; import org.skife.jdbi.v2.IDBI; public abstract class NotificationQueueServiceBase extends NotificationQueueDispatcher implements NotificationQueueService { public NotificationQueueServiceBase(final Clock clock, final NotificationQueueConfig config, final IDBI dbi, final MetricRegistry metricRegistry) { super(clock, config, dbi, metricRegistry); } @Override public NotificationQueue createNotificationQueue(final String svcName, final String queueName, final NotificationQueueHandler handler) throws NotificationQueueAlreadyExists { if (svcName == null || queueName == null || handler == null) { throw new RuntimeException("Need to specify all parameters"); } final String compositeName = getCompositeName(svcName, queueName); NotificationQueue result; synchronized (queues) { result = queues.get(compositeName); if (result != null) { throw new NotificationQueueAlreadyExists(String.format("Queue for svc %s and name %s already exist", svcName, queueName)); } result = createNotificationQueueInternal(svcName, queueName, handler); queues.put(compositeName, result); } return result; } @Override public NotificationQueue getNotificationQueue(final String svcName, final String queueName) throws NoSuchNotificationQueue { final NotificationQueue result; final String compositeName = getCompositeName(svcName, queueName); synchronized (queues) { result = queues.get(compositeName); if (result == null) { throw new NoSuchNotificationQueue(String.format("Queue for svc %s and name %s does not exist", svcName, queueName)); } } return result; } public void deleteNotificationQueue(final String svcName, final String queueName) throws NoSuchNotificationQueue { final String compositeName = getCompositeName(svcName, queueName); synchronized (queues) { final NotificationQueue result = queues.get(compositeName); if (result == null) { throw new NoSuchNotificationQueue(String.format("Queue for svc %s and name %s does not exist", svcName, queueName)); } queues.remove(compositeName); } } @Override public List<NotificationQueue> getNotificationQueues() { return new ArrayList<NotificationQueue>(queues.values()); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("NotificationQueueServiceBase"); sb.append("{queues=").append(queues); sb.append('}'); return sb.toString(); } protected abstract NotificationQueue createNotificationQueueInternal(String svcName, String queueName, NotificationQueueHandler handler); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/main/java/org/killbill/notificationq/NotificationQueueDispatcher.java
queue/src/main/java/org/killbill/notificationq/NotificationQueueDispatcher.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2021 Equinix, Inc * Copyright 2014-2021 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq; import java.lang.Thread.UncaughtExceptionHandler; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.killbill.clock.Clock; import org.killbill.commons.metrics.api.Histogram; import org.killbill.commons.metrics.api.MetricRegistry; import org.killbill.notificationq.api.NotificationEvent; import org.killbill.notificationq.api.NotificationQueue; import org.killbill.notificationq.api.NotificationQueueConfig; import org.killbill.notificationq.api.NotificationQueueService.NotificationQueueHandler; import org.killbill.notificationq.dao.NotificationEventModelDao; import org.killbill.notificationq.dao.NotificationSqlDao; import org.killbill.notificationq.dispatching.NotificationCallableCallback; import org.killbill.queue.DBBackedQueue; import org.killbill.queue.DBBackedQueue.ReadyEntriesWithMetrics; import org.killbill.queue.DBBackedQueueWithPolling; import org.killbill.queue.DefaultQueueLifecycle; import org.killbill.queue.dao.EventEntryModelDao; import org.killbill.queue.dispatching.BlockingRejectionExecutionHandler; import org.killbill.queue.dispatching.Dispatcher; import org.skife.jdbi.v2.IDBI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NotificationQueueDispatcher extends DefaultQueueLifecycle { protected static final Logger log = LoggerFactory.getLogger(NotificationQueueDispatcher.class); public static final int CLAIM_TIME_MS = (5 * 60 * 1000); // 5 minutes private final AtomicLong nbProcessedEvents; protected final NotificationQueueConfig config; protected final Clock clock; protected final Map<String, NotificationQueue> queues; protected final DBBackedQueue<NotificationEventModelDao> dao; protected final MetricRegistry metricRegistry; private final Map<String, Histogram> perQueueProcessingTime; // We could event have one per queue is required... private final Dispatcher<NotificationEvent, NotificationEventModelDao> dispatcher; private final AtomicBoolean isInitialized; private volatile boolean isStarted; private volatile int activeQueues; private final NotificationCallableCallback notificationCallableCallback; private final NotificationReaper reaper; // Package visibility on purpose NotificationQueueDispatcher(final Clock clock, final NotificationQueueConfig config, final IDBI dbi, final MetricRegistry metricRegistry) { super(config.getTableName(), config, metricRegistry); final ThreadFactory notificationQThreadFactory = new ThreadFactory() { @Override public Thread newThread(final Runnable r) { final Thread th = new Thread(r); th.setName(config.getTableName() + "-th"); th.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread t, final Throwable e) { log.error("Uncaught exception for thread " + t.getName(), e); } }); return th; } }; this.clock = clock; this.config = config; this.nbProcessedEvents = new AtomicLong(); this.dao = new DBBackedQueueWithPolling<NotificationEventModelDao>(clock, dbi, NotificationSqlDao.class, config, config.getTableName(), metricRegistry); this.queues = new TreeMap<String, NotificationQueue>(); this.perQueueProcessingTime = new HashMap<String, Histogram>(); this.metricRegistry = metricRegistry; this.isInitialized = new AtomicBoolean(false); this.isStarted = false; this.activeQueues = 0; this.reaper = new NotificationReaper(this.dao, config, clock); this.notificationCallableCallback = new NotificationCallableCallback(this); this.dispatcher = new Dispatcher<>(1, config, 10, TimeUnit.MINUTES, config.getShutdownTimeout().getPeriod(), config.getShutdownTimeout().getUnit(), new LinkedBlockingQueue<Runnable>(config.getEventQueueCapacity()), notificationQThreadFactory, new BlockingRejectionExecutionHandler(), clock, notificationCallableCallback, this); } @Override public boolean initQueue() { if (isInitialized.compareAndSet(false, true)) { dao.initialize(); dispatcher.start(); return true; } else { return false; } } @Override public boolean startQueue() { if (!isInitialized.get()) { // Make it easy for our tests, so they simply call startQueue initQueue(); } // // The first DefaultNotificationQueue#startQueue will call this method and start the reaper and lifecycle dispatch thread pool // All subsequent DefaultNotificationQueue#startQueue will simply increment the # activeQueues // synchronized (queues) { // Increment number of active queues activeQueues++; if (!isStarted) { reaper.start(); super.startQueue(); isStarted = true; return true; } else { return false; } } } @Override public boolean stopQueue() { synchronized (queues) { if (activeQueues == 0) { return true; } activeQueues--; // // The last DefaultNotificationQueue#stopQueue will call this method and stop the reaper and lifecycle dispatch thread pool // if (activeQueues == 0) { isInitialized.set(false); boolean terminated = true; // Stop the reaper first if (!reaper.stop()) { terminated = false; } // Then, the lifecycle dispatcher threads (no new work accepted) if (!super.stopLifecycleDispatcher()) { terminated = false; } // Then, stop the working threads (finish on-going work) if (!dispatcher.stopDispatcher()) { terminated = false; } // Finally, stop the completion threads (cleanup recently finished work) if (!super.stopLifecycleCompletion()) { terminated = false; } dao.close(); isStarted = false; return terminated; } return false; } } @Override public boolean isStarted() { return isStarted; } @Override public DispatchResultMetrics doDispatchEvents() { final List<NotificationEventModelDao> notifications = getReadyNotifications(); if (notifications.isEmpty()) { return new DispatchResultMetrics(0, -1); } log.debug("Notifications from {} to process: {}", config.getTableName(), notifications); for (final NotificationEventModelDao cur : notifications) { dispatcher.dispatch(cur); } // No need to return time, this is easy to compute from caller return new DispatchResultMetrics(notifications.size(), -1); } @Override public void doProcessCompletedEvents(final Iterable<? extends EventEntryModelDao> completed) { notificationCallableCallback.moveCompletedOrFailedEvents((Iterable<NotificationEventModelDao>) completed); } @Override public void doProcessRetriedEvents(final Iterable<? extends EventEntryModelDao> retried) { Iterator<? extends EventEntryModelDao> it = retried.iterator(); while (it.hasNext()) { NotificationEventModelDao cur = (NotificationEventModelDao) it.next(); notificationCallableCallback.updateRetriedEvents(cur); } } public void handleNotificationWithMetrics(final NotificationQueueHandler handler, final NotificationEventModelDao notification, final NotificationEvent key) throws NotificationQueueException { // Create specific metric name because: // - ':' is not allowed for metric name // - name would be too long (e.g entitlement-service:subscription-events-process-time -> ent-subscription-events-process-time) // final String[] parts = notification.getQueueName().split(":"); final String metricName = new StringBuilder(parts[0].substring(0, 3)) .append("-") .append(parts[1]) .append("-ProcessingTime").toString(); Histogram perQueueHistogramProcessingTime = perQueueProcessingTime.get(notification.getQueueName()); if (perQueueHistogramProcessingTime == null) { synchronized (perQueueProcessingTime) { if (!perQueueProcessingTime.containsKey(notification.getQueueName())) { perQueueProcessingTime.put(notification.getQueueName(), metricRegistry.histogram(String.format("%s.%s", NotificationQueueDispatcher.class.getName(), metricName))); } perQueueHistogramProcessingTime = perQueueProcessingTime.get(notification.getQueueName()); } } final long beforeProcessing = System.nanoTime(); try { handler.handleReadyNotification(key, notification.getEffectiveDate(), notification.getFutureUserToken(), notification.getSearchKey1(), notification.getSearchKey2()); } catch (final RuntimeException e) { throw new NotificationQueueException(e); } finally { nbProcessedEvents.incrementAndGet(); // Unclear if those stats should include failures perQueueHistogramProcessingTime.update(System.nanoTime() - beforeProcessing); } } public NotificationQueueHandler getHandlerForActiveQueue(final String compositeName) { final NotificationQueue queue = queues.get(compositeName); if (queue == null || !queue.isStarted()) { return null; } return queue.getHandler(); } private List<NotificationEventModelDao> getReadyNotifications() { final ReadyEntriesWithMetrics<NotificationEventModelDao> result = dao.getReadyEntries(); final List<NotificationEventModelDao> input = result.getEntries(); final List<NotificationEventModelDao> claimedNotifications = new ArrayList<NotificationEventModelDao>(); for (final NotificationEventModelDao cur : input) { // Skip non active queues... final NotificationQueue queue = queues.get(cur.getQueueName()); if (queue == null || !queue.isStarted()) { continue; } claimedNotifications.add(cur); } return claimedNotifications; } public static String getCompositeName(final String svcName, final String queueName) { return svcName + ":" + queueName; } public NotificationQueueConfig getConfig() { return config; } public Clock getClock() { return clock; } public DBBackedQueue<NotificationEventModelDao> getDao() { return dao; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/main/java/org/killbill/notificationq/NotificationReaper.java
queue/src/main/java/org/killbill/notificationq/NotificationReaper.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq; import org.killbill.clock.Clock; import org.killbill.notificationq.api.NotificationQueueConfig; import org.killbill.notificationq.dao.NotificationEventModelDao; import org.killbill.queue.DBBackedQueue; import org.killbill.queue.DefaultReaper; public class NotificationReaper extends DefaultReaper { public NotificationReaper(final DBBackedQueue<NotificationEventModelDao> dao, final NotificationQueueConfig config, final Clock clock) { super(dao, config, clock, "NotificationReaper"); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/main/java/org/killbill/notificationq/DefaultUUIDNotificationKey.java
queue/src/main/java/org/killbill/notificationq/DefaultUUIDNotificationKey.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq; import java.util.UUID; import org.killbill.notificationq.api.NotificationEvent; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class DefaultUUIDNotificationKey implements NotificationEvent { private final UUID uuidKey; @JsonCreator public DefaultUUIDNotificationKey(@JsonProperty("uuidKey") final UUID uuidKey) { this.uuidKey = uuidKey; } public UUID getUuidKey() { return uuidKey; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((uuidKey == null) ? 0 : uuidKey.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final DefaultUUIDNotificationKey other = (DefaultUUIDNotificationKey) obj; if (uuidKey == null) { if (other.uuidKey != null) { return false; } } else if (!uuidKey.equals(other.uuidKey)) { return false; } return true; } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/main/java/org/killbill/notificationq/NotificationQueueException.java
queue/src/main/java/org/killbill/notificationq/NotificationQueueException.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq; public class NotificationQueueException extends Exception { public NotificationQueueException() { } public NotificationQueueException(final String message) { super(message); } public NotificationQueueException(final String message, final Throwable cause) { super(message, cause); } public NotificationQueueException(final Throwable cause) { super(cause); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/main/java/org/killbill/notificationq/DefaultNotificationQueue.java
queue/src/main/java/org/killbill/notificationq/DefaultNotificationQueue.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2021 Equinix, Inc * Copyright 2014-2021 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Objects; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.joda.time.DateTime; import org.killbill.CreatorName; import org.killbill.clock.Clock; import org.killbill.commons.profiling.Profiling; import org.killbill.commons.profiling.ProfilingFeature; import org.killbill.commons.utils.collect.Iterables; import org.killbill.commons.utils.collect.Iterators; import org.killbill.notificationq.api.NotificationEvent; import org.killbill.notificationq.api.NotificationEventWithMetadata; import org.killbill.notificationq.api.NotificationQueue; import org.killbill.notificationq.api.NotificationQueueConfig; import org.killbill.notificationq.api.NotificationQueueService; import org.killbill.notificationq.api.NotificationQueueService.NotificationQueueHandler; import org.killbill.notificationq.dao.NotificationEventModelDao; import org.killbill.notificationq.dao.NotificationSqlDao; import org.killbill.queue.DBBackedQueue; import org.killbill.queue.InTransaction; import org.killbill.queue.QueueObjectMapper; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.dao.QueueSqlDao; import org.killbill.queue.dispatching.CallableCallbackBase; import org.killbill.queue.dispatching.EventEntryDeserializer; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Transaction; import org.skife.jdbi.v2.TransactionStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.ObjectWriter; public class DefaultNotificationQueue implements NotificationQueue { private static final Logger logger = LoggerFactory.getLogger(DefaultNotificationQueue.class); private final DBI dbi; private final DBBackedQueue<NotificationEventModelDao> dao; private final String svcName; private final String queueName; private final NotificationQueueHandler handler; private final NotificationQueueService notificationQueueService; private final ObjectReader objectReader; private final ObjectWriter objectWriter; private final Clock clock; private final NotificationQueueConfig config; private final Profiling<Iterable<NotificationEventModelDao>, RuntimeException> prof; private AtomicBoolean isInitialized; private AtomicBoolean isStarted; public DefaultNotificationQueue(final String svcName, final String queueName, final NotificationQueueHandler handler, final DBI dbi, final DBBackedQueue<NotificationEventModelDao> dao, final NotificationQueueService notificationQueueService, final Clock clock, final NotificationQueueConfig config) { this(svcName, queueName, handler, dbi, dao, notificationQueueService, clock, config, QueueObjectMapper.get()); } public DefaultNotificationQueue(final String svcName, final String queueName, final NotificationQueueHandler handler, final DBI dbi, final DBBackedQueue<NotificationEventModelDao> dao, final NotificationQueueService notificationQueueService, final Clock clock, final NotificationQueueConfig config, final ObjectMapper objectMapper) { this.isStarted = new AtomicBoolean(false); this.isInitialized = new AtomicBoolean(false); this.dbi = dbi; this.svcName = svcName; this.queueName = queueName; this.handler = handler; this.dao = dao; this.notificationQueueService = notificationQueueService; this.objectReader = objectMapper.reader(); this.objectWriter = objectMapper.writer(); this.clock = clock; this.config = config; this.prof = new Profiling<Iterable<NotificationEventModelDao>, RuntimeException>(); } @Override public void recordFutureNotification(final DateTime futureNotificationTime, final NotificationEvent event, final UUID userToken, final Long searchKey1, final Long searchKey2) throws IOException { final String eventJson = objectWriter.writeValueAsString(event); final UUID futureUserToken = UUID.randomUUID(); final Long searchKey2WithNull = Objects.requireNonNullElse(searchKey2, 0L); final NotificationEventModelDao notification = new NotificationEventModelDao(CreatorName.get(), clock.getUTCNow(), event.getClass().getName(), eventJson, userToken, searchKey1, searchKey2WithNull, futureUserToken, futureNotificationTime, getFullQName()); dao.insertEntry(notification); } @Override public void recordFutureNotificationFromTransaction(final Connection connection, final DateTime futureNotificationTime, final NotificationEvent event, final UUID userToken, final Long searchKey1, final Long searchKey2) throws IOException { final String eventJson = objectWriter.writeValueAsString(event); final UUID futureUserToken = UUID.randomUUID(); final Long searchKey2WithNull = Objects.requireNonNullElse(searchKey2, 0L); final NotificationEventModelDao notification = new NotificationEventModelDao(CreatorName.get(), clock.getUTCNow(), event.getClass().getName(), eventJson, userToken, searchKey1, searchKey2WithNull, futureUserToken, futureNotificationTime, getFullQName()); final InTransaction.InTransactionHandler<NotificationSqlDao, Void> handler = new InTransaction.InTransactionHandler<NotificationSqlDao, Void>() { @Override public Void withSqlDao(final NotificationSqlDao transactional) { dao.insertEntryFromTransaction(transactional, notification); return null; } }; InTransaction.execute(dbi, connection, handler, NotificationSqlDao.class); } @Override public void updateFutureNotification(final Long recordId, final NotificationEvent event, final Long searchKey1, final Long searchKey2) throws IOException { final String eventJson = objectWriter.writeValueAsString(event); final Long searchKey2WithNull = Objects.requireNonNullElse(searchKey2, 0L); ((NotificationSqlDao) dao.getSqlDao()).updateEntry(recordId, eventJson, searchKey1, searchKey2WithNull, config.getTableName()); } @Override public void updateFutureNotificationFromTransaction(final Connection connection, final Long recordId, final NotificationEvent event, final Long searchKey1, final Long searchKey2) throws IOException { final String eventJson = objectWriter.writeValueAsString(event); final Long searchKey2WithNull = Objects.requireNonNullElse(searchKey2, 0L); final InTransaction.InTransactionHandler<NotificationSqlDao, Void> handler = new InTransaction.InTransactionHandler<NotificationSqlDao, Void>() { @Override public Void withSqlDao(final NotificationSqlDao transactional) { ((NotificationSqlDao) dao.getSqlDao()).updateEntry(recordId, eventJson, searchKey1, searchKey2WithNull, config.getTableName()); return null; } }; InTransaction.execute(dbi, connection, handler, NotificationSqlDao.class); } @Override public <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureNotificationForSearchKeys(final Long searchKey1, final Long searchKey2) { return getFutureNotificationsInternal((NotificationSqlDao) dao.getSqlDao(), null, searchKey1, searchKey2); } @Override public <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureNotificationFromTransactionForSearchKeys(final Long searchKey1, final Long searchKey2, final Connection connection) { final InTransaction.InTransactionHandler<NotificationSqlDao, Iterable<NotificationEventWithMetadata<T>>> handler = new InTransaction.InTransactionHandler<NotificationSqlDao, Iterable<NotificationEventWithMetadata<T>>>() { @Override public Iterable<NotificationEventWithMetadata<T>> withSqlDao(final NotificationSqlDao transactional) { return getFutureNotificationsInternal(transactional, null, searchKey1, searchKey2); } }; return InTransaction.execute(dbi, connection, handler, NotificationSqlDao.class); } @Override public <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureNotificationForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2) { return getFutureNotificationsInternal((NotificationSqlDao) dao.getSqlDao(), maxEffectiveDate, null, searchKey2); } @Override public <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureNotificationFromTransactionForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2, final Connection connection) { final InTransaction.InTransactionHandler<NotificationSqlDao, Iterable<NotificationEventWithMetadata<T>>> handler = new InTransaction.InTransactionHandler<NotificationSqlDao, Iterable<NotificationEventWithMetadata<T>>>() { @Override public Iterable<NotificationEventWithMetadata<T>> withSqlDao(final NotificationSqlDao transactional) { return getFutureNotificationsInternal(transactional, maxEffectiveDate, null, searchKey2); } }; return InTransaction.execute(dbi, connection, handler, NotificationSqlDao.class); } @Override public <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getInProcessingNotifications() { return toNotificationEventWithMetadata(dao.getSqlDao().getInProcessingEntries(config.getTableName())); } @Override public <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationForSearchKeys(final Long searchKey1, final Long searchKey2) { return getFutureOrInProcessingNotificationsInternal((NotificationSqlDao) dao.getSqlDao(), null, searchKey1, searchKey2); } @Override public <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationFromTransactionForSearchKeys(final Long searchKey1, final Long searchKey2, final Connection connection) { final InTransaction.InTransactionHandler<NotificationSqlDao, Iterable<NotificationEventWithMetadata<T>>> handler = new InTransaction.InTransactionHandler<NotificationSqlDao, Iterable<NotificationEventWithMetadata<T>>>() { @Override public Iterable<NotificationEventWithMetadata<T>> withSqlDao(final NotificationSqlDao transactional) { return getFutureOrInProcessingNotificationsInternal(transactional, null, searchKey1, searchKey2); } }; return InTransaction.execute(dbi, connection, handler, NotificationSqlDao.class); } @Override public <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2) { return getFutureOrInProcessingNotificationsInternal((NotificationSqlDao) dao.getSqlDao(), maxEffectiveDate, null, searchKey2); } @Override public <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationFromTransactionForSearchKey2(final DateTime maxEffectiveDate, final Long searchKey2, final Connection connection) { final InTransaction.InTransactionHandler<NotificationSqlDao, Iterable<NotificationEventWithMetadata<T>>> handler = new InTransaction.InTransactionHandler<NotificationSqlDao, Iterable<NotificationEventWithMetadata<T>>>() { @Override public Iterable<NotificationEventWithMetadata<T>> withSqlDao(final NotificationSqlDao transactional) { return getFutureOrInProcessingNotificationsInternal(transactional, maxEffectiveDate, null, searchKey2); } }; return InTransaction.execute(dbi, connection, handler, NotificationSqlDao.class); } @Override public <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getHistoricalNotificationForSearchKeys(final Long searchKey1, final Long searchKey2) { return getHistoricalNotificationsInternal((NotificationSqlDao) dao.getSqlDao(), null, searchKey1, searchKey2); } @Override public <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getHistoricalNotificationForSearchKey2(final DateTime minEffectiveDate, final Long searchKey2) { return getHistoricalNotificationsInternal((NotificationSqlDao) dao.getSqlDao(), minEffectiveDate, null, searchKey2); } private <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureNotificationsInternal(final NotificationSqlDao transactionalDao, @Nullable final DateTime maxEffectiveDate, @Nullable final Long searchKey1, final Long searchKey2) { final Iterable<NotificationEventModelDao> entries = getFutureNotificationsInternalWithProfiling(transactionalDao, maxEffectiveDate, searchKey1, searchKey2); return toNotificationEventWithMetadata(entries); } private <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getFutureOrInProcessingNotificationsInternal(final NotificationSqlDao transactionalDao, @Nullable final DateTime maxEffectiveDate, @Nullable final Long searchKey1, final Long searchKey2) { final Iterable<NotificationEventModelDao> entries = getFutureOrInProcessingNotificationsInternalWithProfiling(transactionalDao, maxEffectiveDate, searchKey1, searchKey2); return toNotificationEventWithMetadata(entries); } private <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> getHistoricalNotificationsInternal(final NotificationSqlDao transactionalDao, @Nullable final DateTime minEffectiveDate, @Nullable final Long searchKey1, final Long searchKey2) { final Iterable<NotificationEventModelDao> entries = getHistoricalNotificationsInternalWithProfiling(transactionalDao, minEffectiveDate, searchKey1, searchKey2); return toNotificationEventWithMetadata(entries); } private Iterable<NotificationEventModelDao> getFutureNotificationsInternalWithProfiling(final NotificationSqlDao transactionalDao, @Nullable final DateTime maxEffectiveDate, @Nullable final Long searchKey1, final Long searchKey2) { return prof.executeWithProfiling(ProfilingFeature.ProfilingFeatureType.DAO, "DAO:NotificationSqlDao:getReadyQueueEntriesForSearchKeys", new Profiling.WithProfilingCallback<Iterable<NotificationEventModelDao>, RuntimeException>() { @Override public Iterable<NotificationEventModelDao> execute() throws RuntimeException { return new Iterable<NotificationEventModelDao>() { @Override public Iterator<NotificationEventModelDao> iterator() { return searchKey1 != null ? transactionalDao.getReadyQueueEntriesForSearchKeys(getFullQName(), searchKey1, searchKey2, config.getTableName()) : transactionalDao.getReadyQueueEntriesForSearchKey2(getFullQName(), maxEffectiveDate, searchKey2, config.getTableName()); } }; } }); } private Iterable<NotificationEventModelDao> getFutureOrInProcessingNotificationsInternalWithProfiling(final NotificationSqlDao transactionalDao, @Nullable final DateTime maxEffectiveDate, @Nullable final Long searchKey1, final Long searchKey2) { return prof.executeWithProfiling(ProfilingFeature.ProfilingFeatureType.DAO, "DAO:NotificationSqlDao:getReadyOrInProcessingQueueEntriesForSearchKeys", new Profiling.WithProfilingCallback<Iterable<NotificationEventModelDao>, RuntimeException>() { @Override public Iterable<NotificationEventModelDao> execute() throws RuntimeException { return new Iterable<NotificationEventModelDao>() { @Override public Iterator<NotificationEventModelDao> iterator() { return searchKey1 != null ? transactionalDao.getReadyOrInProcessingQueueEntriesForSearchKeys(getFullQName(), searchKey1, searchKey2, config.getTableName()) : transactionalDao.getReadyOrInProcessingQueueEntriesForSearchKey2(getFullQName(), maxEffectiveDate, searchKey2, config.getTableName()); } }; } }); } private Iterable<NotificationEventModelDao> getHistoricalNotificationsInternalWithProfiling(final NotificationSqlDao transactionalDao, @Nullable final DateTime minEffectiveDate, @Nullable final Long searchKey1, final Long searchKey2) { return prof.executeWithProfiling(ProfilingFeature.ProfilingFeatureType.DAO, "DAO:NotificationSqlDao:getHistoricalQueueEntriesForSearchKeys", new Profiling.WithProfilingCallback<Iterable<NotificationEventModelDao>, RuntimeException>() { @Override public Iterable<NotificationEventModelDao> execute() throws RuntimeException { return new Iterable<NotificationEventModelDao>() { @Override public Iterator<NotificationEventModelDao> iterator() { return searchKey1 != null ? transactionalDao.getHistoricalQueueEntriesForSearchKeys(getFullQName(), searchKey1, searchKey2, config.getHistoryTableName()) : transactionalDao.getHistoricalQueueEntriesForSearchKey2(getFullQName(), minEffectiveDate, searchKey2, config.getHistoryTableName()); } }; } }); } private <T extends NotificationEvent> Iterable<NotificationEventWithMetadata<T>> toNotificationEventWithMetadata(final Iterable<NotificationEventModelDao> entries) { return Iterables.toStream(entries) .map(cur -> { final T event = EventEntryDeserializer.deserialize(cur, objectReader); return new NotificationEventWithMetadata<T>(cur.getRecordId(), cur.getUserToken(), cur.getCreatedDate(), cur.getSearchKey1(), cur.getSearchKey2(), event, cur.getFutureUserToken(), cur.getEffectiveDate(), cur.getQueueName()); }).collect(Collectors.toUnmodifiableList()); } @Override public long getNbReadyEntries(final DateTime maxCreatedDate) { return dao.getNbReadyEntries(maxCreatedDate.toDate()); } @Override public void removeNotification(final Long recordId) { final NotificationEventModelDao existing = dao.getSqlDao().getByRecordId(recordId, config.getTableName()); final NotificationEventModelDao removedEntry = new NotificationEventModelDao(existing, CreatorName.get(), clock.getUTCNow(), PersistentQueueEntryLifecycleState.REMOVED); dao.moveEntryToHistory(removedEntry); } @Override public void removeNotificationFromTransaction(final Connection connection, final Long recordId) { final InTransaction.InTransactionHandler<NotificationSqlDao, Void> handler = new InTransaction.InTransactionHandler<NotificationSqlDao, Void>() { @Override public Void withSqlDao(final NotificationSqlDao transactional) { final NotificationEventModelDao existing = transactional.getByRecordId(recordId, config.getTableName()); final NotificationEventModelDao removedEntry = new NotificationEventModelDao(existing, CreatorName.get(), clock.getUTCNow(), PersistentQueueEntryLifecycleState.REMOVED); dao.moveEntryToHistoryFromTransaction(transactional, removedEntry); return null; } }; InTransaction.execute(dbi, connection, handler, NotificationSqlDao.class); } @Override public void removeFutureNotificationsForSearchKeys(final Long searchKey1, final Long searchKey2) { dao.getSqlDao().inTransaction(new Transaction<Void, QueueSqlDao<NotificationEventModelDao>>() { @Override public Void inTransaction(final QueueSqlDao<NotificationEventModelDao> transactional, final TransactionStatus status) throws Exception { // Move entries by batch into the history table final int batchSize = 25; final Collection<NotificationEventModelDao> currentBatch = new ArrayList<NotificationEventModelDao>(batchSize); // Note that we don't claim them here, so it could be possible that some of these entries end up being processed nonetheless final Iterator<NotificationEventModelDao> futureQueueEntriesForSearchKeys = ((NotificationSqlDao) transactional).getReadyQueueEntriesForSearchKeys(getFullQName(), searchKey1, searchKey2, config.getTableName()); try { while (futureQueueEntriesForSearchKeys.hasNext()) { final NotificationEventModelDao notificationEventModelDao = futureQueueEntriesForSearchKeys.next(); notificationEventModelDao.setProcessingState(PersistentQueueEntryLifecycleState.REMOVED); currentBatch.add(notificationEventModelDao); if (currentBatch.size() >= batchSize || !futureQueueEntriesForSearchKeys.hasNext()) { dao.moveEntriesToHistoryFromTransaction(transactional, currentBatch); currentBatch.clear(); } } } finally { // This will go through all results to close the connection final int nbNotificationsLeft = Iterators.size(futureQueueEntriesForSearchKeys); if (nbNotificationsLeft > 0) { logger.warn("Unable to remove {} notifications for searchKey1={}, searchKey2={}", searchKey1, searchKey2); } } return null; } }); } @Override public String getFullQName() { return NotificationQueueServiceBase.getCompositeName(svcName, queueName); } @Override public String getServiceName() { return svcName; } @Override public String getQueueName() { return queueName; } @Override public NotificationQueueHandler getHandler() { return handler; } @Override public boolean initQueue() { if (config.isProcessingOff()) { logger.warn("Not initializing queue {} because of xxx.notification.off config", getFullQName()); return false; } if (!isInitialized.compareAndSet(false, true)) { return notificationQueueService.initQueue(); } else { return false; } } @Override public boolean startQueue() { if (config.isProcessingOff()) { logger.warn("Not starting queue {} because of xxx.notification.off config", getFullQName()); return false; } if (isStarted.compareAndSet(false, true)) { notificationQueueService.startQueue(); return true; } else { return false; } } @Override public boolean stopQueue() { if (isStarted.compareAndSet(true, false)) { isInitialized.set(false); return notificationQueueService.stopQueue(); } return true; } @Override public boolean isStarted() { return isStarted.get(); } @Override public String toString() { final StringBuilder sb = new StringBuilder("DefaultNotificationQueue{"); sb.append("svcName='").append(svcName).append('\''); sb.append(", queueName='").append(queueName).append('\''); sb.append('}'); return sb.toString(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/main/java/org/killbill/notificationq/dao/NotificationSqlDao.java
queue/src/main/java/org/killbill/notificationq/dao/NotificationSqlDao.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq.dao; import java.util.Iterator; import org.joda.time.DateTime; import org.killbill.commons.jdbi.statement.SmartFetchSize; import org.killbill.commons.jdbi.template.KillBillSqlDaoStringTemplate; import org.killbill.queue.dao.QueueSqlDao; import org.skife.jdbi.v2.sqlobject.Bind; import org.skife.jdbi.v2.sqlobject.SqlQuery; import org.skife.jdbi.v2.sqlobject.SqlUpdate; import org.skife.jdbi.v2.sqlobject.customizers.Define; @KillBillSqlDaoStringTemplate public interface NotificationSqlDao extends QueueSqlDao<NotificationEventModelDao> { @SqlQuery @SmartFetchSize(shouldStream = true) Iterator<NotificationEventModelDao> getReadyQueueEntriesForSearchKeys(@Bind("queueName") String queueName, @Bind("searchKey1") final Long searchKey1, @Bind("searchKey2") final Long searchKey2, @Define("tableName") final String tableName); @SqlQuery @SmartFetchSize(shouldStream = true) Iterator<NotificationEventModelDao> getReadyQueueEntriesForSearchKey2(@Bind("queueName") String queueName, @Bind("maxEffectiveDate") final DateTime maxEffectiveDate, @Bind("searchKey2") final Long searchKey2, @Define("tableName") final String tableName); @SqlQuery @SmartFetchSize(shouldStream = true) Iterator<NotificationEventModelDao> getReadyOrInProcessingQueueEntriesForSearchKeys(@Bind("queueName") String queueName, @Bind("searchKey1") final Long searchKey1, @Bind("searchKey2") final Long searchKey2, @Define("tableName") final String tableName); @SqlQuery @SmartFetchSize(shouldStream = true) Iterator<NotificationEventModelDao> getReadyOrInProcessingQueueEntriesForSearchKey2(@Bind("queueName") String queueName, @Bind("maxEffectiveDate") final DateTime maxEffectiveDate, @Bind("searchKey2") final Long searchKey2, @Define("tableName") final String tableName); @SqlQuery @SmartFetchSize(shouldStream = true) Iterator<NotificationEventModelDao> getHistoricalQueueEntriesForSearchKeys(@Bind("queueName") String queueName, @Bind("searchKey1") final Long searchKey1, @Bind("searchKey2") final Long searchKey2, @Define("historyTableName") final String historyTableName); @SqlQuery @SmartFetchSize(shouldStream = true) Iterator<NotificationEventModelDao> getHistoricalQueueEntriesForSearchKey2(@Bind("queueName") String queueName, @Bind("minEffectiveDate") final DateTime minEffectiveDate, @Bind("searchKey2") final Long searchKey2, @Define("historyTableName") final String historyTableName); @SqlUpdate void updateEntry(@Bind("recordId") Long id, @Bind("eventJson") String eventJson, @Bind("searchKey1") final Long searchKey1, @Bind("searchKey2") final Long searchKey2, @Define("tableName") final String tableName); }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/main/java/org/killbill/notificationq/dao/NotificationEventModelDao.java
queue/src/main/java/org/killbill/notificationq/dao/NotificationEventModelDao.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq.dao; import java.util.UUID; import org.joda.time.DateTime; import org.killbill.bus.dao.BusEventModelDao; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; public class NotificationEventModelDao extends BusEventModelDao { private UUID futureUserToken; private DateTime effectiveDate; private String queueName; public NotificationEventModelDao() { /* Default ctor for jdbi mapper */ } public NotificationEventModelDao(final long id, final String createdOwner, final String owner, final DateTime createdDate, final DateTime nextAvailable, final PersistentQueueEntryLifecycleState processingState, final String eventJsonClass, final String eventJson, final Long errorCount, final UUID userToken, final Long searchKey1, final Long searchKey2, final UUID futureUserToken, final DateTime effectiveDate, final String queueName) { super(id, createdOwner, owner, createdDate, nextAvailable, processingState, eventJsonClass, eventJson, errorCount, userToken, searchKey1, searchKey2); this.futureUserToken = futureUserToken; this.effectiveDate = effectiveDate; this.queueName = queueName; } public NotificationEventModelDao(final String createdOwner, final DateTime createdDate, final String eventJsonClass, final String eventJson, final UUID userToken, final Long searchKey1, final Long searchKey2, final UUID futureUserToken, final DateTime effectiveDate, final String queueName) { this(-1L, createdOwner, null, createdDate, null, PersistentQueueEntryLifecycleState.AVAILABLE, eventJsonClass, eventJson, 0L, userToken, searchKey1, searchKey2, futureUserToken, effectiveDate, queueName); } public NotificationEventModelDao(final NotificationEventModelDao in, final String owner, final DateTime nextAvailable, final PersistentQueueEntryLifecycleState state) { this(in.getRecordId(), in.getCreatingOwner(), owner, in.getCreatedDate(), nextAvailable, state, in.getClassName(), in.getEventJson(), in.getErrorCount(), in.getUserToken(), in.getSearchKey1(), in.getSearchKey2(), in.getFutureUserToken(), in.getEffectiveDate(), in.getQueueName()); } public NotificationEventModelDao(final NotificationEventModelDao in, final String owner, final DateTime nextAvailable, final PersistentQueueEntryLifecycleState state, final Long errorCount) { this(in.getRecordId(), in.getCreatingOwner(), owner, in.getCreatedDate(), nextAvailable, state, in.getClassName(), in.getEventJson(), errorCount, in.getUserToken(), in.getSearchKey1(), in.getSearchKey2(), in.getFutureUserToken(), in.getEffectiveDate(), in.getQueueName()); } public UUID getFutureUserToken() { return futureUserToken; } public void setFutureUserToken(final UUID futureUserToken) { this.futureUserToken = futureUserToken; } public DateTime getEffectiveDate() { return effectiveDate; } public void setEffectiveDate(final DateTime effectiveDate) { this.effectiveDate = effectiveDate; } public String getQueueName() { return queueName; } public void setQueueName(final String queueName) { this.queueName = queueName; } @Override public String toString() { final StringBuilder sb = new StringBuilder("NotificationEventModelDao{"); sb.append("recordId=").append(getRecordId()); sb.append(", className='").append(getClassName()).append('\''); sb.append(", eventJson='").append(getEventJson()).append('\''); sb.append(", userToken=").append(getUserToken()); sb.append(", createdDate=").append(getCreatedDate()); sb.append(", creatingOwner='").append(getCreatingOwner()).append('\''); sb.append(", processingOwner='").append(getProcessingOwner()).append('\''); sb.append(", processingAvailableDate=").append(getProcessingAvailableDate()); sb.append(", errorCount=").append(getErrorCount()); sb.append(", processingState=").append(getProcessingState()); sb.append(", searchKey1=").append(getSearchKey1()); sb.append(", searchKey2=").append(getSearchKey2()); sb.append(", futureUserToken=").append(futureUserToken); sb.append(", effectiveDate=").append(effectiveDate); sb.append(", queueName='").append(queueName).append('\''); sb.append('}'); return sb.toString(); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false
killbill/killbill-commons
https://github.com/killbill/killbill-commons/blob/9239f88b55d9255c172143bab180b7aa042fcd36/queue/src/main/java/org/killbill/notificationq/dispatching/NotificationCallableCallback.java
queue/src/main/java/org/killbill/notificationq/dispatching/NotificationCallableCallback.java
/* * Copyright 2010-2014 Ning, Inc. * Copyright 2014-2020 Groupon, Inc * Copyright 2020-2020 Equinix, Inc * Copyright 2014-2020 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.notificationq.dispatching; import org.joda.time.DateTime; import org.killbill.CreatorName; import org.killbill.notificationq.NotificationQueueDispatcher; import org.killbill.notificationq.NotificationQueueException; import org.killbill.notificationq.api.NotificationEvent; import org.killbill.notificationq.api.NotificationQueueService; import org.killbill.notificationq.dao.NotificationEventModelDao; import org.killbill.queue.api.PersistentQueueEntryLifecycleState; import org.killbill.queue.dispatching.CallableCallbackBase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NotificationCallableCallback extends CallableCallbackBase<NotificationEvent, NotificationEventModelDao> { private static final Logger log = LoggerFactory.getLogger(NotificationCallableCallback.class); private final NotificationQueueDispatcher parent; public NotificationCallableCallback(final NotificationQueueDispatcher parent) { super(parent.getDao(), parent.getClock(), parent.getConfig(), parent.getObjectReader()); this.parent = parent; } @Override public void dispatch(final NotificationEvent event, final NotificationEventModelDao modelDao) throws NotificationQueueException { final NotificationQueueService.NotificationQueueHandler handler = parent.getHandlerForActiveQueue(modelDao.getQueueName()); if (handler == null) { // Will increment errorCount and eventually move to history table. throw new IllegalStateException(String.format("Cannot find handler for notification: queue = %s, record_id = %s", modelDao.getQueueName(), modelDao.getRecordId())); } parent.handleNotificationWithMetrics(handler, modelDao, event); } @Override public NotificationEventModelDao buildEntry(final NotificationEventModelDao modelDao, final DateTime now, final PersistentQueueEntryLifecycleState newState, final long newErrorCount) { return new NotificationEventModelDao(modelDao, CreatorName.get(), now, newState, newErrorCount); } }
java
Apache-2.0
9239f88b55d9255c172143bab180b7aa042fcd36
2026-01-05T02:38:41.530814Z
false